Mockito: Wanted but not invoked - however, there were other interactions - java

I'm receiving this error and have researched that it is because I am not calling the Mocked class but the actual class? I've looked over it numerous times and it seems to be pretty straightforward to simply be invoking the mock. The main error I get is
Wanted but not invoked:
dsIn.setItemString(1, "MAKE", "MAKE");
However, there were other interactions with this mock:
dsIn.getItemNumber(1, "APPROVED");
dsIn.setItemString(1, "VIN", "VIN");
dsIn.setItemObject(1, "MAKE", null);
And then it just continues through the others.
Below is the class to be tested:
if(dsIn.getItemNumber(1,"APPROVED") == 1) {
throw new TRDIException("Cannot change Approved record");
}
String sql;
sql = "select c.EQUIPMENT_NAME, c.VIN, c.MAKE, c.MODEL,c.EQUIPMENT_CLASS_CODE_ID,c.SALVAGE_VALUE,c.GARAGE_ASSIGNED,c.EQ_LOCATION_ID, c.DEPT_PM_NOTIFY, " +
"GET_DEPR_VALUE(c.EQUIPMENT_ID) AS EQ_CURRENT_VALUE " +
" from EQUIPMENT_INVENTORY c where c.EQUIPMENT_ID = " + newValueIn ;
DataStore ds = dl.createDataStore(sql);
ds.retrieve();
dsIn.setItemString(1,"VIN",ds.getItemString(1,"VIN"));
dsIn.setItemObject(1,"MAKE",ds.getItemObject(1,"MAKE"));
dsIn.setItemObject(1,"MODEL",ds.getItemObject(1,"MODEL"));
dsIn.setItemObject(1,"EQUIPMENT_CLASS_CODE_ID",ds.getItemObject(1,"EQUIPMENT_CLASS_CODE_ID"));
dsIn.setItemObject(1,"GARAGE_ASSIGNED",ds.getItemObject(1,"GARAGE_ASSIGNED"));
dsIn.setItemObject(1,"EQ_LOCATION_ID",ds.getItemObject(1,"EQ_LOCATION_ID"));
dsIn.setItemObject(1,"SALVAGE_VALUE",ds.getItemObject(1,"SALVAGE_VALUE"));
if(dsIn.getItemNumber(1,"APPROVED") == 1) {
throw new TRDIException("Cannot change approved record");
}
Below is the test class:
#RunWith(Parameterized.class)
public class TestFillEqDisposalAttr extends TestGroovy {
#Mock
private DataLayer dl;
#Mock
private DataStore dsIn;
#Mock
private DataStore ds;
private String newValueIn;
#Parameter
public String client;
#Parameters(name = "{index}: {0}")
public static Object[] data() {
return new Object[]{
"test"
};
}
#Before
public void setUp() throws Exception {
//groovy script file to test
groovyScriptFile = new File(GROOVY_SCRIPTS_FOLDER + "/" + client + "/test.groovy");
MockitoAnnotations.initMocks(this);
Mockito.when(dl.createDataStore(Mockito.anyString())).thenReturn(ds);
newValueIn = "1";
//groovy script parameters
addGroovyBindingVariable(GroovyScriptArgName.DATALAYER, dl);
addGroovyBindingVariable(GroovyScriptArgName.DATASTORE, dsIn);
addGroovyBindingVariable(GroovyScriptArgName.NEW_VALUE, newValueIn);
}
/**
*/
#Test
public void testEqDisposalAttr() throws IOException, TRDIException {
Mockito.when(ds.getItemString(1, "VIN")).thenReturn("VIN");
Mockito.when(ds.getItemString(1, "MAKE")).thenReturn("MAKE");
Mockito.when(ds.getItemString(1, "MODEL")).thenReturn("MODEL");
Mockito.when(ds.getItemString(1, "EQUIPMENT_CLASS_CODE_ID")).thenReturn("EQUIPMENT_CLASS_CODE_ID");
Mockito.when(ds.getItemString(1, "GARAGE_ASSIGNED")).thenReturn("GARAGE_ASSIGNED");
Mockito.when(ds.getItemString(1, "EQ_LOCATION_ID")).thenReturn("EQ_LOCATION_ID");
Mockito.when(ds.getItemString(1, "SALVAGE_VALUE")).thenReturn("SALVAGE_VALUE");
evaluate();
String sql = "select c.EQUIPMENT_NAME, c.VIN, c.MAKE, c.MODEL,c.EQUIPMENT_CLASS_CODE_ID,c.SALVAGE_VALUE,c.GARAGE_ASSIGNED,c.EQ_LOCATION_ID, c.DEPT_PM_NOTIFY, " +
"GET_DEPR_VALUE(c.EQUIPMENT_ID) AS EQ_CURRENT_VALUE " +
" from EQUIPMENT_INVENTORY c where c.EQUIPMENT_ID = " + newValueIn ;
Mockito.verify(dl).createDataStore(sql);
Mockito.verify(ds).retrieve();
Mockito.verify(dsIn).setItemString(1, "VIN", "VIN");
Mockito.verify(dsIn).setItemString(1, "MAKE", "MAKE");
Mockito.verify(dsIn).setItemString(1, "MODEL", "MODEL");
Mockito.verify(dsIn).setItemString(1, "EQUIPMENT_CLASS_CODE_ID", "EQUIPMENT_CLASS_CODE_ID");
Mockito.verify(dsIn).setItemString(1, "GARAGE_ASSIGNED", "GARAGE_ASSIGNED");
Mockito.verify(dsIn).setItemString(1, "EQ_LOCATION_ID", "EQ_LOCATION_ID");
Mockito.verify(dsIn).setItemString(1, "SALVAGE_VALUE", "SALVAGE_VALUE");
}

Related

How to mock repository to perform the flush() method

I am trying to write a test of a service method. Most of the logic performed in their is covered by tests of those methods. I am mostly trying to see if the correct repository calls are being performed.The method returns the id of the receipt/bon it just created.
I can train the mocks of the repository with the calls being performed in the service. But my test keeps failing, because the service call is unable to return an id value (long). This is because the id is generated by performing the save method followed by the flush. I cannot seem to train my mocks to do this right.
This is the only error eccuring, that it cannot perform the service call, because it returns a null value instead of an id.
How can I mock the repository correct so testing my method will not fail on not having an id?
method:
#Override
#Transactional
public long addBonAndProducts(Boninfo boninfo) {
Consignatiebon bon = new Consignatiebon(boninfo.getGebruiker(), LocalDate.now(), boninfo.getOpmbon(), boninfo.getSolden());
LocalDate dateUit = this.createCorrectDateOut(bon.getDatumIn(), bon.getSolden());
bon.setDatumUit(dateUit);
//creates correct bonnr - logic tested elswhere
String currentLetterBon = this.findCurrentLetter();
Integer numberToInsert = this.findMostRecentBoncode(currentLetterBon);
bon.setBonCode(currentLetterBon, (numberToInsert + 1));
consignatiebonRepository.save(bon);
consignatiebonRepository.flush();
for(var product:boninfo.getLijstproducten()) {
product.setConsignatiebon(bon);
if(!(product.getStatus()==Status.STOCK)) {
product.setDatumUit(dateUit);
}
//creates correct articlenr - logi tested elswhere
String currentLetter = this.findCurrentLetter();
Integer numberToInsertBon = this.findMostRecentArtikelcode(currentLetter);
product.setArtikelCode(currentLetter, (numberToInsertBon + 1));
productRepository.save(product);
productRepository.flush();
long idProduct = product.getProductId();
bon.add(product);
}
consignatiebonRepository.save(bon);
consignatiebonRepository.flush();
bon.setTotalPieces();
bon.setTotalValueBon();
// these values are correct
System.out.println("inside function pieces: " + bon.getTotalPieces());
System.out.println("inside function pieces: " + bon.getTotalPrice());
consignatiebonRepository.save(bon);
// in the test, this is outputted as null, cause the flush method doesn't get performed
System.out.println("inside function pieces: " + bon.getIdConsignatiebon());
return bon.getIdConsignatiebon();
}
test:
#ExtendWith(MockitoExtension.class)
class ProductServiceTest {
private DefaultProductService productService;
private Kleur kleur;
private Maat maat;
private Merk merk;
private Eigenschap eigenschap;
private Product product;
private Product productTwo;
private Product productThree;
private Adres adres;
private Gebruiker gebruiker;
private Consignatiebon consignatiebon;
private Consignatiebon consignatiebonToFill;
#Mock
private ProductRepository productRepository;
#Mock
private GebruikerRepository gebruikerRepository;
#Mock
private ConsignatiebonRepository consignatiebonRepository;
#Mock
private WoocommerceApi woocommerceApi;
#Mock
private Mailing mailing;
#BeforeEach
void beforeEach() {
productService = new DefaultProductService(productRepository, consignatiebonRepository, gebruikerRepository,
woocommerceApi, mailing);
kleur = new Kleur("testkleur");
maat = new Maat("testmaat");
merk = new Merk("testmerk");
eigenschap = new Eigenschap("testclustereigenschap", "testsubeigenschap");
adres = new Adres("teststraat", "testhuisnummer", "testpostcode", "testgemeente", "testland");
gebruiker = new Gebruiker("testvoornaam","testnaam", "testriziv", "testmail#hotmail.be", true,
"testtelefoonnr", adres, Gebruikersrol.TESTLEVERANCIER, "testopmerking");
consignatiebon = new Consignatiebon(gebruiker, LocalDate.of(2020, 1, 1), "testopmerking", true);
product = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijving", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
productTwo = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijvingTwo", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
productThree = new Product(gebruiker, consignatiebon, eigenschap, kleur, merk, maat, Soort.DAMES,
"testbeschrijvingThree", BigDecimal.valueOf(10), BigDecimal.valueOf(25), Status.TEKOOP, false, true);
}
#Test
void addBonAndProducts() {
when(consignatiebonRepository.save(Mockito.any(Consignatiebon.class))).thenAnswer(i -> i.getArguments()[0]);
when(productRepository.save(Mockito.any(Product.class))).thenAnswer(i -> i.getArguments()[0]);
// when(productService.addBonAndProducts(Mockito.any(Boninfo.class))).thenReturn(1L);
List<Product> productlist = new ArrayList<>();
productlist.add(product);
productlist.add(productTwo);
productlist.add(productThree);
Boninfo testboninfo = new Boninfo(productlist, gebruiker, "testopmerkingbon", true);
productService.addBonAndProducts(testboninfo);
verify(consignatiebonRepository, times(3)).save(consignatiebon);
verify(productRepository, times(1)).save(product);
verify(productRepository, times(1)).save(productTwo);
verify(productRepository, times(1)).save(productThree);
}
}

Exception in combination of #DirtiesContext and FlywayConfig bean in integration test

I have a problem when adding new test. And the problem is I think related to #DirtiesContext. I tried removing and adding it but nothing works in combination. Test 1 is using Application Context as well.
the following two are running together and no issue.
Test 1
#ActiveProfiles({"aws", "local"})
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UnauthorizedControllerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UnauthorizedControllerTest.class);
#Autowired
private TestRestTemplate testRestTemplate;
#LocalServerPort
private int port;
#Autowired
private ApplicationContext context;
private Map<Class<?>, List<String>> excludedMethodsPerController;
#Before
public void setUp() {
excludedMethodsPerController = excludedMethodsPerController();
}
#Test
public void contextStarts() {
assertNotNull(context);
}
#Test
public void controllerCall_WithoutAuthorization_ReturnsUnauthorized() {
Map<String, Object> controllerBeans = context.getBeansWithAnnotation(Controller.class);
for (Object controllerInstance : controllerBeans.values()) {
LOGGER.info("Checking controller {}", controllerInstance);
checkController(controllerInstance);
}
}
public void checkController(Object controllerInstance) {
// Use AopUtils for the case that spring wraps the controller in a proxy
Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controllerInstance);
Method[] allMethods = controllerClass.getDeclaredMethods();
for (Method method : allMethods) {
LOGGER.info("Checking method: {}", method.getName());
if (!isCallable(controllerClass, method)) {
continue;
}
String urlPrefix = urlPrefix(controllerClass);
Mapping mapping = Mapping.of(method.getAnnotations());
for (String url : mapping.urls) {
for (RequestMethod requestMethod : mapping.requestMethods) {
ResponseEntity<String> exchange = exchange(urlPrefix + url, requestMethod);
String message = String.format("Failing %s.%s", controllerClass.getName(), method.getName());
assertEquals(message, HttpStatus.UNAUTHORIZED, exchange.getStatusCode());
}
}
}
}
private ResponseEntity<String> exchange(String apiEndpoint, RequestMethod requestMethod) {
return testRestTemplate.exchange(url(replacePathVariables(apiEndpoint)), HttpMethod.resolve(requestMethod.name()), null, String.class);
}
private String urlPrefix(Class<?> aClass) {
if (!aClass.isAnnotationPresent(RequestMapping.class)) {
return "";
}
RequestMapping annotation = aClass.getAnnotation(RequestMapping.class);
return annotation.value()[0];
}
private String url(String url) {
return "http://localhost:" + port + url;
}
private boolean isCallable(Class<?> controller, Method method) {
return Modifier.isPublic(method.getModifiers())
&& !isExcluded(controller, method)
&& !isExternal(controller);
}
private boolean isExcluded(Class<?> controller, Method method) {
List<String> excludedMethodsPerController = this.excludedMethodsPerController.getOrDefault(controller, new ArrayList<>());
return excludedMethodsPerController.contains(method.getName());
}
private boolean isExternal(Class<?> controller) {
return controller.getName().startsWith("org.spring");
}
private String replacePathVariables(String url) {
return url.replaceAll("\\{[^\\/]+}", "someValue");
}
/**
* There must be a really good reason to exclude the method from being checked.
*
* #return The list of urls that must not be checked by the security
*/
private static Map<Class<?>, List<String>> excludedMethodsPerController() {
Map<Class<?>, List<String>> methodPerController = new HashMap<>();
methodPerController.put(AuthenticationController.class, Collections.singletonList("generateAuthorizationToken"));
methodPerController.put(SystemUserLoginController.class, Arrays.asList("systemUserLogin", "handleException"));
methodPerController.put(ValidationController.class, Collections.singletonList("isValid"));
return methodPerController;
}
}
Test 2
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles({"aws", "local"})
public class RoleAdminControllerAuditTest {
private static final String DOMAIN_NAME = "testDomain";
private static final String APP_NAME_1 = "testApp_1";
private static final String APP_NAME_2 = "testApp_2";
private static final String ROLE_NAME = "testRole";
private static final String USER_NAME = "testUser";
#Autowired
AuditRepository auditRepository;
#Autowired
RoleAdminController roleAdminController;
#MockBean
RoleAdminService roleAdminService;
#MockBean
RoleAdminInfoBuilder infoBuilder;
#MockBean
AppInfoBuilder appInfoBuilder;
#MockBean
BoundaryValueService boundaryValueService;
#MockBean
RoleService roleService;
#MockBean
private SecurityService securityService;
private static final String URS_USER = "loggedInUser";
private static final String BOUNDARY_VALUE_KEY = "11";
private static final String BOUNDARY_VALUE_NAME = "Schulenberg";
private String auditEventDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
#BeforeClass
public static void setupTestEnv() {
// https://github.com/localstack/localstack/issues/592
System.setProperty("com.amazonaws.sdk.disableCbor", "true");
}
#Before
public void setUp() throws Exception {
auditRepository.clean();
when(securityService.getLoggedInUser()).thenReturn(new TestHelper.FakeUser(URS_USER));
//when(roleService.addRoleToApp(any(), any(), eq(ROLE_NAME))).thenReturn(TestHelper.initRole(ROLE_NAME));
when(boundaryValueService.findBoundaryValueById(eq(123L))).thenReturn(initBoundaryValue(BOUNDARY_VALUE_KEY, BOUNDARY_VALUE_NAME));
when(boundaryValueService.findBoundaryValueById(eq(666L))).thenReturn(initBoundaryValue(BOUNDARY_VALUE_KEY, BOUNDARY_VALUE_NAME));
}
#Test
public void addUserAsRoleAdminLogged() throws UserIsAlreadyRoleAdminException, RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
List<RoleAdminInfo> roleAdminInfos = getRoleAdminInfos();
roleAdminController.addUserAsRoleAdmin(user, roleAdminInfos);
List<String> result = auditRepository.readAll();
assertEquals("some data", result.toString());
}
#Test
public void removeUserAsRoleAdminLogged() throws RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
Long roleId = Long.valueOf(444);
Role role = initRole("test-role");
role.setApp(initApp("test-app"));
role.setDomain(initDomain("test-domain"));
when(roleService.getRoleByIdOrThrow(roleId)).thenReturn(role);
roleAdminController.removeUserAsRoleAdmin(user, roleId, Long.valueOf(666));
List<String> result = auditRepository.readAll();
assertEquals("some data", result.toString());
}
#Test
public void removeRoleAdminPermission() throws RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
List<RoleAdminInfo> roleAdminInfos = getRoleAdminInfos();
roleAdminController.removeRoleAdminPermission(user, roleAdminInfos);
List<String> result = auditRepository.readAll();
assertEquals(1, result.size());
assertEquals("some data", result.toString());
}
private List<RoleAdminInfo> getRoleAdminInfos() {
RoleAdminInfo info1 = initRoleAdminInfo(DOMAIN_NAME, ROLE_NAME, APP_NAME_1);
RoleAdminInfo info2 = initRoleAdminInfo(DOMAIN_NAME, ROLE_NAME, APP_NAME_2);
info1.setBoundaryValueId(123L);
info1.setBoundaryValueKey(BOUNDARY_VALUE_KEY);
info1.setBoundaryValueName(BOUNDARY_VALUE_NAME);
return Arrays.asList(info1, info2);
}
}
Test 3 (newly added one)
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = FlywayConfig.class)
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
#ActiveProfiles({"aws", "local"})
public class BoundaryValueDeltaControllerTest {
private static final String API_V1 = "/api/v1/";
#Autowired
TestRestTemplate testRestTemplate;
#Autowired
private DomainBuilder domainBuilder;
#Autowired
private AppBuilder appBuilder;
#Autowired
private UserBuilder userBuilder;
#Autowired
private DomainAdminBuilder domainAdminBuilder;
#Autowired
private BoundarySetBuilder boundarySetBuilder;
#MockBean
private LoginUserProvider loginUserProvider;
#MockBean
private LoginTokenService loginTokenService;
#MockBean
private BoundaryServiceAdapter serviceAdapter;
#LocalServerPort
private int port;
LoginUserInfo loggedInUser;
#Before
public void setUp() {
clear();
}
#After
public void tearDown() {
clear();
}
#Test
public void updateBoundaryValuesFromApi() throws UrsBusinessException {
Domain domain = domainBuilder.persist();
App app = appBuilder.persist(domain);
BoundarySet boundarySet = boundarySetBuilder.persist(domain);
User user = userBuilder.persist(domain.getAuthor().getUsername());
aLoggedInUser(domain.getAuthor().getUsername());
domainAdminBuilder.persist(user, domain);
mockReadInfoFromApiUsingApp();
ResponseEntity<String> response = callUpdateBoundaryValuesFromApi(domain, boundarySet, app);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
}
private void mockReadInfoFromApiUsingApp() throws UrsBusinessException {
BoundaryValueInfo boundaryValueInfo = new BoundaryValueInfo();
boundaryValueInfo.setBoundaryValueId(10L);
boundaryValueInfo.setBoundaryValueKey("boundaryValueKey");
boundaryValueInfo.setBoundaryValueName("boundaryValuename");
when(serviceAdapter.readInfoFromApiUsingApp(any(), any(), any())).thenReturn(new BoundaryValueInfo[]{boundaryValueInfo});
}
private ResponseEntity<String> callUpdateBoundaryValuesFromApi(Domain domain, BoundarySet boundarySet, App app) {
String url = url(API_V1 + "domains/" + domain.getName() + "/boundarysets/" + boundarySet.getBoundarySetName() + "/app/" + app.getName()+ "/updatefromapi/");
return testRestTemplate.exchange(url,HttpMethod.GET, null, String.class);
}
private String url(String url) {
return "http://localhost:" + port + url;
}
private void aLoggedInUser(String username) {
Claims claims = Jwts.claims();
claims.put("username", username);
loggedInUser = LoginUserInfo.parse(claims);
when(loginUserProvider.getLoggedInUser()).thenReturn(loggedInUser);
when(loginTokenService.parseToken(any())).thenReturn(loggedInUser);
}
private void clear() {
appBuilder.deleteAll();
boundarySetBuilder.deleteAll();
domainAdminBuilder.deleteAll();
domainBuilder.deleteAll();
userBuilder.deleteAll();
}
}
Flyway config
#TestConfiguration
public class FlywayConfig {
#Bean
public FlywayMigrationStrategy clean() {
return flyway -> {
flyway.clean();
flyway.migrate();
};
}
}
And I am getting below exception while running all together.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java.....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: Too many connections
---------------------------------------------------------------
SQL State : 08004
Error Code : 1040
Message : Too many connections
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
... 49 more
Caused by: org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: Too many connections
I am struggling since yesterday's and you might find duplicate but I tried to add the more details today. please guide me here.
you must add the configuration for flyway
flyway.url=jdbc:postgresql://xxx.eu-west-2.rds.amazonaws.com:5432/xxx
flyway.user=postgres
flyway.password=xxx

Can we use variables defined in testng listeners in any of the test class?

I am setting up a new framework and want to implement Extent Report as part of IInvokedMethod listeners so that before every method I can start the extentTest and log the steps.
Currently I am starting the extentTest(reference of ExtentTest declared in BaseTest class) in every method in test class.
But I don't want to write the same code again and again.
Below is my code.
Is there any way that I can initialize extentTest in testng listeners and use the same in below test class?
Current Code(Test Class):
public class ApplyNowPageTests extends BaseTest {
#Test(groups = {"Apply Now"}, enabled = false, dataProvider = "validStates", dataProviderClass = GeneralDataProvider.class)
public void verifyApplyNowRangeValues(String state) throws Exception {
testCaseName = className + " : " +state;
extentTest = extentReport.startTest(
className + " : " + new Throwable().getStackTrace()[0].getMethodName()+" - " +state);
extentTest.log(LogStatus.INFO, "Starting the test");
extentTest.assignAuthor("Ankur Magan");
ApplyNow applyNow = new ApplyNow(driver, extentTest);
PageFactory.initElements(new AppiumFieldDecorator(driver), applyNow);
applyNow.gotoApplyNowFlow();
applyNow.enterEmail(dataClient.getEmail());
applyNow.enterState(state);
applyNow.verifyRangeSliderDisplayed();
Map<String, String> loanActualValues =applyNow.getRangeSliderAmount();
Assert.assertEquals(States.getStateMinAmount(state), loanActualValues.get("min"));
Assert.assertEquals(States.getStateMaxAmount(state), loanActualValues.get("max"));
applyNow.reportPass(state + " : Passed ");
}
/* Verify Apply Now - Login Functionality*/
#Test(groups = {"Apply Now"}, enabled = true)
public void verifyApplyNowLogin() throws Throwable {
testCaseName = className + " : " +new Throwable().getStackTrace()[0].getMethodName();
extentTest = extentReport.startTest(
className + " : " + new Throwable().getStackTrace()[0].getMethodName());
extentTest.log(LogStatus.INFO, "Starting the test");
extentTest.assignAuthor("Ankur Magan");
ApplyNow applyNow = new ApplyNow(driver, extentTest);
PageFactory.initElements(new AppiumFieldDecorator(driver), applyNow);
CreateYourAccount createAccnt=applyNow.completeApplyNowPage(dataClient);
createAccnt.completeCreateYourAccountPage(dataClient);
}
}
But I don't want to write the same code again and again. Below is my
code. Is there any way that I can initialize extentTest in testng
listeners and use the same in below test class?
#BeforeEach
public void init(){
//This method will be executed before every #Test
}
check this answer
public class MyTest{
#BeforeMethod
public void init(){
//your logic
testCaseName = className + " : " +state;
extentTest = extentReport.startTest(
className + " : " + new Throwable().getStackTrace()[0].getMethodName()+" - " +state);
extentTest.log(LogStatus.INFO, "Starting the test");
extentTest.assignAuthor("Ankur Magan");
//.............
}
#Test
public void test1(){
//test some
}
#Test
public void test2(){
//
}
}
Annotate init() with #BeforeMethod annotation. See http://testng.org/doc/documentation-main.html#annotations

How do I create a very simple rule using Apache Calcite and use it on Apache Flink?

I have this application in Flink which use Table API to print data from a source. THe official documentation of Flink says that the Table API uses Calcite on its core to translate and optimize query plans. They don't describe it very in deep, so I went to the source code and tried to copy some codes from there. But, as far as I saw, they use Calcite rules as well.
What if I want to implement my own rule? Is it possible? How do I implement a simple rule in Calcite to change the parameter of a filter for example?
Here is my code
public class HelloWorldCalcitePlanTableAPI {
private static final Logger logger = LoggerFactory.getLogger(HelloWorldCalcitePlanTableAPI.class);
private static final String TICKETS_STATION_01_PLATFORM_01 = "TicketsStation01Plat01";
public static void main(String[] args) throws Exception {
new HelloWorldCalcitePlanTableAPI("127.0.0.1", "127.0.0.1");
}
public HelloWorldCalcitePlanTableAPI(String ipAddressSource01, String ipAddressSink) throws Exception {
// Start streaming from fake data source sensors
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
// StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, tableConfig);
StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
// Calcite configuration file to change the query execution plan
// CalciteConfig cc = tableEnv.getConfig().getCalciteConfig();
CalciteConfig cc = new CalciteConfigBuilder()
.addNormRuleSet(RuleSets.ofList(MyFilterReduceExpressionRule.FILTER_INSTANCE))
.replaceDecoRuleSet(RuleSets.ofList(MyDataStreamRule.INSTANCE))
.build();
tableEnv.getConfig().setCalciteConfig(cc);
// obtain query configuration from TableEnvironment
StreamQueryConfig qConfig = tableEnv.queryConfig();
qConfig.withIdleStateRetentionTime(Time.minutes(30), Time.hours(2));
// Register Data Source Stream tables in the table environment
tableEnv.registerTableSource(TICKETS_STATION_01_PLATFORM_01,
new MqttSensorTableSource(ipAddressSource01, TOPIC_STATION_01_PLAT_01_TICKETS));
Table result = tableEnv.scan(TICKETS_STATION_01_PLATFORM_01)
.filter(VALUE + " >= 50 && " + VALUE + " <= 100 && " + VALUE + " >= 50")
;
tableEnv.toAppendStream(result, Row.class).print();
System.out.println("Execution plan ........................ ");
System.out.println(env.getExecutionPlan());
System.out.println("Plan explaination ........................ ");
System.out.println(tableEnv.explain(result));
System.out.println("........................ ");
System.out.println("NormRuleSet: " + cc.getNormRuleSet().isDefined());
System.out.println("LogicalOptRuleSet: " + cc.getLogicalOptRuleSet().isDefined());
System.out.println("PhysicalOptRuleSet: " + cc.getPhysicalOptRuleSet().isDefined());
System.out.println("DecoRuleSet: " + cc.getDecoRuleSet().isDefined());
// #formatter:on
env.execute("HelloWorldCalcitePlanTableAPI");
}
}
public class MyDataStreamRule extends RelOptRule {
public static final MyDataStreamRule INSTANCE = new MyDataStreamRule(operand(DataStreamRel.class, none()), "MyDataStreamRule");
public MyDataStreamRule(RelOptRuleOperand operand, String description) {
super(operand, "MyDataStreamRule:" + description);
}
public MyDataStreamRule(RelBuilderFactory relBuilderFactory) {
super(operand(DataStreamRel.class, any()), relBuilderFactory, null);
}
public void onMatch(RelOptRuleCall call) {
DataStreamRel dataStreamRel = (DataStreamRel) call.rel(0);
System.out.println("======================= MyDataStreamRule.onMatch ====================");
}
}
public class MyFilterReduceExpressionRule extends RelOptRule {
public static final MyFilterReduceExpressionRule FILTER_INSTANCE = new MyFilterReduceExpressionRule(
operand(LogicalFilter.class, none()), "MyFilterReduceExpressionRule");
public MyFilterReduceExpressionRule(RelOptRuleOperand operand, String description) {
super(operand, "MyFilterReduceExpressionRule:" + description);
}
public MyFilterReduceExpressionRule(RelBuilderFactory relBuilderFactory) {
super(operand(LogicalFilter.class, any()), relBuilderFactory, null);
}
public MyFilterReduceExpressionRule(RelOptRuleOperand operand) {
super(operand);
}
#Override
public void onMatch(RelOptRuleCall arg0) {
System.out.println("======================= MyFilterReduceExpressionRule.onMatch ====================");
}
}

How to intercept subqueries in mybatis

I would like to log sql statements execution time. To do this I'm using interceptor plugin. However it only "catches" the outer statement and prints combined time needed to execute the whole statement including subqueries contained in #Result. Why does it not log all the statements separetely and is there any solution for this?
Here is the code reproducing my scenario:
ADao:
#Select({
"select * from a",
"where id = #{id,jdbcType=INTEGER}"
})
#Results({
#Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
#Result(column="id", property="bs", javaType=List.class, many=#Many(fetchType=FetchType.EAGER, select = "org.BDao.selectByAId")),
#Result(column="id", property="cs", javaType=List.class, many=#Many(fetchType=FetchType.EAGER, select = "org.CDao.selectByAId"))
})
A selectByPrimaryKey(Integer id);
BDao:
#Select({
"select * from b",
"where a_id = #{aId,jdbcType=INTEGER}"
})
#Results({
...
})
List<B> selectByAId(Integer aId);
CDao:
#Select({
"select * from c",
"where a_id = #{aId,jdbcType=INTEGER}"
})
#Results({
...
})
List<C> selectByAId(Integer aId);
Interceptor:
#Intercepts({ #Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class LogTimeQueryExecutePlugin implements Interceptor {
static int MAPPED_STATEMENT_INDEX = 0;
static int PARAMETER_INDEX = 1;
static int ROWBOUNDS_INDEX = 2;
static int RESULT_HANDLER_INDEX = 3;
static Logger logger = LoggerFactory.getLogger(LogTimeQueryExecutePlugin.class);
public Object intercept(Invocation invocation) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = invocation.proceed();
MappedStatement ms = (MappedStatement) invocation.getArgs()[MAPPED_STATEMENT_INDEX];
logger.info("Execution time "+ms.getId()+" : "+(System.currentTimeMillis() - start)+" ms");
return proceed;
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
Log:
Execution time org.ADao.selectByPrimaryKey : 59033 ms
Try StatementHandler.class instead of Executor.class.
#Intercepts({
#Signature(type = StatementHandler.class, method = "query", args = { Statement.class, ResultHandler.class }),
#Signature(type = StatementHandler.class, method = "update", args = { Statement.class })
})
public class StatementHandlerPlugin implements Interceptor {
#Override
public Object intercept(final Invocation invocation) throws Throwable {
// just for simplification, use safer way
val stmt = (StatementHandler) invocation.getTarget();
val boundSql = stmt.getBoundSql(); // contains sql, parameterObject, parameterMappings ...
// rest of implementation
}
// omitted
}

Categories