Commit 9979beab authored by neo's avatar neo

Merge branch 'dev_oracle' of code.tech.tax.asia.pwcinternal.com:root/atms into neo_jpa_withoutgen

parents 6c96d113 060fafe6
This diff is collapsed.
package pwc.taxtech.atms;
import java.util.Arrays;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import pwc.taxtech.atms.security.JwtAuthenticationProvider;
import pwc.taxtech.atms.security.JwtAuthenticationToken;
import pwc.taxtech.atms.security.JwtUtil;
public abstract class CommonTestUtils {
public static void initTestAuth() {
Authentication request = new JwtAuthenticationToken("xxxx");
JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider();
JwtUtil jwtutil = new JwtUtil();
jwtutil.setJwtBase64Secret("testkey");
jwtutil.setJwtPowerToken("xxxx");
ReflectionTestUtils.setField(jwtAuthenticationProvider, "jwtUtil", jwtutil);
ProviderManager providerManager = new ProviderManager(Arrays.asList(jwtAuthenticationProvider));
Authentication authenticaiton = providerManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
}
}
package pwc.taxtech.atms;
import java.lang.reflect.Field;
public class FieldsCompare {
public static <S, D> void map(S source, D dest) throws ClassNotFoundException, IllegalAccessException {
Class destClass = Class.forName(dest.getClass().getName());
Class clsSource = Class.forName(source.getClass().getName());
Field[] declaredFields = destClass.getDeclaredFields();
Field[] clsFields = clsSource.getDeclaredFields();
System.out.println(destClass.getName());
System.out.println();
System.out.println(clsSource.getName());
System.out.println(clsFields.toString());
System.out.println(clsSource.getName() + ":" + clsFields.length);
System.out.println(destClass.getName() + ":" + declaredFields.length);
Field[] fieldsMax = null;
Field[] fieldsMin = null;
Class fieldsMaxClass = null;
Class fieldsMinClass = null;
if (declaredFields.length > clsFields.length) {
fieldsMax = declaredFields;
fieldsMin = clsFields;
fieldsMaxClass = destClass;
fieldsMinClass = clsSource;
} else {
fieldsMax = clsFields;
fieldsMaxClass = clsSource;
fieldsMin = declaredFields;
fieldsMinClass = destClass;
}
for (Field field : fieldsMax) {
field.setAccessible(true);
String fieldName = field.getName();
try {
if ("serialVersionUId".equals(fieldName)) {
continue;
}
fieldsMinClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
System.out.println("NoSuchFieldException " + fieldsMinClass.getName() + "." + fieldName);
}
}
for (Field field : fieldsMin) {
field.setAccessible(true);
String fieldName = field.getName();
try {
if ("serialVersionUId".equals(fieldName)) {
continue;
}
fieldsMaxClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
System.out.println("NoSuchFieldException " + fieldsMaxClass.getName() + "." + fieldName);
}
}
}
public static void main(String[] args) throws IllegalAccessException, ClassNotFoundException {
// map(new CompanyBalanceDto(), new CompanyBalance());
}
}
\ No newline at end of file
package pwc.taxtech.atms;
//import org.eclipse.jetty.server.Server;
//import org.eclipse.jetty.webapp.WebAppContext;
//import org.eclipse.jetty.websocket.jsr356.server.ServerContainer;
//import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
public class JettyLauncher {
public static void main(String[] args) {
// int port = 8180;
// Server server = new Server(port);
// WebAppContext webAppContext = new WebAppContext("webapp", "/");
//
// webAppContext.setDescriptor("webapp/WEB-INF/web.xml");
// webAppContext.setResourceBase("src/main/webapp");
// webAppContext.setDisplayName("atms-api");
// webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
// webAppContext.setConfigurationDiscovered(true);
// webAppContext.setParentLoaderPriority(true);
//
//
// server.setHandler(webAppContext);
// System.out.println(webAppContext.getContextPath());
// System.out.println(webAppContext.getDescriptor());
// System.out.println(webAppContext.getResourceBase());
// System.out.println(webAppContext.getBaseResource());
//
// try {
// ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(webAppContext);
// // Add WebSocket endpoint to javax.websocket layer
//// wscontainer.addEndpoint(MyWebSocket.class); //这行是如果需要使用websocket就加上,不需要就注释掉这行,mywebsocket是自己写的websocket服务类
//
// server.start();
// } catch (Exception e) {
// e.printStackTrace();
// }
// System.out.println("server is start, port is " + port + "............");
}
}
package pwc.taxtech.atms;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
String regex = "[A-Z]*\\([A-Za-z0-9\\\"\\,\\.\\u4e00-\\u9fa5\\%\\-]*\\)";
String forumula = "ND(2) +ND(1) +A2";
// 不以baidu开头的字符串 (?!SUM)[A-Z]+[0-9]+
String regex3 = "^(?!baidu).*$";
String regex2 = "[A-Z]+[0-9]+";
int count = 0;
Pattern p = Pattern.compile(regex2);
Matcher m = p.matcher(forumula);
while (m.find()) {
//如果有些公式无法用正则匹配,可以做特殊处理
System.out.println("匹配项" + count + ":" + m.group()); //group方法返回由以前匹配操作所匹配的输入子序列。
count++;
}
}
}
package pwc.taxtech.atms.common;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.security.JwtAuthenticationProvider;
import pwc.taxtech.atms.security.JwtAuthenticationToken;
public class AuthUserHelperIT extends CommonIT {
@Autowired
private AuthUserHelper authUserHelper;
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Before
public void init() {
Authentication request = new JwtAuthenticationToken("xxxx");
Authentication authenticaiton = jwtAuthenticationProvider.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
}
@Test
public void test() {
Assert.assertNotNull(SecurityContextHolder.getContext());
Assert.assertNotNull(SecurityContextHolder.getContext().getAuthentication());
Assert.assertNotNull(SecurityContextHolder.getContext().getAuthentication().getName());
Assert.assertNotNull(authUserHelper);
Assert.assertNotNull(authUserHelper.getCurrentAuditor());
System.out.println(authUserHelper.getCurrentAuditor());
}
}
package pwc.taxtech.atms.common;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import pwc.taxtech.atms.CommonTestUtils;
public class AuthUserHelperTest {
private AuthUserHelper authUserHelper = new AuthUserHelperImpl();
@Before
public void before() {
CommonTestUtils.initTestAuth();
}
@Test
public void test() {
String ipAddress = authUserHelper.getIpaddressFromSecurityContextHolder();
Assert.assertEquals("The ip does not match", "127.0.0.1", ipAddress);
}
}
package pwc.taxtech.atms.common;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.common.ftp.FtpService;
import java.io.File;
import java.io.FileInputStream;
public class FTPTest extends CommonIT {
@Autowired
FtpService ftpService;
@Test
public void test() {
try {
// FTPClient client = ftpClientPool.getClient();
// FTPClient client = null;
// client.listFiles("hhhhh/sss/ccc");
// client.makeDirectory("hhhhh/sss/ccc");
// client.changeWorkingDirectory("hhhhh/sss/ccc");
// client.storeFile("./aa/bb/cc/dd/text.txt", new FileInputStream(new File("C:\\temp/Fixed.txt")));
// System.out.println(client.listFiles().length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.common;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.entity.Stock;
public class JsonIT extends CommonIT {
@Autowired
private ObjectMapper objectMapper;
@Test
public void nullToString() throws JsonProcessingException {
System.out.println("############# PRINT START #################");
System.out.println(objectMapper.writeValueAsString(null));
System.out.println("############# PRINT END #################");
}
@Test
public void testNumber() throws JsonParseException, JsonMappingException, IOException {
Stock obj = new Stock();
BigDecimal capitalAmount = new BigDecimal("123456789012345678.888");
obj.setCapitalAmount(capitalAmount);
String jsonString = objectMapper.writeValueAsString(obj);
System.out.println(jsonString);
double d = 123456789012345678.888;
Map<String, Object> map = new HashMap<>();
map.put("key1", d);
System.out.println(objectMapper.writeValueAsString(map));
}
@Test
public void test() throws JsonParseException, JsonMappingException, IOException {
{
IdModel module = objectMapper.readValue("{\"id\":\"dummy\"}", IdModel.class);
Assert.assertEquals("dummy", module.getId());
}
{
IdModel module = objectMapper.readValue("{\"id\":\"dummy\"}", IdModel.class);
Assert.assertEquals("dummy", module.getId());
}
{
IdModel module = objectMapper.readValue("{\"id\":\"dummy\"}", IdModel.class);
Assert.assertEquals("dummy", module.getId());
}
{
IdModel module = objectMapper.readValue("{\"Id\":\"dummy\"}", IdModel.class);
Assert.assertEquals("dummy", module.getId());
}
}
public static class IdModel {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
package pwc.taxtech.atms.common;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyBatisGeneratorTest {
public static void main(String[] args) throws Exception {
try {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
//指定 逆向工程配置文件
File configFile = new File(MyBatisGeneratorTest.class.getClassLoader().getResource("generatorConfig.xml").getPath());
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.common;
import static org.mockito.Mockito.when;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MyServletContextListenerTest {
@InjectMocks
private MyServletContextListener myServletContextListener;
@Mock
private ServletContextEvent servletContextEvent;
@Mock
private ServletContext servletContext;
@Test
public void contextInitialized() {
when(servletContextEvent.getServletContext()).thenReturn(servletContext);
when(servletContext.getMajorVersion()).thenReturn(2);
when(servletContext.getMinorVersion()).thenReturn(5);
myServletContextListener.contextInitialized(servletContextEvent);
}
@Test
public void contextDestroyed() {
myServletContextListener.contextDestroyed(servletContextEvent);
}
}
package pwc.taxtech.atms.common;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.parser.pdf.PDFParserConfig;
import org.apache.tika.sax.BodyContentHandler;
import java.io.File;
import java.io.FileInputStream;
public class PDFTest {
public static void main(String[] args) {
try {
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File("C:\\woo\\test.pdf"));
ParseContext pcontext = new ParseContext();
PDFParser pdfparser = new PDFParser();
pdfparser.getPDFParserConfig().setSortByPosition(true);//参见底层实现
// pdfparser.getPDFParserConfig().setEnableAutoSpace(false);
// pdfparser.getPDFParserConfig().setAverageCharTolerance(1f);
// pdfparser.getPDFParserConfig().setSpacingTolerance(20f);
pdfparser.parse(inputstream, handler, metadata, pcontext);
System.out.println(handler.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.common;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
import org.apache.poi.ss.formula.udf.DefaultUDFFinder;
import org.apache.poi.ss.formula.udf.UDFFinder;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
public class POITest {
public static void main(String[] args) {
File workbookFile = new File("C:\\source\\test - Copy.xlsx");
try {
FileInputStream fis = new FileInputStream(workbookFile);
Workbook workbook = WorkbookFactory.create(fis);
String[] functionNames = {"TmpFunction"};
FreeRefFunction[] functionImpls = {new TmpFunction()};
UDFFinder udfs = new DefaultUDFFinder(functionNames, functionImpls);
UDFFinder udfToolpack = new AggregatingUDFFinder(udfs);
workbook.addToolPack(udfToolpack);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
int sheetNum = workbook.getNumberOfSheets();
Sheet st1 = workbook.getSheetAt(0);
for (int i = 0; i < 10; i++) {
if (st1.getRow(i) == null) {
st1.createRow(i);
for (int j = 0; j < 10; j++) {
if (st1.getRow(i).getCell(j) == null) {
st1.getRow(i).createCell(j).setCellFormula("TmpFunction(\"g2\","+j+")+B5-TmpFunction(\"g2\","+i+")");
}
}
}
}
st1.getRow(1).getCell(0).setCellType(CellType.NUMERIC);
st1.getRow(1).getCell(0).setCellValue(15);
evaluator.evaluateAll();
for (int i = 0; i < sheetNum; i++) {
Sheet tmpSheet = workbook.getSheetAt(i);
for (int r = tmpSheet.getFirstRowNum(); r <= tmpSheet.getLastRowNum(); r++) {
Row row = tmpSheet.getRow(r);
if (null == row) {
continue;
}
for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
System.out.println("row :" + r + " cell: " + c);
Cell tmp = row.getCell(c);
if (null != tmp && tmp.getCellTypeEnum().equals(CellType.FORMULA)) {
// CellValue v = evaluator.evaluate(tmp);
tmp.setCellType(CellType.NUMERIC);
tmp.setCellValue(tmp.getNumericCellValue());
}
}
}
}
FileOutputStream excelFileOutPutStream = new FileOutputStream("C:\\source\\test - Copy.xlsx");
workbook.write(excelFileOutPutStream);
excelFileOutPutStream.flush();
excelFileOutPutStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.common;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import pwc.taxtech.atms.dto.VMRegionDevTreeData;
import pwc.taxtech.atms.dto.navtree.DevTreeDto;
public class SortUtilsTest{
@Test
public void sortDevTreeDtoByTextTest() {
List<DevTreeDto<VMRegionDevTreeData>> devTree = new ArrayList<>();
DevTreeDto<VMRegionDevTreeData> o1 = new DevTreeDto<>();
o1.setText("111");
DevTreeDto<VMRegionDevTreeData> o2 = new DevTreeDto<>();
o2.setText("CBA");
DevTreeDto<VMRegionDevTreeData> o3 = new DevTreeDto<>();
o3.setText("abc");
DevTreeDto<VMRegionDevTreeData> o4 = new DevTreeDto<>();
o4.setText("直辖市");
DevTreeDto<VMRegionDevTreeData> o5 = new DevTreeDto<>();
o5.setText("大中华");
devTree.add(o1);devTree.add(o2);devTree.add(o3);devTree.add(o4);devTree.add(o5);
SortUtils.sortDevTreeDtoByText(devTree);
assertEquals("111", devTree.get(0).getText());
assertEquals("abc", devTree.get(1).getText());
assertEquals("CBA", devTree.get(2).getText());
assertEquals("大中华", devTree.get(3).getText());
assertEquals("直辖市", devTree.get(4).getText());
}
}
package pwc.taxtech.atms.common;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.StringUtils;
public class StringHelperTest {
@Test
public void getPwd() {
StringHelper stringHelper = new StringHelper();
Assert.assertTrue(StringUtils.hasText(stringHelper.generateRandomPassword()));
}
}
package pwc.taxtech.atms.common;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import java.io.*;
public class TikaTest {
public static void main(String[] args) {
try {
// Tika tika = new Tika();
File xpsFile = new File("C:\\woo\\海关稽核结果.xps");
InputStream inputStream = new FileInputStream(xpsFile);
// String FileName = xpsFile.getName();
// Metadata metadata = new Metadata();
// if (FileName != null && FileName.length() > 0)
// metadata.add(Metadata.RESOURCE_NAME_KEY, FileName);
// String MimeType = tika.detect(inputStream, metadata);
//
// metadata.add(Metadata.CONTENT_TYPE, MimeType);
// inputStream.close();
// inputStream = new FileInputStream(xpsFile);
// Reader reader = tika.parse(inputStream, metadata);
// String content = IOUtils.toString(reader);
// inputStream.close();
Metadata metadata = new Metadata();
ContentHandler handler = new BodyContentHandler();
new TmpXPSParser().parse(inputStream, handler, metadata, new ParseContext());
String content = handler.toString();
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package pwc.taxtech.atms.common;
import org.apache.poi.ss.formula.OperationEvaluationContext;
import org.apache.poi.ss.formula.eval.*;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
import org.apache.poi.ss.util.CellReference;
/*
TmpFunction("g2",5)
*/
public class TmpFunction implements FreeRefFunction {
@Override
public ValueEval evaluate(ValueEval[] valueEvals, OperationEvaluationContext operationEvaluationContext) {
// if (valueEvals.length != 3) {
// return ErrorEval.VALUE_INVALId;
// }
try {
ValueEval v1 = OperandResolver.getSingleValue(valueEvals[0],
operationEvaluationContext.getRowIndex(),
operationEvaluationContext.getColumnIndex());
ValueEval v2 = OperandResolver.getSingleValue(valueEvals[1],
operationEvaluationContext.getRowIndex(),
operationEvaluationContext.getColumnIndex());
String val1 = OperandResolver.coerceValueToString(v1);
int val2 = OperandResolver.coerceValueToInt(v2);
CellReference reference = new CellReference(val1);
int referenceSheetIndex = operationEvaluationContext.getWorkbook().getSheetIndex(reference.getSheetName());
return new NumberEval(operationEvaluationContext.getWorkbook()
.getSheet(referenceSheetIndex)
.getCell(reference.getRow(), reference.getCol())
.getNumericCellValue()
+ val2);
} catch (EvaluationException e) {
e.printStackTrace();
}
return null;
}
}
package pwc.taxtech.atms.common;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javaaxp.core.service.IXPSAccess;
import javaaxp.core.service.IXPSPageAccess;
import javaaxp.core.service.XPSError;
import javaaxp.core.service.impl.XPSServiceImpl;
import javaaxp.core.service.impl.document.jaxb.CTCanvas;
import javaaxp.core.service.impl.document.jaxb.CTGlyphs;
import javaaxp.core.service.impl.document.jaxb.CTPath;
import javaaxp.core.service.model.document.page.IFixedPage;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class TmpXPSParser implements Parser {
private double currentXPosition = 0;
/**
*
*/
private static final long serialVersionUId = -3528366722867144747L;
private static final Set<MediaType> SUPPORTED_TYPES =
Collections.singleton(MediaType.application("vnd.ms-xpsdocument"));
private static final String XPS_MIME_TYPE = "application/vnd.ms-xpsdocument";
private XHTMLContentHandler fileXHTML;
public Set<MediaType> getSupportedTypes(ParseContext context) {
return SUPPORTED_TYPES;
}
public void parse(
InputStream stream, ContentHandler handler,
Metadata metadata, ParseContext context)
throws IOException, SAXException, TikaException {
metadata.set(Metadata.CONTENT_TYPE, XPS_MIME_TYPE);
fileXHTML = new XHTMLContentHandler(handler, metadata);
try {
parseXPS(stream);
} catch (XPSError e) {
throw new IOException(e);
}
stream.close();
}
private void parseXPS(InputStream inputStream) throws XPSError, SAXException {
IXPSAccess xpsAccess = XPSServiceImpl.getInstance().getXPSAccess(inputStream);
xhtmlStartDocument();
int firstDocNum = xpsAccess.getDocumentAccess().getFirstDocNum();
int lastDocNum = xpsAccess.getDocumentAccess().getLastDocNum();
for (int i = firstDocNum; i <= lastDocNum; i++) {
IXPSPageAccess xpsPageAccess = xpsAccess.getPageAccess(i);
int firstPageNum = xpsPageAccess.getFirstPageNum();
int lastPageNum = xpsPageAccess.getLastPageNum();
for (int j = firstPageNum; j <= lastPageNum; j++) {
IFixedPage fixedPage = xpsPageAccess.getPage(j);
parseObjs(fixedPage.getPathOrGlyphsOrCanvas());
}
}
xhtmlEndDocument();
}
private void parseObjs(List<Object> objs) throws XPSError, SAXException {
for (Object o : objs)
parseObj(o);
}
private void parseObj(Object xpsObj) throws XPSError, SAXException {
if (xpsObj instanceof CTCanvas) {
CTCanvas c = (CTCanvas) xpsObj;
xhtmlStartCanvas();
parseObjs(c.getPathOrGlyphsOrCanvas());
xhtmlEndCanvas();
} else if (xpsObj instanceof CTGlyphs) {
CTGlyphs c = (CTGlyphs) xpsObj;
if (c.getOriginX() < currentXPosition) {
fileXHTML.startElement("div");
fileXHTML.characters(" ");
fileXHTML.endElement("div");
}
String text = c.getUnicodeString();
xhtmlParagraph(text);
currentXPosition = c.getOriginX();
} else if (xpsObj instanceof CTPath) {
} else {
System.out.println("Unhandled type : " + xpsObj.getClass().getCanonicalName());
}
}
private void xhtmlStartDocument() throws SAXException {
fileXHTML.startDocument();
}
private void xhtmlEndDocument() throws SAXException {
fileXHTML.endDocument();
}
private void xhtmlStartCanvas() throws SAXException {
fileXHTML.startElement("div");
}
private void xhtmlEndCanvas() throws SAXException {
fileXHTML.endElement("div");
}
private void xhtmlParagraph(String text) throws SAXException {
fileXHTML.startElement("span");
fileXHTML.characters(text);
fileXHTML.endElement("span");
}
/**
* @deprecated This method will be removed in Apache Tika 1.0.
*/
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
parse(stream, handler, metadata, new ParseContext());
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dto.LoginOutputDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.user.UserPasswordDto;
import pwc.taxtech.atms.service.UserAccountService;
@RunWith(MockitoJUnitRunner.class)
public class AccountControllerTest {
// @Mock
// private UserService userService;
@Mock
private UserAccountService userAccountService;
@InjectMocks
private AccountController accountController;
@Test
public void nullResult() {
UserPasswordDto userPasswordDto = new UserPasswordDto();
assertThat(accountController.changeExternalUserPassword(userPasswordDto)).isNull();
}
@Test
public void notNullResult() {
UserPasswordDto userPasswordDto = new UserPasswordDto();
when(userAccountService.changeExternalUserPassword(userPasswordDto))
.thenReturn(new OperationResultDto<LoginOutputDto>());
assertThat(accountController.changeExternalUserPassword(userPasswordDto)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.AreaDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.service.AreaService;
@RunWith(MockitoJUnitRunner.class)
public class AreaControllerTest {
@Mock
private AreaService areaService;
@InjectMocks
private AreaController areaController = new AreaController();
@Test
public void setIsActiveNotNullResult() {
AreaDto areaDto = new AreaDto();
areaDto.setId(CommonUtils.getUUID());
areaDto.setIsActive(CommonConstants.ACTIVE_STATUS);
areaDto.setName("areaNotNull");
OperationResultDto<List<String>> operationResultDto = new OperationResultDto<>();
when(areaService.setIsActive(areaDto)).thenReturn(operationResultDto);
assertThat(areaController.setIsActive(areaDto)).isNotNull();
}
@Test
public void getAreaListTest() {
when(areaService.getAreaList(1)).thenReturn(new ArrayList<>());
assertThat(areaController.getAreaList(1)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.arearegion.AreaRegionInfo;
import pwc.taxtech.atms.service.AreaRegionService;
@RunWith(MockitoJUnitRunner.class)
public class AreaRegionControllerTest {
@Mock
private AreaRegionService areaRegionService;
@InjectMocks
private AreaRegionController areaRegionController = new AreaRegionController();
@Test
public void addNotNullResult() {
AreaRegionInfo areaRegionInfo = new AreaRegionInfo();
areaRegionInfo.setName("areaNotNull");
areaRegionInfo.setParentId(CommonUtils.getUUID());
OperationResultDto<?> operationResultDto = new OperationResultDto<>();
when(areaRegionService.add(areaRegionInfo)).thenReturn(operationResultDto);
assertThat(areaRegionController.add(areaRegionInfo)).isNotNull();
}
@Test
public void updateNotNullResult() {
AreaRegionInfo areaRegionInfo = new AreaRegionInfo();
areaRegionInfo.setName("areaNotNull");
areaRegionInfo.setParentId(CommonUtils.getUUID());
OperationResultDto<?> operationResultDto = new OperationResultDto<>();
when(areaRegionService.update(areaRegionInfo)).thenReturn(operationResultDto);
assertThat(areaRegionController.update(areaRegionInfo)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.BusinessUnitDto;
import pwc.taxtech.atms.dto.IdModel;
import pwc.taxtech.atms.service.BusinessUnitService;
@RunWith(MockitoJUnitRunner.class)
public class BusinessUnitControllerTest {
@Mock
private BusinessUnitService businessUnitService;
@InjectMocks
private BusinessUnitController businessUnitController = new BusinessUnitController();
@Test
public void getBusinessUnitsNotNullResult() {
List<BusinessUnitDto> businessUnitDtos = new ArrayList<>();
when(businessUnitService.getBusinessUnits()).thenReturn(businessUnitDtos);
assertThat(businessUnitController.getBusinessUnits()).isNotNull();
}
@Test
public void updateBusinessUnitsNotNullResult() {
List<BusinessUnitDto> businessUnitDtos = new ArrayList<>();
BusinessUnitDto businessUnitDto = new BusinessUnitDto();
businessUnitDto.setId(CommonUtils.getUUID());
businessUnitDto.setIsActive(true);
businessUnitDto.setName("businessUnitNotNull");
businessUnitDtos.add(businessUnitDto);
when(businessUnitService.updateBusinessUnits(businessUnitDtos)).thenReturn(true);
assertThat(businessUnitController.updateBusinessUnits(businessUnitDtos)).isNotNull();
}
@Test
public void deleteBusinessUnitNotNullResult() {
IdModel idModel = new IdModel();
idModel.setId(CommonUtils.getUUID());
when(businessUnitService.deleteBusinessUnit(idModel)).thenReturn(1);
assertThat(businessUnitController.deleteBusinessUnit(idModel)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.customer.CustomerDto;
import pwc.taxtech.atms.dto.customer.CustomerValidateInfoDto;
import pwc.taxtech.atms.service.CustomerService;
@RunWith(MockitoJUnitRunner.class)
public class CustomerControllerTest {
@Mock
private CustomerService customerService;
@Mock
private CommonsMultipartFile commonsMultipartFile;
@InjectMocks
private CustomerController customerController;
@Test
public void addRangeNotNullResult() {
List<CustomerDto> customerDtoList = new ArrayList<>();
CustomerDto customerDto = new CustomerDto();
customerDto.setId(CommonUtils.getUUID());
customerDto.setName("customer-name");
customerDto.setCode("customer-code");
customerDto.setEnterPriseAccountId(CommonUtils.getUUID());
customerDtoList.add(customerDto);
List<OperationResultDto<CustomerDto>> operationResultDtoList = new ArrayList<>();
when(customerService.addRange(customerDtoList)).thenReturn(operationResultDtoList);
assertThat(customerController.addRange(customerDtoList)).isNotNull();
}
@Test
public void getByIdNotNullResult() {
String setId = CommonUtils.getUUID();
when(customerService.getByEnterpriseAccountSetId(setId)).thenReturn(new CustomerValidateInfoDto());
assertThat(customerController.getById(setId)).isNotNull();
}
@Test
public void getNotNullResult() {
List<CustomerDto> customerDtoList = new ArrayList<>();
when(customerService.getCustomer()).thenReturn(customerDtoList);
assertThat(customerController.getCustomer()).isNotNull();
}
@Test
public void deleteRangeNotNullResult() {
List<CustomerDto> customerDtoList = new ArrayList<>();
CustomerDto customerDto = new CustomerDto();
customerDto.setId(CommonUtils.getUUID());
customerDto.setName("customer-name");
customerDto.setCode("customer-code");
customerDto.setEnterPriseAccountId(CommonUtils.getUUID());
customerDtoList.add(customerDto);
OperationResultDto<String> operationResultDto = new OperationResultDto<>();
when(customerService.deleteRange(customerDtoList)).thenReturn(operationResultDto);
assertThat(customerController.deleteRange(customerDtoList)).isNotNull();
}
@Test
public void updateRangeNotNullResult() {
List<CustomerDto> customerDtoList = new ArrayList<>();
CustomerDto customerDto = new CustomerDto();
customerDto.setId(CommonUtils.getUUID());
customerDto.setName("customer-name");
customerDto.setCode("customer-code");
customerDto.setEnterPriseAccountId(CommonUtils.getUUID());
customerDtoList.add(customerDto);
List<OperationResultDto<CustomerDto>> operationResultDtoList = new ArrayList<>();
when(customerService.updateRange(customerDtoList)).thenReturn(operationResultDtoList);
assertThat(customerController.updateRange(customerDtoList)).isNotNull();
}
@SuppressWarnings("rawtypes")
@Test
public void uploadNullFile() {
CommonsMultipartFile inputFile = null;
String enterpriseAccountId = "enterpriseAccountId1";
String action = "1";
Object obj = customerController.upload(inputFile, enterpriseAccountId, action);
OperationResultDto result = (OperationResultDto) obj;
Assert.assertEquals(Boolean.FALSE, result.getResult());
}
@Test
public void uploadFile() {
String enterpriseAccountId = "enterpriseAccountId1";
String action = "1";
when(commonsMultipartFile.getSize()).thenReturn(1L);
Object obj = customerController.upload(commonsMultipartFile, enterpriseAccountId, action);
Assert.assertNull(obj);
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.service.DimensionService;
@RunWith(MockitoJUnitRunner.class)
public class DimensionControllerTest {
@Mock
private DimensionService dimensionService;
@InjectMocks
private DimensionController dimensionController;
@Test
public void emptyResult() {
assertThat(dimensionController.getDimensionStatics()).isEmpty();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dto.MenuDisplayDto;
import pwc.taxtech.atms.dto.MenuDto;
import pwc.taxtech.atms.service.MenuService;
@RunWith(MockitoJUnitRunner.class)
public class MenuControllerTest {
@Mock
private MenuService menuService;
@InjectMocks
private MenuController menuController = new MenuController();
@Test
public void getMenusForDisplayNotNull() {
List<MenuDisplayDto> menuDisplayDtos = new ArrayList<>();
Integer moduleId = 1;
when(menuService.getMenusForDisplay(moduleId)).thenReturn(menuDisplayDtos);
assertThat(menuController.getMenusForDisplay(moduleId)).isNotNull();
}
@Test
public void getMenusNotNull() {
List<MenuDto> menuDtos = new ArrayList<>();
Integer moduleId = 1;
when(menuService.getMenus(moduleId)).thenReturn(menuDtos);
assertThat(menuController.getMenus(moduleId)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dto.OperationLogDto;
import pwc.taxtech.atms.dto.PagingResultDto;
import pwc.taxtech.atms.dto.QueryOperateParamDto;
import pwc.taxtech.atms.service.OperationLogService;
@RunWith(MockitoJUnitRunner.class)
public class OperationLogTest {
@Mock
private OperationLogService operationLogService;
@InjectMocks
private OperationLogController operationLogController = new OperationLogController();
@Test
public void getOperationLogListNotNullResult() {
QueryOperateParamDto queryOperateParamDto = new QueryOperateParamDto();
PagingResultDto<OperationLogDto> pagingResultDto = new PagingResultDto<>();
when(operationLogService.getOperationLogList(queryOperateParamDto)).thenReturn(pagingResultDto);
assertThat(operationLogController.getOperationLogList(queryOperateParamDto)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dpo.OrganizationDto;
import pwc.taxtech.atms.dto.navtree.NavTreeDto;
import pwc.taxtech.atms.dto.organization.DimensionRoleDto;
import pwc.taxtech.atms.service.OrganizationService;
import pwc.taxtech.atms.service.UserRoleService;
import pwc.taxtech.atms.service.UserService;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class OrganizationControllerTest {
@Mock
private OrganizationService organizationService;
@Mock
private UserRoleService userRoleService;
@Mock
private UserService userService;
@InjectMocks
private OrganizationController organizationController = new OrganizationController();
@Test
public void getOrganizationFilterListTest() {
List<OrganizationDto> organizationDtoList = new ArrayList<>();
when(organizationService.getOrganizationFilterList()).thenReturn(organizationDtoList);
assertThat(organizationController.getOrganizationFilterList()).isNotNull();
}
@Test
public void getOrgListToJsonTest() {
List<NavTreeDto> navTreeDtos = new ArrayList<>();
Integer useType = 0;
when(organizationService.getOrgListToJson(useType)).thenReturn(navTreeDtos);
assertThat(organizationController.getOrgListToJson(useType)).isNotNull();
}
@Test
public void getOrgListTest() {
List<OrganizationDto> organizationDtos = new ArrayList<>();
Integer useType = 0;
when(organizationService.getOrgList(useType)).thenReturn(organizationDtos);
assertThat(organizationController.getOrgList(useType)).isNotNull();
}
@Test
public void getOrgBuAreaIndustryUserTest() {
List<DimensionRoleDto> dimensionRoleDtos = new ArrayList<>();
when(userRoleService.getOrgBuAreaIndustryUser("userId")).thenReturn(dimensionRoleDtos);
assertThat(organizationController.getOrgBuAreaIndustryUser("userId")).isNotNull();
}
@Test
public void deleteUserDimensionValueTest() {
DimensionRoleDto dto = new DimensionRoleDto();
assertThat(organizationController.deleteUserDimensionValue(dto, "userId")).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.OrganizationStructureDto;
import pwc.taxtech.atms.dto.OrganizationStructureInputDto;
import pwc.taxtech.atms.dto.customer.CustomerDto;
import pwc.taxtech.atms.dto.customer.CustomerValidateInfoDto;
import pwc.taxtech.atms.service.CustomerService;
import pwc.taxtech.atms.service.OrganizationStructureService;
@RunWith(MockitoJUnitRunner.class)
public class OrganizationStructureControllerTest {
@Mock
private OrganizationStructureService organizationStructureService;
@InjectMocks
private OrganizationStructureController organizationStructureController = new OrganizationStructureController();
@Test
public void addRangeNotNullResult() {
List<OrganizationStructureDto> organizationStructureDtoList = new ArrayList<>();
when(organizationStructureService.getOrganizationStructures()).thenReturn(organizationStructureDtoList);
assertThat(organizationStructureController.getOrganizationStructures()).isNotNull();
}
@Test
public void addOrganizationStructuresNotNullResult() {
List<OrganizationStructureInputDto> organizationStructureDtoList = new ArrayList<>();
OrganizationStructureInputDto organizationStructureDto = new OrganizationStructureInputDto();
organizationStructureDto.setId(CommonUtils.getUUID());
organizationStructureDto.setIsActive(true);
organizationStructureDto.setName("organization-tructure-name");
organizationStructureDtoList.add(organizationStructureDto);
when(organizationStructureService.updateOrganizationStructures(organizationStructureDtoList)).thenReturn(true);
assertThat(organizationStructureController.updateOrganizationStructure(organizationStructureDtoList)).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dto.navtree.DevTreeDto;
import pwc.taxtech.atms.dto.navtree.RolePermissionDisplayDto;
import pwc.taxtech.atms.service.PermissionService;
@RunWith(MockitoJUnitRunner.class)
public class PermissionControllerTest {
@Mock private PermissionService permissionService;
@InjectMocks
private PermissionController permissionController = new PermissionController();
@Test
public void getIvhTreePermissionsByRoleIdTest() {
when(permissionService.getIvhTreePermissionsByRoleId("id", "serviceType")).thenReturn(new RolePermissionDisplayDto());
assertThat(permissionController.getIvhTreePermissionsByRoleId("id", "serviceType")).isNotNull();
}
@Test
public void getIvhTreePermissionsByRoleIdListTest() {
when(permissionService.getIvhTreePermissionsByRoleIdList(Arrays.asList("Id1","Id2"), "serviceType")).thenReturn(new ArrayList<DevTreeDto>());
assertThat(permissionController.getIvhTreePermissionsByRoleIdList(Arrays.asList("Id1","Id2"), "serviceType")).isNotNull();
}
@Test
public void getAllPermissionsTest() {
when(permissionService.getAllPermissions("serviceType")).thenReturn(new ArrayList<DevTreeDto>());
assertThat(permissionController.getAllPermissions("serviceType")).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dto.VMRegionDevTreeData;
import pwc.taxtech.atms.dto.navtree.DevTreeDto;
import pwc.taxtech.atms.dto.navtree.IvhTreeDto;
import pwc.taxtech.atms.entity.Region;
import pwc.taxtech.atms.service.RegionService;
@RunWith(MockitoJUnitRunner.class)
public class RegionControllerTest {
@Mock
private RegionService regionService;
@InjectMocks
private RegionController regionController = new RegionController();
@Test
public void getSettingRegionTreeNotNullResult() {
List<DevTreeDto<VMRegionDevTreeData>> devTreeDto = new ArrayList<>();
when(regionService.getRegionAreaTree()).thenReturn(devTreeDto);
assertThat(regionController.getSettingRegionTree()).isNotNull();
}
@Test
public void getProvinceAndCityTreeListNotNullResult() {
List<DevTreeDto<IvhTreeDto<Region>>> devTreeDto = new ArrayList<>();
when(regionService.getProvinceAndCityTreeList()).thenReturn(devTreeDto);
assertThat(regionController.getProvinceAndCityTreeList()).isNotNull();
}
@SuppressWarnings("rawtypes")
@Test
public void getAreRegionTreeByNodeIdTest() {
List<DevTreeDto> devTreeDto = new ArrayList<>();
when(regionService.getAreaRegionTreeByNodeId("1")).thenReturn(devTreeDto);
assertThat(regionController.getAreRegionTreeByNodeId("1")).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dpo.UserRoleInfo;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.RoleCategoryDto;
import pwc.taxtech.atms.dto.navtree.NavTreeDto;
import pwc.taxtech.atms.dto.role.RoleDisplayDto;
import pwc.taxtech.atms.dto.role.RoleDto;
import pwc.taxtech.atms.dto.role.RoleDtoTree;
import pwc.taxtech.atms.dto.user.DimensionRole;
import pwc.taxtech.atms.dto.user.DimensionUser;
import pwc.taxtech.atms.dto.user.UserRoleDimensionValueDto;
import pwc.taxtech.atms.dto.user.UserRoleDto;
import pwc.taxtech.atms.dto.user.UserRoleUpdateDto;
import pwc.taxtech.atms.entity.RoleCategory;
import pwc.taxtech.atms.service.RoleService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RoleControllerTest {
@Mock
private RoleService roleService;
@InjectMocks
private RoleController roleController = new RoleController();
@Test
public void getRoleTreeListNotNull() {
List<NavTreeDto> navTreeDtos = new ArrayList<>();
when(roleService.getRoleTreeList()).thenReturn(navTreeDtos);
assertThat(roleController.getRoleTreeList()).isNotNull();
}
@Test
public void commonCopyPropertiesTest() {
RoleCategory roleCategory = new RoleCategory();
roleCategory.setIsActive(false);
RoleCategoryDto roleCategoryDto = new RoleCategoryDto();
CommonUtils.copyProperties(roleCategory, roleCategoryDto);
Short short1 = 0;
Assert.assertEquals(roleCategoryDto.getIsActive(), short1);
roleCategory.setIsActive(true);
CommonUtils.copyProperties(roleCategory, roleCategoryDto);
Short short2 = 1;
Assert.assertEquals(roleCategoryDto.getIsActive(), short2);
}
@Test
public void testFindFirst() {
NavTreeDto navTreeDto = new NavTreeDto();
navTreeDto.setLabel("test");
List<NavTreeDto> navTreeDtos = new ArrayList<>();
navTreeDtos.add(navTreeDto);
Boolean findNav = navTreeDtos.stream().filter(oneNav -> oneNav.getLabel().equals("good")).findFirst()
.isPresent();
Boolean findNav2 = navTreeDtos.stream().anyMatch(oneNav -> oneNav.getLabel().equals("test"));
Assert.assertFalse(findNav);
Assert.assertTrue(findNav2);
List<NavTreeDto> list = navTreeDtos.stream().filter(oneNav -> oneNav.getLabel().equals("good"))
.collect(Collectors.toList());
Assert.assertTrue(list.isEmpty());
}
@Test
public void getAllOwnUserRoleListNotNull() {
List<UserRoleInfo> userRoleInfos = new ArrayList<>();
when(roleService.getAllOwnUserRoleList()).thenReturn(userRoleInfos);
assertThat(roleController.getAllOwnUserRoleList()).isNotNull();
}
@Test
public void getAllUserRoleListNotNull() {
List<UserRoleInfo> userRoleInfos = new ArrayList<>();
when(roleService.getAllUserRoleList()).thenReturn(userRoleInfos);
assertThat(roleController.getAllUserRoleList()).isNotNull();
}
@Test
public void getAllRoleListByUserIdTest() {
Map<String, String> aMap = new HashMap<>();
aMap.put("123", "456");
Map<String, String> bMap = new HashMap<>();
bMap.put("123", "456");
List<Map<String, String>> list = new ArrayList<>();
list.add(aMap);
list.add(bMap);
list = list.stream().distinct().collect(Collectors.toList());
Assert.assertEquals(1, list.size());
List<UserRoleDto> userRoleDtos = new ArrayList<>();
when(roleService.getAllRoleListByUserId("userId", "serviceTypeId")).thenReturn(userRoleDtos);
assertThat(roleController.getAllRoleListByUserId("userId", "serviceTypeId")).isNotNull();
}
@Test
public void getRoleListTest() {
List<RoleDtoTree> roleDtoTrees = new ArrayList<>();
when(roleService.getRoleList()).thenReturn(roleDtoTrees);
assertThat(roleController.getRoleList()).isNotNull();
}
@Test
public void getUsersByRoleIdTest() {
List<UserRoleDto> userList = new ArrayList<>();
when(roleService.getUsersByRoleId("roleId")).thenReturn(userList);
assertThat(roleController.getUsersByRoleId("roleId")).isNotNull();
}
@Test
public void getExtraUsersByRoleIdTest() {
List<UserRoleDto> userList = new ArrayList<>();
when(roleService.getExtraUsersByRoleId("roleId")).thenReturn(userList);
assertThat(roleController.getExtraUsersByRoleId("roleId")).isNotNull();
}
@Test
public void removeUserRoleTest() {
assertThat(roleController.removeUserRole("userId", Arrays.asList("roleId"), "2")).isTrue();
}
@Test
public void getRoleListByRoleTypeTest() {
List<RoleDto> roleList = new ArrayList<>();
when(roleService.getRoleListByRoleType("2")).thenReturn(roleList);
assertThat(roleController.getRoleListByRoleType("2")).isNotNull();
}
@Test
public void addRoleCategoryTest() {
assertThat(roleController.addRoleCategory("name", "id")).isTrue();
}
@Test
public void updateRoleCategoryTest() {
assertThat(roleController.updateRoleCategory("name", "id")).isTrue();
}
@Test
public void deleteRoleCategoryTest() {
when(roleService.deleteRoleCategory("id")).thenReturn(new OperationResultDto());
assertThat(roleController.deleteRoleCategory("id")).isNotNull();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void addRoleTestWhenRoleNameDuplicate() {
RoleDisplayDto roleDto = new RoleDisplayDto();
Map result = new HashMap();
result.put("data", -1);
when(roleService.addRole(roleDto)).thenReturn("-1");
assertThat(roleController.addRole(roleDto)).isEqualTo(result);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void addRoleTest() {
RoleDisplayDto roleDto = new RoleDisplayDto();
Map result = new HashMap();
result.put("data", new ArrayList<RoleDtoTree>());
when(roleService.addRole(roleDto)).thenReturn("roleId");
assertThat(roleController.addRole(roleDto)).isEqualTo(result);
}
@Test
public void validateRoleNameUniqueTest() {
when(roleService.validateRoleNameUnique("roleName", "oldRoleName")).thenReturn(true);
assertThat(roleController.validateRoleNameUnique("roleName", "oldRoleName")).isTrue();
}
@Test
public void checkExistReferenceTest() {
when(roleService.checkUserRole("roleId")).thenReturn(true);
assertThat(roleController.checkExistReference("roleId")).isTrue();
}
@Test
public void deleteRoleTest() {
RoleDto roleDto = new RoleDto();
when(roleService.getRoleList()).thenReturn(new ArrayList<RoleDtoTree>());
assertThat(roleController.deleteRole(roleDto)).isNotNull();
}
@Test
public void getUserRoleListTest() {
UserRoleDimensionValueDto userRoleDimensionValueDto = new UserRoleDimensionValueDto();
when(roleService.getUserRoleList(userRoleDimensionValueDto)).thenReturn(new ArrayList<>());
assertThat(roleController.getUserRoleList(userRoleDimensionValueDto.getOrganizationId(),
userRoleDimensionValueDto.getDimensionId(), userRoleDimensionValueDto.getDimensionValueId()))
.isNotNull();
}
@Test
public void getAllRolePermissionTest() {
when(roleService.getAllRolePermission("2")).thenReturn(new ArrayList<>());
assertThat(roleController.getAllRolePermission("2")).isNotNull();
}
@Test
public void updateUserRoleTest() {
assertThat(roleController.updateUserRole(new UserRoleUpdateDto())).isTrue();
}
@Test
public void getDimensionRoleUserListTest() {
List<DimensionRole> dimensionRoles = new ArrayList<>();
when(roleService.getDimensionRoleUserList("1", "2")).thenReturn(dimensionRoles);
assertThat(roleController.getDimensionRoleUserList("1", "2")).isNotNull();
}
@Test
public void getDimensionUserRoleListTest() {
List<DimensionUser> dimensionUsers = new ArrayList<>();
when(roleService.getDimensionUserRoleList("1", "2")).thenReturn(dimensionUsers);
assertThat(roleController.getDimensionUserRoleList("1", "2")).isNotNull();
}
@Test
public void getActiveUserRoleListByAreaIdTest() {
List<UserRoleInfo> userRoleInfos = new ArrayList<>();
when(roleService.getActiveUserRoleListByAreaId("1")).thenReturn(userRoleInfos);
assertThat(roleController.getActiveUserRoleListByAreaId("1")).isNotNull();
}
}
package pwc.taxtech.atms.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import pwc.taxtech.atms.dpo.StatisticAttributeDisplayDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.StatisticAttributeDto;
import pwc.taxtech.atms.service.StatisticAttributeService;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StatisticAttributeControllerTest {
@Mock
private StatisticAttributeService statisticAttributeService;
@InjectMocks
private StatisticAttributeController statisticAttributeController = new StatisticAttributeController();
@Test
public void getByParentDimensionIdTest() {
List<StatisticAttributeDisplayDto> statisticAttributeDisplayDtos = new ArrayList<>();
when(statisticAttributeService.getStatisticAttributeListByDimensionId("1", null))
.thenReturn(statisticAttributeDisplayDtos);
assertThat(statisticAttributeController.getDimensionStatics("1")).isNotNull();
}
@Test
public void getStatisticAttributeListTest() {
List<StatisticAttributeDto> statisticAttributeDisplayDtos = new ArrayList<>();
when(statisticAttributeService.getStatisticAttributeList("1")).thenReturn(statisticAttributeDisplayDtos);
assertThat(statisticAttributeController.getStatisticAttributeList("1")).isNotNull();
}
@SuppressWarnings("rawtypes")
@Test
public void updateDimensionTest() {
OperationResultDto operationResultDto = new OperationResultDto();
List<StatisticAttributeDisplayDto> modelList = new ArrayList<>();
when(statisticAttributeService.updateStatisticAttribute(modelList)).thenReturn(operationResultDto);
assertThat(statisticAttributeController.updateDimension(modelList)).isNotNull();
}
@Test
public void getOrgSubChildrenStatAttributeListTest() {
List<StatisticAttributeDisplayDto> statisticAttributeDisplayDtos = new ArrayList<>();
when(statisticAttributeService.getOrgSubChildrenStatAttributeList("1"))
.thenReturn(statisticAttributeDisplayDtos);
assertThat(statisticAttributeController.getOrgSubChildrenStatAttributeList("1")).isNotNull();
}
}
package pwc.taxtech.atms.plugin;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.util.List;
public class MapperAnnotationPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper"));
interfaze.addAnnotation("@Mapper");
interfaze.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Repository"));
interfaze.addAnnotation("@Repository");
return true;
}
}
package pwc.taxtech.atms.security;
import org.junit.Assert;
import org.junit.Test;
public class AtmsPasswordEncoderTest {
@Test
public void shouldMatch() {
AtmsPasswordEncoder atmsPasswordEncoder = new AtmsPasswordEncoderImpl();
boolean result = atmsPasswordEncoder.matches("111111",
"69BC651769B8D284F8E210B52F1796A170B9B0D114EC24F6EE25405BEA562BBEC0F5A03363B0F35F348A67721A92D932D294D20527097A49E216DE6ADC1D75EE");
Assert.assertTrue("Password not match", result);
}
}
package pwc.taxtech.atms.security;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;
import org.nutz.lang.Times;
import pwc.taxtech.atms.common.CommonUtils;
import java.util.Calendar;
import java.util.Date;
public class JwtGneratorTest {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2999);
Date now = new Date();
JwtBuilder jwtBuilder = Jwts.builder();
// 设置Subject为登录用户名
jwtBuilder.setSubject("longi");
jwtBuilder.setExpiration(calendar.getTime());
jwtBuilder.setIssuedAt(now);
// 设置时钟误差偏移量,即10分钟
Date notBefore = Times.nextSecond(now, -600);
jwtBuilder.setNotBefore(notBefore);
jwtBuilder.setId(CommonUtils.getUUID());
jwtBuilder.claim("appId", "longi");
// 设置body.username为数据库用户名
jwtBuilder.signWith(SignatureAlgorithm.HS512, "TXppQjFlZFBSbnJzMHc0Tg==");
System.out.println(jwtBuilder.compact());
}
@Test
public void tt() {
}
}
package pwc.taxtech.atms.security;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JwtUtilTest {
private static final Logger logger = LoggerFactory.getLogger(JwtUtilTest.class);
private static final String TEST_SECRET_KEY = "test_secret_key";
private JwtUtil jwtUtil = new JwtUtil();
{
jwtUtil.setJwtBase64Secret(TEST_SECRET_KEY);
}
@Test
public void generateTokenThenValidate() {
String token = jwtUtil.generateToken("admin", "Admin", "UUID_OF_ADMIN_USER");
logger.debug("print token:{}", token);
JwtUser jwtUser = jwtUtil.parseToken(token);
logger.debug("print jwtUser:{}", JSON.toJSONString(jwtUser, true));
Assert.assertNotNull(jwtUser);
Assert.assertEquals("Admin", jwtUser.getDatabaseUsername());
Assert.assertEquals("admin", jwtUser.getUsername());
Assert.assertEquals("UUID_OF_ADMIN_USER", jwtUser.getUserid());
}
@Test(expected = ExpiredJwtException.class)
public void getExpiredToken() {
String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() - 1000))
.signWith(SignatureAlgorithm.HS512, TEST_SECRET_KEY).compact();
JwtParser parser = Jwts.parser().setSigningKey(TEST_SECRET_KEY);
parser.parseClaimsJws(token);
}
}
package pwc.taxtech.atms.security;
import java.util.Hashtable;
import org.junit.Assert;
import org.junit.Test;
public class LdapAuthenticationProviderTest {
// 暂时跳过该测试方法
// @Test
public void authenticateOk() {
LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProviderImpl();
String username = "xxx";
String password = "xxx";
String ldapUrl = "LDAP://nam.ad.pwcinternal.com";
String domain = "NAM";
boolean result = ldapAuthenticationProvider.authenticate(username, password, ldapUrl, domain);
System.out.println(result);
// Assert.assertTrue(result);
}
@Test
public void newClass() {
LdapAuthenticationProviderImpl ldapAuthenticationProvider = new LdapAuthenticationProviderImpl();
String username = "xxx";
String password = "xxx";
String ldapUrl = "LDAP://nam.ad.pwcinternal.com";
String domain = "NAM";
Hashtable<String, String> param = ldapAuthenticationProvider.buildParam(username, password, ldapUrl, domain);
Assert.assertNotNull(param);
}
}
package pwc.taxtech.atms.service;
import java.util.List;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.dimension.DimensionDto;
public interface DemoService {
OperationResultDto addDimensionWithoutTranction(List<DimensionDto> modelList);
OperationResultDto addDimensionWithTranction(List<DimensionDto> modelList);
OperationResultDto addDimensionWithTranctionType2(List<DimensionDto> modelList);
}
package pwc.taxtech.atms.service.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.OperationModule;
import pwc.taxtech.atms.common.message.AreaMessage;
import pwc.taxtech.atms.common.message.RegionMessage;
import pwc.taxtech.atms.dto.AreaDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.entity.Area;
import pwc.taxtech.atms.entity.OperationLogBasicData;
import pwc.taxtech.atms.entity.OperationLogBasicDataExample;
import pwc.taxtech.atms.security.JwtAuthenticationProvider;
import pwc.taxtech.atms.security.JwtAuthenticationToken;
import pwc.taxtech.atms.service.AreaService;
public class AreaServiceIT extends CommonIT {
@Autowired
private AreaService areaService;
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Before
public void setUp() {
// delete all from Area
cleanUpAllTables();
}
@Test
public void findTopAreasTest() {
// Data preparation
for (int i = 0; i < 4; i++) {
Area area = new Area();
area.setId("area" + (i + 1));
area.setName("area" + (i + 1));
area.setIsActive(true);
if (i % 2 == 1) {
area.setParentId("area" + i);
}
areaMapper.insert(area);
}
List<Area> areaList = areaService.findTopAreas();
assertEquals(2, areaList.size());
}
@Test
public void findAreasByParentIdTest() {
// Data preparation
for (int i = 0; i < 4; i++) {
Area area = new Area();
area.setId("area" + (i + 1));
area.setName("area" + (i + 1));
area.setIsActive(true);
if (i >= 1) {
area.setParentId("area1");
}
areaMapper.insert(area);
}
List<Area> areaList = areaService.getSubAreaListIngoreActive("area1");
assertEquals(3, areaList.size());
}
@Test
public void setIsActiveTestDeactivateSingle() {
// data preparation
execSqlFile("sql/area_data_update_test.sql");
// get current user name
Authentication request = new JwtAuthenticationToken("xxxx");
Authentication authenticaiton = jwtAuthenticationProvider.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
AreaDto areaDto = new AreaDto();
areaDto.setId("359667ee-bf7b-47bc-95b4-1c6e00f1de8d");
areaDto.setIsActive(CommonConstants.DEACTIVE_STATUS);
OperationResultDto<List<String>> operationResult = areaService.setIsActive(areaDto);
// check area
Area expectedArea = areaMapper.selectByPrimaryKey("359667ee-bf7b-47bc-95b4-1c6e00f1de8d");
Assert.assertEquals(CommonConstants.DEACTIVE_STATUS, expectedArea.getIsActive());
// check response
Assert.assertEquals(true, operationResult.getResult());
// check operation log
OperationLogBasicDataExample example = new OperationLogBasicDataExample();
List<OperationLogBasicData> operationLogs = operationLogBasicDataMapper.selectByExample(example);
Assert.assertEquals(1, operationLogs.size());
OperationLogBasicData log = operationLogs.get(0);
Assert.assertEquals(log.getOperationObject(), expectedArea.getName());
Assert.assertEquals(CommonConstants.ACTIVE_STATUS.toString(), log.getOriginalState());
Assert.assertEquals(CommonConstants.DEACTIVE_STATUS.toString(), log.getUpdateState());
Assert.assertEquals(OperationModule.BasicDataArea.name(), log.getModuleName());
}
@Test
public void setIsActiveTestCascadeDeactivate() {
// data preparation
execSqlFile("sql/area_data_update_test.sql");
// get current user name
Authentication request = new JwtAuthenticationToken("xxxx");
Authentication authenticaiton = jwtAuthenticationProvider.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
AreaDto areaDto = new AreaDto();
areaDto.setId("141eee99-4046-473e-a8b7-7ccd25892b71");
areaDto.setIsActive(CommonConstants.DEACTIVE_STATUS);
OperationResultDto<List<String>> operationResult = areaService.setIsActive(areaDto);
// check area
Area expectedArea = areaMapper.selectByPrimaryKey("141eee99-4046-473e-a8b7-7ccd25892b71");
Assert.assertEquals(CommonConstants.DEACTIVE_STATUS, expectedArea.getIsActive());
List<Area> allSubAreas = areaService.getAllSubAreas("141eee99-4046-473e-a8b7-7ccd25892b71");
Assert.assertEquals(3, allSubAreas.size());
Assert.assertArrayEquals(
new Boolean[] { CommonConstants.DEACTIVE_STATUS, CommonConstants.DEACTIVE_STATUS,
CommonConstants.DEACTIVE_STATUS },
allSubAreas.stream().map(area -> area.getIsActive()).collect(Collectors.toList()).toArray());
// check response
Assert.assertEquals(true, operationResult.getResult());
// check operation log
OperationLogBasicDataExample example = new OperationLogBasicDataExample();
example.setOrderByClause("CreateTime ASC");
List<OperationLogBasicData> operationLogs = operationLogBasicDataMapper.selectByExample(example);
Assert.assertEquals(4, operationLogs.size());
assertThat(operationLogs).extracting("originalState").contains(CommonConstants.ACTIVE_STATUS.toString());
assertThat(operationLogs).extracting("updateState").contains(CommonConstants.DEACTIVE_STATUS.toString());
assertThat(operationLogs).extracting("comment").contains(AreaMessage.AreaName + ":" + expectedArea.getName() + AreaMessage.DisableCascade);
/*OperationLogBasicData targetArealog = operationLogs.get(0);
Assert.assertEquals(targetArealog.getOperationObject(), expectedArea.getName());
Assert.assertEquals(CommonConstants.ACTIVE_STATUS.toString(), targetArealog.getOriginalState());
Assert.assertEquals(CommonConstants.DEACTIVE_STATUS.toString(), targetArealog.getUpdateState());
Assert.assertEquals(OperationModule.BasicDataArea.name(), targetArealog.getModuleName());
OperationLogBasicData cascadeArealog = operationLogs.get(1);
Assert.assertEquals(allSubAreas.get(0).getName(), cascadeArealog.getOperationObject());
Assert.assertEquals(CommonConstants.ACTIVE_STATUS.toString(), cascadeArealog.getOriginalState());
Assert.assertEquals(CommonConstants.DEACTIVE_STATUS.toString(), cascadeArealog.getUpdateState());
Assert.assertEquals(OperationModule.BasicDataArea.name(), cascadeArealog.getModuleName());
Assert.assertEquals(AreaMessage.AreaName + ":" + expectedArea.getName() + AreaMessage.DisableCascade,
cascadeArealog.getComment());*/
}
@Test
public void setIsActiveTestCascadeDeactivateWithLinkedOrganization() {
// data preparation
execSqlFile("sql/area_data_update_test.sql");
// get current user name
Authentication request = new JwtAuthenticationToken("xxxx");
Authentication authenticaiton = jwtAuthenticationProvider.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
AreaDto areaDto = new AreaDto();
areaDto.setId("141eb884-e9b9-4188-9a00-a3571ab1e7e9");
areaDto.setIsActive(CommonConstants.DEACTIVE_STATUS);
OperationResultDto<List<String>> operationResult = areaService.setIsActive(areaDto);
// check response
Assert.assertEquals(false, operationResult.getResult());
Assert.assertEquals(RegionMessage.CannotStopRegionTips, operationResult.getResultMsg());
Assert.assertEquals(Arrays.asList("华天证券有限公司"), operationResult.getData());
// check operation log
OperationLogBasicDataExample example = new OperationLogBasicDataExample();
example.setOrderByClause("CreateTime ASC");
List<OperationLogBasicData> operationLogs = operationLogBasicDataMapper.selectByExample(example);
Assert.assertEquals(0, operationLogs.size());
}
@Test
public void getAreaListTest() {
// data preparation
execSqlFile("sql/area_data.sql");
List<AreaDto> areaDtoList = areaService.getAreaList(1);
Assert.assertEquals(49, areaDtoList.size());
areaDtoList = areaService.getAreaList(0);
Assert.assertEquals(40, areaDtoList.size());
}
@Test
public void getAreaTreeTest() {
// data preparation
execSqlFile("sql/area_data.sql");
List<AreaDto> areaDtoTree = areaService.getAreaTree(1);
Assert.assertEquals(31, areaDtoTree.size());
areaDtoTree = areaService.getAreaTree(0);
Assert.assertEquals(29, areaDtoTree.size());
}
@After
public void tearDown() {
}
}
package pwc.taxtech.atms.service.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.CommonTestUtils;
import pwc.taxtech.atms.dto.dimension.DimensionDto;
import pwc.taxtech.atms.service.DemoService;
public class DemoServiceIT extends CommonIT {
@Autowired
private DemoService demoService;
@Before
public void setUp() {
dimensionMapper.deleteByExample(null);
dimensionValueMapper.deleteByExample(null);
dimensionValueOrgMapper.deleteByExample(null);
statisticAttributeMapper.deleteByExample(null);
statisticAttributeDimensionMapper.deleteByExample(null);
operationLogOrganizationMapper.deleteByExample(null);
cleanUpOperationLogBasicDataTable();
}
@Test
public void testOk() {
CommonTestUtils.initTestAuth();
List<DimensionDto> modelList = new ArrayList<>();
{
DimensionDto model = new DimensionDto();
model.setName("单元测试name1");
model.setIsActive(true);
modelList.add(model);
}
{
DimensionDto model = new DimensionDto();
model.setName("单元测试name2");
model.setIsActive(true);
modelList.add(model);
}
assertThat(demoService.addDimensionWithoutTranction(modelList).getResult()).isTrue();
assertThat(dimensionMapper.countByExample(null)).isEqualTo(2);
}
@Test
public void testFailed() {
CommonTestUtils.initTestAuth();
List<DimensionDto> modelList = new ArrayList<>();
{
DimensionDto model = new DimensionDto();
model.setName("单元测试name1");
model.setIsActive(true);
modelList.add(model);
}
{
DimensionDto model = new DimensionDto();
// 把name设置为null,数据库会报错
model.setName(null);
model.setIsActive(true);
modelList.add(model);
}
assertThat(demoService.addDimensionWithoutTranction(modelList).getResult()).isFalse();
// 没有回滚,有一条记录
assertThat(dimensionMapper.countByExample(null)).isEqualTo(1);
}
@Test
public void addDimensionWithTranction() {
CommonTestUtils.initTestAuth();
List<DimensionDto> modelList = new ArrayList<>();
{
DimensionDto model = new DimensionDto();
model.setName("单元测试name1");
model.setIsActive(true);
modelList.add(model);
}
{
DimensionDto model = new DimensionDto();
// 把name设置为null,数据库会报错
model.setName(null);
model.setIsActive(true);
modelList.add(model);
}
assertThat(demoService.addDimensionWithTranction(modelList).getResult()).isFalse();
// 回滚了,有0条记录
assertThat(dimensionMapper.countByExample(null)).isEqualTo(0);
}
@Test
public void addDimensionWithTranctionType2() {
CommonTestUtils.initTestAuth();
List<DimensionDto> modelList = new ArrayList<>();
{
DimensionDto model = new DimensionDto();
model.setName("单元测试name1");
model.setIsActive(true);
modelList.add(model);
}
{
DimensionDto model = new DimensionDto();
// 把name设置为null,数据库会报错
model.setName(null);
model.setIsActive(true);
modelList.add(model);
}
assertThatThrownBy(() -> {
demoService.addDimensionWithTranctionType2(modelList);
}).isInstanceOf(DataIntegrityViolationException.class);
// 回滚了,有0条记录
assertThat(dimensionMapper.countByExample(null)).isEqualTo(0);
}
// @Test
// public void failedTest() {
// throw new RuntimeException();
// }
}
package pwc.taxtech.atms.service.impl;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.dimension.DimensionDto;
import pwc.taxtech.atms.entity.Dimension;
import pwc.taxtech.atms.service.DemoService;
@Service
public class DemoServiceImpl extends AbstractService implements DemoService {
@Override
public OperationResultDto addDimensionWithoutTranction(List<DimensionDto> modelList) {
logger.debug("Enter addDimensionWithoutTranction");
try {
int i = 0;
for (DimensionDto model : modelList) {
logger.debug("Insert 第{}条记录, name:{}", ++i, model.getName());
Dimension entity = new Dimension();
CommonUtils.copyProperties(model, entity);
entity.setId(CommonUtils.getUUID());
entity.setOrderIndex((short) 1);
entity.setIsSystemDimension(false);
entity.setIsMandatory(BooleanUtils.isTrue(entity.getIsMandatory()));
entity.setIsActive(BooleanUtils.isTrue(entity.getIsActive()));
String currentUserId = authUserHelper.getCurrentUserId();
entity.setCreateBy(currentUserId);
entity.setUpdateBy(currentUserId);
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
dimensionMapper.insert(entity);
}
return new OperationResultDto(true);
} catch (Exception e) {
logger.debug("出错了:" + e);
return new OperationResultDto(false);
}
}
@Override
public OperationResultDto addDimensionWithTranction(List<DimensionDto> modelList) {
logger.debug("Enter addDimensionWithTranction");
try {
int i = 0;
for (DimensionDto model : modelList) {
logger.debug("Insert 第{}条记录, name:{}", ++i, model.getName());
Dimension entity = new Dimension();
CommonUtils.copyProperties(model, entity);
entity.setId(CommonUtils.getUUID());
entity.setOrderIndex((short) 1);
entity.setIsSystemDimension(false);
entity.setIsMandatory(BooleanUtils.isTrue(entity.getIsMandatory()));
entity.setIsActive(BooleanUtils.isTrue(entity.getIsActive()));
String currentUserId = authUserHelper.getCurrentUserId();
entity.setCreateBy(currentUserId);
entity.setUpdateBy(currentUserId);
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
dimensionMapper.insert(entity);
}
return new OperationResultDto(true);
} catch (Exception e) {
logger.debug("出错了:" + e);
logger.debug("标记回滚, ready to call setRollbackOnly");
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new OperationResultDto(false);
}
}
@Override
public OperationResultDto addDimensionWithTranctionType2(List<DimensionDto> modelList) {
logger.debug("Enter addDimensionWithTranctionType2");
int i = 0;
for (DimensionDto model : modelList) {
logger.debug("Insert 第{}条记录, name:{}", ++i, model.getName());
Dimension entity = new Dimension();
CommonUtils.copyProperties(model, entity);
entity.setId(CommonUtils.getUUID());
entity.setOrderIndex((short) 1);
entity.setIsSystemDimension(false);
entity.setIsMandatory(BooleanUtils.isTrue(entity.getIsMandatory()));
entity.setIsActive(BooleanUtils.isTrue(entity.getIsActive()));
String currentUserId = authUserHelper.getCurrentUserId();
entity.setCreateBy(currentUserId);
entity.setUpdateBy(currentUserId);
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
dimensionMapper.insert(entity);
}
return new OperationResultDto(true);
}
}
package pwc.taxtech.atms.service.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import pwc.taxtech.atms.dto.OperationResultDto;
public class FileServiceTest {
private FileService fileService = new FileService();
private static final Logger logger = LoggerFactory.getLogger(FileServiceTest.class);
@Test
public void saveTempFile() throws IOException {
ClassPathResource res = new ClassPathResource("excel/customer-atms.xlsx");
logger.debug("print input file url:" + res.getURL());
InputStream inputStream = res.getInputStream();
// String.format("%s/unit_test/testfile.xlsx",
// FileUtils.getTempDirectory().getAbsolutePath());
String filePath = FileUtils.getTempDirectory().getAbsolutePath() + "/unit_test/testfile_"
+ System.currentTimeMillis() + ".xlsx";
// System.out.println("target filePath:" + filePath);
OperationResultDto<Object> result = fileService.saveFile(inputStream, filePath);
Assert.assertTrue(result.getResult());
}
@Test
public void importFileThenGetMap() throws IOException {
ClassPathResource res = new ClassPathResource("excel/customer-atms.xlsx");
Collection<Map> collection = fileService.readExcelAndClose(res.getInputStream());
assertThat(collection).isNotEmpty();
// System.out.println(JSON.toJSONString(collection, true));
}
}
package pwc.taxtech.atms.service.impl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.dao.MailQueueMapper;
import pwc.taxtech.atms.dto.MailMto;
import pwc.taxtech.atms.entity.MailQueue;
import pwc.taxtech.atms.service.CommonService;
import java.util.Date;
public class MailServiceIT extends CommonIT {
private static final Logger logger = LoggerFactory.getLogger(MailServiceIT.class);
@Autowired
private CommonService commonService;
@Autowired
private MailQueueMapper mailQueueMapper;
@Before
public void setUp() {
mailQueueMapper.deleteByExample(null);
}
@Test
public void sendMail() {
MailMto mailmto = new MailMto();
mailmto.setTo("test@test.com");
mailmto.setSubject("sub1");
mailmto.setContent("content1");
commonService.sendMail(mailmto);
long count = mailQueueMapper.countByExample(null);
Assert.assertTrue(count > 0);
}
@Test
public void insertThenCount() {
MailQueue record = new MailQueue();
record.setAppcode("appcode1");
record.setMto("a@a.com");
record.setMfrom("from@a.com");
record.setReplyto("from@a.com");
record.setSubject("subject1中文");
record.setContent("aaabbb");
record.setSubmitby("by1");
record.setSubmitdate(new Date());
record.setPostedflag("N");
record.setSenddate(new Date());
record.setImmediateflag("N");
Assert.assertNull(record.getMailseq());
int inserted = mailQueueMapper.insert(record);
// logger.debug("inserted:{}", inserted);
Assert.assertTrue(inserted > 0);
// logger.debug("record.getMailseq():{}", record.getMailseq());
Assert.assertNotNull(record.getMailseq());
long count = mailQueueMapper.countByExample(null);
// logger.debug("MailQueue count:{}", count);
Assert.assertTrue(count > 0);
}
}
package pwc.taxtech.atms.service.impl;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.dto.MenuDisplayDto;
import pwc.taxtech.atms.dto.MenuDto;
import pwc.taxtech.atms.security.JwtAuthenticationProvider;
import pwc.taxtech.atms.security.JwtAuthenticationToken;
import pwc.taxtech.atms.service.MenuService;
public class MenuServiceIT extends CommonIT {
private static Logger logger = LoggerFactory.getLogger(MenuServiceIT.class);
@Autowired
private MenuService menuService;
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Before
public void init() {
execSqlFile("sql/menu.sql");
// get current user name
Authentication request = new JwtAuthenticationToken("xxxx");
Authentication authenticaiton = jwtAuthenticationProvider.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(authenticaiton);
}
@Test
public void getMenusForDisplayTest() {
logger.debug("Start to test getMenusForDisplay");
Integer serviceId = 1;
List<MenuDisplayDto> menuDisplayDtos = menuService.getMenusForDisplay(serviceId);
Assert.assertNotNull(menuDisplayDtos);
Assert.assertEquals(2, menuDisplayDtos.size());
for (MenuDisplayDto menuDisplayDto : menuDisplayDtos) {
assertSubDisplayMenus("apps", menuDisplayDto, 2);
assertSubDisplayMenus("assignment", menuDisplayDto, 4);
for (MenuDisplayDto subMenuDto : menuDisplayDto.getSubMenus()) {
assertSubDisplayMenus("dns", subMenuDto, 4);
assertSubDisplayMenus("local_atm", subMenuDto, 2);
}
}
}
@Test
public void getMenusTest() {
logger.debug("Start to test getMenus");
Integer serviceId = 1;
List<MenuDto> menuDtos = menuService.getMenus(serviceId);
Assert.assertNotNull(menuDtos);
Assert.assertEquals(2, menuDtos.size());
for (MenuDto menuDto : menuDtos) {
assertSubMenus("apps", menuDto, 2);
assertSubMenus("assignment", menuDto, 5);
for (MenuDto subMenuDto : menuDto.getSubMenus()) {
assertSubMenus("dns", subMenuDto, 4);
assertSubMenus("local_atm", subMenuDto, 2);
}
}
}
private void assertSubDisplayMenus(String iconClassName, MenuDisplayDto menuDisplayDto, int menuSize) {
if (menuDisplayDto.getIconClassName().equals(iconClassName)) {
Assert.assertNotNull(menuDisplayDto.getSubMenus());
Assert.assertEquals(menuDisplayDto.getSubMenus().size(), menuSize);
}
}
private void assertSubMenus(String iconClassName, MenuDto menuDto, int menuSize) {
if (menuDto.getIconClassName().equals(iconClassName)) {
Assert.assertNotNull(menuDto.getSubMenus());
Assert.assertEquals(menuDto.getSubMenus().size(), menuSize);
}
}
@After
public void clean() {
cleanUpMenuTable();
}
}
package pwc.taxtech.atms.service.impl;
import java.util.Date;
import org.junit.Test;
import pwc.taxtech.atms.dto.UpdateLogParams;
import pwc.taxtech.atms.entity.OrganizationStructure;
public class UpdateLogParamsTest{
@Test
public void test()
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
UpdateLogParams updateLogParams = new UpdateLogParams();
OrganizationStructure origin = new OrganizationStructure();
Date date = new Date();
origin.setId("1");
origin.setIsActive(true);
origin.setCreateTime(date);
origin.setUpdateTime(date);
origin.setName("abc");
OrganizationStructure update = new OrganizationStructure();
update.setId("1");
update.setIsActive(false);
update.setCreateTime(date);
update.setUpdateTime(date);
update.setName("cba");
updateLogParams.setOriginalState(origin);
updateLogParams.setUpdateState(update);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment