mercredi 31 janvier 2018

python mock Django settings variable

settings.py

IMAGE_LIMIT = 256

thumbnail_utils.py

from settings import IMAGE_LIMIT

def thumbnail():
    image_memory = 10   
    if image_memory > IMAGE_LIMIT:
        return Ture
    else:
        pass

test.py

@patch('thumbnail.IMAGE_LIMIT', '0')
def test_thumbnail(self, mock_IMAGE_LIMIT):
    status = thumbnail()
    assert status == False

The above is the wrong test.I urgently want to know how I should do it.

gradle beforeSuite{} & afterSuite{} executing multiple times

I have come across a problem today having to do with beforeSuite{} and afterSuite{}in Gradle. I have added a beforeSuite{} and an afterSuite{} to my testing task in gradle 4.1, however every time I execute my test it is running the closures multiple times. I think I have narrowed it down using -debug to multiple task actions being generated for a single task.

build.gradle:

task unzipfirefoxDriver(type: Copy) {
    //https://github.com/mozilla/geckodriver/releases
    def outputDir = file("$buildDir/webdriver/geckodriver")
    outputs.dir(outputDir)
    if (OperatingSystem.current().isWindows()) {
        from(zipTree("drivers/geckodriver-${gechoVersion}-win64.zip"))
    } else {
        from(tarTree("drivers/geckodriver-${gechoVersion}-macos.tar.gz"))
    }
    into(outputDir)
    def geckodriverFilename = OperatingSystem.current().isWindows() ? "geckodriver.exe" : "geckodriver"
    map.put("firefox", new File(outputs.files.singleFile, geckodriverFilename))

}

task firefoxTest(type: Test) {
    testLogging {
        events 'started', 'passed'
    }
    reports {
        html.destination = reporting.file("$name/tests")
        junitXml.destination = file("$buildDir/test-results/$name")
    }
    beforeSuite { desc ->
        println "Automation has Started"
    }
    afterSuite { desc, result ->
        println "Automation has Finished - Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, 
${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
    }
    outputs.upToDateWhen { false }
    systemProperty("webdriver.gecko.driver", map."firefox".absolutePath)
    systemProperty("geb.env", "firefox")
}
firefoxTest.dependsOn unzipfirefoxDriver

Debug information:

7:26:44.236 [INFO] [org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter] Executing task ':firefoxTest' (up-to-date check took 0.138 secs) due to:
Task.upToDateWhen is false.
17:26:44.237 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter] Executing actions for task ':firefoxTest'.
17:26:44.237 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Execute task action 1/5 for :firefoxTest' started
17:26:44.237 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute task action 1/5 for :firefoxTest'
17:26:44.237 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Execute task action 2/5 for :firefoxTest' started
17:26:44.237 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute task action 2/5 for :firefoxTest'
17:26:44.237 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Execute task action 3/5 for :firefoxTest' started
17:26:44.238 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute task action 3/5 for :firefoxTest'
17:26:44.238 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Execute task action 4/5 for :firefoxTest' started
17:26:44.238 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Execute task action 4/5 for :firefoxTest'
17:26:44.238 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Execute task action 5/5 for :firefoxTest' started
17:26:44.239 [DEBUG] [org.gradle.api.internal.file.delete.Deleter] Deleting ..../test-results/firefoxTest/binary
17:26:44.242 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Build operation 'Resolve files of :testRuntimeClasspath' started
17:26:44.242 [DEBUG] [org.gradle.internal.progress.DefaultBuildOperationExecutor] Completing Build operation 'Resolve files of :testRuntimeClasspath'
17:26:44.242 [QUIET] [system.out] Automation has Started
17:26:44.243 [DEBUG] [TestEventLogger] 
17:26:44.243 [DEBUG] [TestEventLogger] Gradle Test Run :firefoxTest STARTED

Terminal Output:

> Task :firefoxTest
Automation has Started
Automation has Started
Automation has Started

com.example.ReviewWidgetSpec > test 1 STARTED

com.example.ReviewWidgetSpec > test 1 PASSED

com.example.ReviewWidgetSpec > test 2 STARTED

com.example.ReviewWidgetSpec > test 2 PASSED

com.example.ReviewWidgetSpec > test 3 STARTED

com.example.ReviewWidgetSpec > test 3 PASSED
Automation has Finished - Results: SUCCESS (3 tests, 3 successes, 0 failures, 0 skipped)
Automation has Started
Automation has Finished - Results: SUCCESS (0 tests, 0 successes, 0 failures, 0 skipped)
Automation has Started
Automation has Finished - Results: SUCCESS (0 tests, 0 successes, 0 failures, 0 skipped)
Automation has Finished - Results: SUCCESS (3 tests, 3 successes, 0 failures, 0 skipped)
Automation has Finished - Results: SUCCESS (3 tests, 3 successes, 0 failures, 0 skipped)


BUILD SUCCESSFUL in 21s
4 actionable tasks: 1 executed, 3 up-to-date

This is my first post so I hope I got everything one might need to help me figure out this problem.

How to handle if statement for mockito tests and multiple when methods

I have a test that I am stuck in , it looks like this

 public CartItem addBookToCartItem(Book book, User user, int qty) throws AccessDeniedException {
        List<CartItem> cartItemList = findByShoppingCart(user.getShoppingCart());

        for (CartItem cartItem : cartItemList) {
            if (book.getId() == cartItem.getBook().getId()) {
                cartItem.setQty(cartItem.getQty() + qty);
                cartItem.setSubTotal(new BigDecimal(book.getOurPrice()).multiply(new BigDecimal(qty)));
                cartItemRepository.save(cartItem); //it shows there is a      problem with this line 
                return cartItem;
            }
        }

        CartItem cartItem = new CartItem();
        cartItem.setShoppingCart(user.getShoppingCart());
        cartItem.setBook(book);

        cartItem.setQty(qty);
        cartItem.setSubTotal(new BigDecimal(book.getOurPrice()).multiply(new BigDecimal(qty)));
        cartItem = cartItemRepository.save(cartItem);

        BookToCartItem bookToCartItem = new BookToCartItem();
        bookToCartItem.setBook(book);
        bookToCartItem.setCartItem(cartItem);

        bookToCartItemRepository.save(bookToCartItem);

        return cartItem;
    }

I am posting the whole code cause I don't know where the problem is and how to go about it . My test looks like this

 @Test
    public void addBookToCartItemTest() throws Exception {

      /// entities initialized here 
        List<CartItem> cartItemList = Arrays.asList(cartItem, cartItem1);

        when(cartItemRepository.findByShoppingCart(user.getShoppingCart())).thenReturn(cartItemList);

        for (CartItem item : cartItemList) {

            if (book1.getId() == item.getBook().getId()) {
                item.setQty(item.getQty() + qty);
                item.setSubTotal(new BigDecimal(book1.getOurPrice()).multiply(new BigDecimal(qty)));
                given(cartItemRepository.save(item)).willReturn(cartItem);

            }
        }

            CartItem newCartItem = new CartItem();
            newCartItem.setShoppingCart(user.getShoppingCart());
            newCartItem.setBook(book1);

            newCartItem.setQty(qty);
            newCartItem.setSubTotal(new BigDecimal(book1.getOurPrice()).multiply(new BigDecimal(qty)));

            when(cartItemRepository.save(newCartItem)).thenReturn(newCartItem);

            BookToCartItem bookToCartItem1 = new BookToCartItem();
            bookToCartItem1.setBook(book1);
            bookToCartItem1.setCartItem(newCartItem);

            when(bookToCartItemRepository.save(bookToCartItem1)).thenReturn(bookToCartItem1);

            cartItemService.addBookToCartItem(book1, user, qty);

            // Assert.assertNotNull(cartItem1);
            // Assert.assertEquals(newCartItem, cartItem1);

            Mockito.verify(cartItemRepository).save(newCartItem); //and this line also has a  problem
            Mockito.verify(bookToCartItemRepository).save(bookToCartItem1);
       // Mockito.verify(cartItemRepository).save(item);

error

Argument(s) are different! Wanted:
com.valentine.repository.CartItemRepository#0 bean.save(
    com.valentine.domain.CartItem@2f05be7f
);
-> at com.valentine.service.CartItemServiceTest.addBookToCartItemTest(CartItemServiceTest.java:110)
Actual invocation has different arguments:
com.valentine.repository.CartItemRepository#0 bean.save(
    com.valentine.domain.CartItem@640f11a1
);
-> at com.valentine.service.CartItemServiceImpl.addBookToCartItem(CartItemServiceImpl.java:48)

Comparison Failure:  <Click to see difference>

Argument(s) are different! Wanted:
com.valentine.repository.CartItemRepository#0 bean.save(
    com.valentine.domain.CartItem@2f05be7f
);

I think the problem is how tp handle the multiple when methods or is there another way to go about it , Any suggestion would suffice thank you .

Karate @RunWith(Karate.class) throwing Error

I am seeing below error when i am running my features with @RunWith(Karate.class)

I have found an an option to run with Junit which works fine however does not generate the karate reports. All my test cases are passing without any issues however i would like to run with Karate so that i get the nice report.

@RunWith(SpringRunner.class)
@CucumberOptions(tags = "~@ignore")
public class RestServicesDmaTestApplicationTests {

    @Test
    public void testABC(){
        CucumberRunner.runFeature(getClass(), "/features/ABC.feature",new HashedMap(),true);
    }
}

I am getting below error when i am running with Karate.

@RunWith(Karate.class)
@CucumberOptions(tags = "~@ignore",features = {"classpath:com/mastercard/send/features/ABC.feature})
public class KarateJunitTest {

    @BeforeClass
    public static void before() {
        System.setProperty("karate.env", "stage");
    }    
}



java.lang.NoSuchMethodError: ch.qos.logback.classic.encoder.PatternLayoutEncoder.encode(Ljava/lang/Object;)[B

            at com.intuit.karate.cucumber.ReporterLogAppender.append(ReporterLogAppender.java:72)
            at com.intuit.karate.cucumber.ReporterLogAppender.append(ReporterLogAppender.java:38)
            at ch.qos.logback.core.AppenderBase.doAppend(AppenderBase.java:82)
            at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51)
            at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:270)
            at ch.qos.logback.classic.Logger.callAppenders(Logger.java:257)
            at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:421)
            at ch.qos.logback.classic.Logger.filterAndLog_1(Logger.java:398)
            at ch.qos.logback.classic.Logger.info(Logger.java:583)
            at com.intuit.karate.ScriptBridge.log(ScriptBridge.java:164)
            at jdk.nashorn.internal.scripts.Script$Recompilation$5$18$\^eval\_.config(<eval>:7)
            at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:636)
            at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:229)
            at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:387)
            at jdk.nashorn.api.scripting.ScriptObjectMirror.call(ScriptObjectMirror.java:110)
            at com.intuit.karate.Script.evalFunctionCall(Script.java:1532)
            at com.intuit.karate.Script.call(Script.java:1489)
            at com.intuit.karate.Script.callAndUpdateConfigAndAlsoVarsIfMapReturned(Script.java:1606)
            at com.intuit.karate.ScriptContext.<init>(ScriptContext.java:131)
            at com.intuit.karate.StepDefs.<init>(StepDefs.java:81)
            at com.intuit.karate.cucumber.KarateObjectFactory.getInstance(KarateObjectFactory.java:80)
            at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
            at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
            at com.intuit.karate.cucumber.CucumberUtils.runStep(CucumberUtils.java:139)
            at com.intuit.karate.cucumber.KarateRuntime.runStep(KarateRuntime.java:80)
            at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
            at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
            at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
            at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
            at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
            at com.intuit.karate.junit4.Karate.runChild(Karate.java:118)
            at com.intuit.karate.junit4.Karate.runChild(Karate.java:33)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at com.intuit.karate.junit4.Karate.run(Karate.java:127)
            at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
            at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
            at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
            at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
            at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:497)
            at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

docker-compose execute command in sibling container

I am building an end to end test suite around a number of services. Some of these services aren't really services. They are actually procedural scripts which are run in sequence. These are executed at the command line and accept arguments, as you would expect a script to do.

We have docker images for these scripts/apps. I have compiled them into a docker-compose file. They are defined there as services which are sibling to the end to end test suite itself. So, for example:

docker-compose.yml

version: '3.4'
services:
  script:
    build: https://${GITHUB_ACCESS}:@github.com/company/script.git
    image: script:e2e
  e2e_tests:
    build: .
    image: e2e:e2e

Now, the e2e service needs to execute the script. Since the script isn't a service, I can't make a simple api call. How would I pass a command into the script container in order to execute it, from the e2e_tests container?

How to JUnit Test a Wicket Page

I've got the following Wicket Page which serves a PDF:

public class TestPage extends WebPage {    
  public TestPage(PageParameters pageParameters) {
        String param1 = pageParameters.get("test").toString();
        String param2 = pageParameters.get("test1").toString();
        [..]
        try {       
            byte[] generatedPDF= generatePDF(param1, param2, pdfGenerationOptions);
                RequestCycle requestCycle = RequestCycle.get();
                HttpServletRequest request = (HttpServletRequest) requestCycle.getRequest().getContainerRequest();
                requestCycle.replaceAllRequestHandlers(new ResourceRequestHandler(new PDFResource("test.pdf", request.getHeader(USER_AGENT), true), null));
        } catch (PdfGenerationException | IOException e) {
            LOGGER.error("error", e);
            new PageProvider(ErrorPage.class);
        }
    }

    @Override
    public void renderPage() {
        // left blank
    }
}

How would it be possible to test if the page returns a byte array (pdf) or the ErrorPage.class since I can only call the constructor in this case?

thanks in advance

How to debug MSTest while building on Bamboo CI?

I like to debug MSTests written in C# when these MSTests run as part of build on Bamboo CI (Continuous Integration) as these tests are running OK on my local machine but fails intermittently on Bamboo Server during build.

check test preconditions or not

let's say I have a functional test where I test whether user can buy some item. Precondition for the test is that user has enough money on his account. Therefore, before I run the test, I set enough money on the user account.

Is it OK just to check the result message of the "set money" call or is it a good practice to check also whether preconditions where executed successfully more verbosely? I mean, when there is a call to set money, there could also be a call, which returns current amount of money on user's account, which I would call after setting amount of money to make sure, user has enough money on his account, before I run the test. Of course, if the "set money" call is unreliable - often changes, then there is a reason, but otherwise?

Thanks for help.

Neural network accuracy rate flatlines / plateaus (doesn't go up or down)

I have created a neural network using Tensorflow to predict college admission decisions. A snippet of the dataset is as below (I have about 500 samples). GPA/SAT/ACT scores have been normalized while the rest have been hot-encoded. snippet of the dataset. All the numbers have been hot-encoded / normalized

But for some reason, whenever I train my data, the accuracy rate hits a ceiling and just stays at a fixed number.

accuracy rate

Visualization of the accuracy rate

I have tried different epochs, optimizers, samples, learning rates, regularizations, dropouts, but nothing seems to improve my model. I'm not sure if this is a bias problem, a variance problem, or something else. Please help me on why my accuracy is still and isn't moving.

Ruby Regular Expression match dimensions

Cirque Black Stone Effect Ceramic Floor Tile, Pack of 9, (L)333mm (W)333mm

I've created a block which iterates through a set of results i need to match the length (L)333mm and the width (W)333mm so I can add them to a database.

I've tried a few regular expressions but non of them are working now it feels like i'm just guessing.

product_description = product.at_css('h3 a').text[/\L[0-9\.]+mm/]

gives nil, can you please point me in the right direction

Visual Studio 2017: Run tests with Startup Projects

I have a solution containing a few projects, three of which startup when hitting the Start button, which are integral to the operation of the program. I have some tests, which have been found by Visual Studio and are inside the Test Explorer panel.

The question is: When I hit the Run All button inside the Test Explorer panel, how can I tell Visual Studio to startup the same projects as when I hit the Start button?

The only way I can see it being done is by using a *.testsettingsfile to use a Setup script that will run the projects, but it just feels like a dirty way of doing it.

Any ideas?

Why && better than -a in bash?

I've read man test and found:

NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead.

Can someone explain what ambiguously in -a and -o?

English is not my native language. As I understood, Kevin Braunsdorf and Matthew Bradburn (authors of this man page) advice us to use && instead of -a just because -a could be used as a key in another binaries, because -a could have different possible meanings.

So, -a is not associated with logical AND when we use test. It's not clear for someone, so people thinking like: "Hmm, what is that key? I don't know, not sure it is logical AND, I must visit man..."

The only reason I could find is that code with && is easier to read for people than code with -a (just an example):

With -a:

if [ -f "${my_var_with_filename}" -a -n "${my_another_array_var_with_filename[2]}" -o -r /just/path/to/file ]
then
...
fi

Same with &&:

if [ -f "${my_var_with_filename}" ] && [ -n "${my_another_array_var_with_filename[2]}" ] || [ -r /just/path/to/file ]
then
...
fi

As for me, both examples are syntactically complex, and it's hard to read bash code with multiple conditions, variables, array variables and logical operators.

So, my questions are:

  1. Do you agree with that -a and -o in test are "inherently ambiguous"?

  2. In multiple conditions, do you use -a(-o) or &&(||)?

  3. Someone has arguments to unequivocally name -a and -o "ambiguous"? Or it's just authors' opinion? Should they advice us to use && instead of -a based only on their opinion in man page?

java lang AssertionError For Service Test

I'm writing a Mockito test for a service method which looks like this but I am an error that says what I expect to save is not what I actually saved and the repositories are mocked by @MockBean annotations

 public CartItem addBookToCartItem(Book book, User user, int qty) throws AccessDeniedException {
        List<CartItem> cartItemList = findByShoppingCart(user.getShoppingCart());

        for (CartItem cartItem : cartItemList) {
            if (book.getId() == cartItem.getBook().getId()) {
                cartItem.setQty(cartItem.getQty() + qty);
                cartItem.setSubTotal(new BigDecimal(book.getOurPrice()).multiply(new BigDecimal(qty)));
                cartItemRepository.save(cartItem);
                return cartItem;
            }
        }

        CartItem cartItem = new CartItem();
        cartItem.setShoppingCart(user.getShoppingCart());
        cartItem.setBook(book);

        cartItem.setQty(qty);
        cartItem.setSubTotal(new BigDecimal(book.getOurPrice()).multiply(new BigDecimal(qty)));
        cartItem = cartItemRepository.save(cartItem);

        BookToCartItem bookToCartItem = new BookToCartItem();
        bookToCartItem.setBook(book);
        bookToCartItem.setCartItem(cartItem);
        bookToCartItemRepository.save(bookToCartItem);

        return cartItem;
    }

I have written a test which I think is ideal and should pass but I get a null value in my assertion Test:

 @RunWith(SpringRunner.class)
    @SpringBootTest(classes = CartItemServiceImpl.class)
    public class CartItemServiceTest {

        @Test
            public void addBookToCartItemTest() throws Exception {


                Book bookForCart = new Book();
                        bookForCart.setOurPrice(12);

                ShoppingCart myCart = new ShoppingCart();
                myCart.setId(1L);
                 //cart do somethin
                User userForCart = new User();
                userForCart.setId(2L);

                int qtyForBook = 5;

                CartItem cartItem = new CartItem();

                cartItem.setShoppingCart(userForCart.getShoppingCart());


                when(cartItemRepository.save(cartItem)).thenReturn(cartItemme);

                BookToCartItem bookToCartItem = new BookToCartItem();
                bookForCart.setId(1L);

                bookToCartItem.setBook(bookForCart);

                bookToCartItem.setCartItem(cartItemme);

                BookToCartItem bookToCartItem1 = new BookToCartItem();

                when(bookToCartItemRepository.save(bookToCartItem)).thenReturn(bookToCartItem1);

                CartItem cartItem1  =  cartItemService.addBookToCartItem(bookForCart, userForCart, qtyForBook);

                 Assert.assertNotNull(cartItem1);
                Mockito.verify(cartItemRepository).save(cartItem1);
                Mockito.verify(bookToCartItemRepository).save(bookToCartItem);

        }
    My log

        Argument(s) are different! Wanted:
        com.valentine.repository.CartItemRepository#0 bean.save(
            com.valentine.domain.CartItem@78365cfa
        );
        -> at com.valentine.service.CartItemServiceTest.addBookToCartItemTest(CartItemServiceTest.java:112)
        Actual invocation has different arguments:
        com.valentine.repository.CartItemRepository#0 bean.save(
            com.valentine.domain.CartItem@64a8c844
        );
        -> at com.valentine.service.CartItemServiceImpl.addBookToCartItem(CartItemServiceImpl.java:59)

Now it says cart item saved is not what I get in return, yes but why and what can to do to correct it?

Body is empty when using MockMvc



> @RunWith(SpringRunner.class) @WebMvcTest(CustomerController.class)
> public class CustomerControllerMvcTest {
> 
>   @Autowired  private WebApplicationContext wac;
> 
>   private MockMvc mockMvc;
> 
>   @MockBean   private ICustomerService customerService;
> 
>   @Before     public void before() {      MockitoAnnotations.initMocks(this);
>       this.mockMvc =
> MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
>   }
> 
>   @Test   public void getTaskByUserdId1() throws Exception {      String
> expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";         this.mockMvc
>               .perform(
>                       MockMvcRequestBuilders.get("/customer/get/vikas").accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
>               .andExpect(status().isOk()).andExpect(content().string(expectedOutput));
>   }
> 
>   @Test   public void getTaskByUserdId2() throws Exception {      String
> expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";
>       this.mockMvc.perform(get("/customer/get/vikas")).andDo(print()).andExpect(status().isOk())
>               .andExpect(content().string(containsString(expectedOutput)));   } }


It always gives empty body:



> MockHttpServletRequest:
>       HTTP Method = GET
>       Request URI = /customer/get/vikas
>        Parameters = {}
>           Headers = {}
> 
> MockHttpServletResponse:
>            Status = 200
>     Error message = null
>           Headers = {}
>      Content type = null
>              Body = 
>     Forwarded URL = null    Redirected URL = null
>           Cookies = []


It is working fine when i use TestRestTemplate. But, when I use MockMvc and @MockBean, it always gives empty output. I have also used com.gargoylesoftware.htmlunit.WebClient. But, that also gives empty body. I don't know what is happening. Please help. Is it a version issue or i am doing something wrong? Spring boot version: 1.5.10

When to use mock and when to use stub with spock?

i want to understand more this sentence found in grails documentation : 'If the test is concerned with proving that the test subject interacts with a collaborator in a particular way, use a mock. If the fact that a collaborator behaves in a certain way exposes a particular behavior in the test subject the outcome of that behavior is what you are testing, use a stub' . Thanks

Why Won't These Jest Mocks Reset?

I have test code that is effecting other tests and causing them to fail. When I run test cases in isolation everything passes, but when I run the entire suit there are many failures. If you look at both tests below you can see I override a mocked module within the test to cause an exception to be thrown.

HttpService.post = jest.fn(() => {
          return Promise.reject({ payload: 'rejected' });
        });

after this line has been run, all tests that need the original HttpService.post mock fail because they aren't reset. How can I properly restore my mock to the imported mock after this test? I have tried jest.resetMock in a beforeEach and about every jest method like it but nothing has worked. I know the answer is probably straight forward but I am confused with all of the differences I read about online around how code is imported (es6 import, commonJs). Thanks!

import HttpService from '../../services/httpService';
import handleErrors from '../../utilities/handleErrors';

jest.mock('../../services/httpService');
jest.mock('../../utilities/handleErrors');

describe('async actions', () => {

  beforeEach(() => {
    store = mockStore({});
  });

  describe('some describe that wraps both tests', () => {

    describe('a describe that wraps just the first test', () => {
      test(`creates ${constants.actions.REQUEST_SAVE_NOTE_FAILURE}`, () => {
        HttpService.post = jest.fn(() => {
          return Promise.reject({ payload: 'rejected' });
        });
        const expectedActions = [
          { type: constants.actions.REQUEST_SAVE_NOTE },
          { type: constants.actions.REQUEST_SAVE_NOTE_FAILURE, data: { payload: 'rejected' } },
        ];
        return store.dispatch(actions.saveNote({
          id: 1,
          note: 'note',
        })).then(() => {
          expect(store.getActions()).toEqual(expectedActions);
        });
      });
    });

    describe('a describe that wraps just the second test', () => {
      test(`creates ${constants.actions.REQUEST_SAVE_NOTE}
        and ${constants.actions.RECEIVE_SAVE_NOTE}`, () => {
        params = {
          body: {
            prospects: [1],
            note: 'note',
          },
        };
        const expectedActions = [
          { type: constants.actions.REQUEST_SAVE_NOTE },
          { type: constants.actions.RECEIVE_SAVE_NOTE, data: { payload: 'payload' } },
        ];

        return store.dispatch(actions.saveNote({
          id: 1,
          note: 'note',
        })).then(() => {
          expect(store.getActions()).toEqual(expectedActions);
          expect(HttpService.post).toBeCalledWith({ ...params, url: '/api/prospect/add-note' });
        });
      });
    });

  })

});

Night watch change value of textContent or innerHTML

I have the following markup and I need to be able to change the values of the textContent for these items:

<div class=".react-grid-HeaderCell-sortable">Jamie</div>
<div class=".react-grid-HeaderCell-sortable">Hutber</div>
<div class=".react-grid-HeaderCell-sortable">Stackoverflow</div>

I know how to change values for input fields, but currently don't know how to do text, maybe with a custom command?

For inputs

  .setValue('.someSelector', 'anewString')

Downloading a file using WireMoc

I'm new to WireMoc. How do i go about Downloading a file using WireMoc stubbing framework? This is what i have so far

     var stub = FluentMockServer.Start(new FluentMockServerSettings
        {
            Urls = new[] { "http://+:5001" },
            StartAdminInterface = true
        });

     stub.Given(
                Request.Create()
                    .WithPath("/myFile")
                    .UsingPost()
                    .WithBody("download file"))
            .RespondWith(Response.Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/multipart")

Codeception custom SQL query to DROP a dynamic mysql database

I'm starting with codeception verison 2.3.4; In an application with many msql databases, I have created a Helper to change to the given DB using

$this->getModule('Db')->_reconfigure

I'm struggling now to DROP the given Database without success, how can I achieve this task ?

Thanks a lot.

File system operation validation at C standard library level

I'm implementing an alternative C standard library with file operation support.

I'm planning to support both:

I'm looking for a test suite which validates my implementation against standard C requirements (example: validates that pread returns zero when the caller requests read beyond the file contents).

I'll be happy for your suggestions.

get values out from elements webdriver with Nightwatch/Selenium

I need to be able to get the values out of elements using nightwatch, but I cannot seem to do it at all

module.exports = {
  tags: ['someTest'],
  'Test login': function (browser) {
       browser
      .elements('css selector', '.react-grid-Header .react-grid-HeaderCell-sortable', (items) => {
        items.value.forEach(item => {
          item //{...}
          item.ELEMENT //123123123.12 (an id of some sort)?
          console.info(driver.findElement(By.id(item.ELEMENT))); //driver is undefined
        });
      })
    }
}

Jmeter add Timestamp in wss

I need to put a test SOAP in Jmeter. This test is signed by Jmeter element "SOAP Message Signer". I sign Timestamp, body and binary security token. When i send test, this test send well but I'm not found timestamp element inside wssecurity tags like:

<wsu:Timestamp wsu:Id="TS-C5B52CA211571174C9151739434007851">
        <wsu:Created>2018-01-31T10:25:40.078Z</wsu:Created>
        <wsu:Expires>2018-01-31T13:12:20.078Z</wsu:Expires>
    </wsu:Timestamp>

I need to put this element inside wss with Jmeter . Anyone knows how can i do it? Thnx.

In app purchase test with real payment for Apple

I developed an ios app that provide in app purchase.I tested in app purchase with Sendbox test user succesfully but I want to make a test with real payment like real credit cart. By the way my app is in testflight. I didnt submit for review apple store. Can I get payment with real credit card even my app is still in testFlight ?

angular testing unable to test component method

i was trying to write tests for my component that has a display() method that makes an request to service and assigns them to an array this is my component

    import { Ialbums } from './../ialbums';
import { AlbumService } from './../album.service';
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-album',
  templateUrl: './album.component.html',
  styleUrls: ['./album.component.css']
})
export class AlbumComponent implements OnInit {
albums: Ialbums[];
response:  Ialbums[];
start: number;
limit: number;
x: any;
pi: number = 1;
  constructor(private albumservice: AlbumService) {
   // this.albums = this.albumservice.getImages(10,5);
  this.start = 0;
    this.limit = 10;

  }

  ngOnInit() {
  }
  display(a)
  {
    if( a < 0 || a > 5000)
    {
      alert('enter a positive and max number is 5000');
    }else {
    this.albumservice.getImages(this.start, a).subscribe(response => {
      this.albums = response;
      // console.log(this.albums);
     // this.albums = response;
    });
  }
    // console.log(a);
  }
  displayimage(b)
  {
    this.x = b;
  }
}

then this is my service

import { Ipersons } from './ipersons';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Ialbums } from './ialbums';

@Injectable()
export class AlbumService {
  albums: any;
  persons: any;
  constructor(private http: HttpClient) {
   }
   getImages(start, limit)
   {
     const url = 'https://jsonplaceholder.typicode.com/photos?_start='+start+'&_limit='+limit;
      return this.http.get<Ialbums[]>(url);
   }
   getPersons(id)
   {
     const url= 'https://jsonplaceholder.typicode.com/users/'+id;
     return this.http.get<Ipersons[]>(url);
   }
}

this is how i am trying to test it

import { AlbumService } from './../album.service';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { AlbumComponent } from './album.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgxPaginationModule } from 'ngx-pagination';
describe('AlbumComponent', () => {
  let component: AlbumComponent;
  let fixture: ComponentFixture<AlbumComponent>;
  const getImages = null;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AlbumComponent ],
      imports: [
        HttpClientModule,
        NgxPaginationModule
      ],
      providers: [AlbumService, HttpClient]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AlbumComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  fit('should return eligible', async(() => {

    const initvalue = 1;
     component.display( initvalue );
     fixture.detectChanges();
    expect(component.albums[0].id).toBe(4);
  }));
});

this returns Cannot read property '0' of undefined i am aware that is should be using spy or something instead of actually requesting api for testing but i am not familiar with those methods if you can please explain or make this work!!!Thanks..

Is there any configuration to avoid skipped after falied one test cases in nightwatch?

I have a test automation framework for regression test cases using nightwatch. Now the problem with this framework is: all cases skiped one case is failed.

Is there any configuration to avoid skipped after falied one test cases in nightwatch?

SyntaxError: Unexpected identifier in selenium-webdriver/lib/http.js:454 async execute(command)

I have recently installed selenium-webdriver javascript(node) client 3.6.0

steps are follows;

# npm install webdriver
# npm install selenium-webdriver
# npm install chromedriver

install them into my project folder

then make a js file into that name "library.js"

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('chrome').build();
By = webdriver.By,
until = webdriver.until;


driver.get('www.google.co.in');

enter image description here

This is showing async execute(command) error at require('selenium-webdriver')

node version V7.1.0.

npm version 3.10.9

chrome Version - ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

Help my in this how to run this

Django Test Not Getting Model Object

I am just scratching the surface of testing in Django. Here is my testing code, inside tests.py:

class AdvertisingTests( TestCase ):

    def test_get_ad( self ):
        '''
        Test if the get ad feature is working, should always load an ad
        '''
        url = reverse('advertising:get_ad')
        response = self.client.get( url )
        self.assertEqual(response.status_code, 200)

This test is just a basic test of a view that should return an Ad. Here is the view code:

from .models import Ad, Impression

def get_ad(request):
    FirstAd = Ad.objects.first()

    # +1 impression
    Impression.objects.create(ad = FirstAd)

    import json
    data = { 'url': FirstAd.url, 'image_url': FirstAd.image.url, 'title': FirstAd.title, 'desc': FirstAd.desc }
    json_data = json.dumps( data )
    return HttpResponse(json_data, content_type='application/json')

I am working in a heroku local environment, so I run the tests like this: heroku local:run python manage.py test advertising

And this test fails, coming from the Impression.objects.create(ad = FirstAd) line:

ValueError: Cannot assign None: "Impression.ad" does not allow null values.

What that tells me is that the FirstAd object is null. OK so I wind up the local shell like this: heroku local:run python manage.py shell to double check. Replicating that code there are no errors:

In [2]: from advertising.models import Ad, Impression

In [3]: print Ad.objects.first()
Flamingo T-Shirt Corporation

In [4]: FirstAd = Ad.objects.first()

In [5]: Impression.objects.create(ad = FirstAd)
Out[5]: <Impression: Impression object>

In [6]: exit()

So I am a little bit stuck. It seems like the tester is accessing an empty database. Is this the correct and desired functionality of the testing suite?

THANKS!

Dynamic parameter cannot be resolved in Gauge

i try to use the file special parameter in a Gauge specification.

Export a customer
----------------------------------------
* Find customer "Hans"
* Export customer to <file:/customer.xml>

The java implementation for this looks like this

@Step("Export tenant to <file>")
public void test(String file) {
   System.out.println("file " + file);
}

I assume the parameter typ is String (can it also be File ?)

But nevertheless, running this, returns

[ParseError] C:\Users\user\IdeaProjects\qmsgauge\specs\tenantManagement.spec:40 
 Dynamic parameter <file:/customer.xml> could not be resolved => 'Export customer to <file:/customers.xml>'
Successfully generated html-report to => C:\Users\user\IdeaProjects\qmsgauge\reports\html-report\index.html

How do I define the file parameter in the spec and how do need to write the java implementation for this ?

Thanks

Nightwatch click event on anchor not working in edge

I've written a command in Nightwatch to test a takeover element. The test works fine in Chrome only it does NOT in Edge.

What i've noticed is that the click function on the first two anchor elements is not triggered. If i manually click them it closes them as expected. The click event does work on the button elements which are lower in the DOM.

Here's my command:

exports.command = function(client) {
    client.elements('css selector', '[data-action="takeover"]', function(elements) {
      elements.value.forEach(function(element){
        client.elementIdAttribute(element.ELEMENT, 'data-rel', function(attribute) {

          client
          .click('css selector', "[data-rel='"+attribute.value+"']")
          .waitForElementVisible(''+attribute.value+'', 5000)
          .collapsibleInTakeover(attribute.value, client)
          .keys(client.Keys.ESCAPE)
          .pause(250)
          .waitForElementNotVisible(''+attribute.value+'', 5000)
        });
      });
    });
    return;
};

Selenium Grid Parallel Test Is Not Work Parallel

Hello I have two node which names are Node1 and Node2 and I do this tests in one computer. My problem is Node1 and Node2 tests doesn't work same time so They are not parallel. Thus when Node1 is finish after Node2 test start but I don't want it , I want them start together.I have already tried parallel="tests" and parallel="classes" in the TestNG.xml file.

This is my Node1.java file:

package grid;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public class Node1 {
    WebDriver driver;
    String nodeUrl;
  @Test
  public void f() {
        try {
            //configuration
            nodeUrl= "http://192.168.56.1:5555/wd/hub";
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            capabilities.setBrowserName("chrome");
            capabilities.setPlatform(Platform.WIN10);
            driver = new RemoteWebDriver(new URL(nodeUrl), capabilities);

            //test scripts
            driver.manage().deleteAllCookies();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
            driver.get("https://www.amazon.com/");
            driver.findElement(By.linkText("Today's Deals")).click();
            driver.findElement(By.linkText("Gift Cards")).click();
            driver.findElement(By.linkText("Today's Deals")).click();
            driver.findElement(By.linkText("Gift Cards")).click();
            driver.findElement(By.linkText("Today's Deals")).click();
        } 
        catch (MalformedURLException e) {       
            e.printStackTrace();            
        }
  }
}

This is my Node2.java file :

package grid;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public class Node2 {    
    WebDriver driver;
    String nodeUrl;
  @Test
  public void f() {
        try {
            //configuration
            nodeUrl= "http://192.168.56.1:5555/wd/hub";
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            capabilities.setBrowserName("chrome");
            capabilities.setPlatform(Platform.WIN10);
            driver = new RemoteWebDriver(new URL(nodeUrl), capabilities);

            //test scripts
            driver.manage().deleteAllCookies();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            driver.manage().timeouts().pageLoadTimeout(45, TimeUnit.SECONDS);
            driver.get("https://www.google.com/");
        } 
        catch (MalformedURLException e) {       
            e.printStackTrace();            
        }
  }
}

And this is my TestNG.xml file :

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Test Grid" parallel="tests">
    <test name="Test Node1">
        <classes>
            <class name="grid.Node1" />
        </classes>
    </test>
    <test name="Test Node2">
        <classes>
            <class name="grid.Node2" />
        </classes>
    </test>
</suite>

mardi 30 janvier 2018

Identity hash check failed when testing Room migrations

I am writing a test following these instructions. My test class has this rule:

@Rule
public MigrationTestHelper testHelper = new MigrationTestHelper(
        InstrumentationRegistry.getInstrumentation(),
        AppDatabase.class.getCanonicalName(),
        new FrameworkSQLiteOpenHelperFactory()
);

and my test is as follows:

@Test
public void testMigration9_10() throws IOException {
    // Create the database with version 9
    SupportSQLiteDatabase db = testHelper.createDatabase(TEST_DB_NAME, 9);

    // Insert before migration
    ContentValues values = new ContentValues();
    values.put("rowid", 1);
    ...
    db.insert("foo", SQLiteDatabase.CONFLICT_FAIL, values);

    // Check inserted data
    Cursor c = db.query("SELECT * FROM foo WHERE rowid = " + values.get("rowid"));
    Assert.assertTrue(c.moveToFirst());
    Assert.assertEquals(c.getString(c.getColumnIndex("rowid")), values.get("rowid"));

    // Migrate
    db = testHelper.runMigrationsAndValidate(TEST_DB_NAME, 10, true, DatabaseCreator.MIGRATION_9_10);
    ...
}

But this fails at the last line (the previous assertions went well), saying this:

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

Which is wrong. I have traced what happens:

  • create the database with the version 9 identity hash
  • insert data
  • check data
  • call runMigrationsAndValidate, which:
    • opens the database
    • checks the identity hash against version 10, and fails

When checking the identity hash, it does:

private void checkIdentity(SupportSQLiteDatabase db) {
    createMasterTableIfNotExists(db);
    String identityHash = "";
    Cursor cursor = db.query(new SimpleSQLiteQuery(RoomMasterTable.READ_QUERY));
    //noinspection TryFinallyCanBeTryWithResources
    try {
        if (cursor.moveToFirst()) {
            identityHash = cursor.getString(0);
        }
    } finally {
        cursor.close();
    }
    if (!mIdentityHash.equals(identityHash)) {
        throw new IllegalStateException("Room cannot verify the data integrity. Looks like"
                + " you've changed schema but forgot to update the version number. You can"
                + " simply fix this by increasing the version number.");
    }
}

So the loaded identityHash is the one loaded from the DB, which is in version 9; and mIdentityHash is the one loaded directly by runMigrationsAndValidate using the version parameter, which is 10.

So of course it fails.

I'm wondering why it is checking the identity hashes BEFORE doing the migrations.

Here's the migration, even if I think it's not relevant here:

public static final Migration MIGRATION_9_10 = new Migration(9, 10) {
    @Override
    public void migrate(@NonNull SupportSQLiteDatabase database) {
        database.beginTransaction();
        database.execSQL("ALTER TABLE DeclarationEntity ADD latitude REAL NOT NULL DEFAULT 0.0");
        database.execSQL("ALTER TABLE DeclarationEntity ADD longitude REAL NOT NULL DEFAULT 0.0");
        database.endTransaction();
    }
};

Did I do something wrong?

PS: here's the full stack trace in case this is interesting:

at android.arch.persistence.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:119)
at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:100)
at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onOpen(FrameworkSQLiteOpenHelper.java:133)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:282)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:175)
at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:93)
at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
at android.arch.persistence.room.testing.MigrationTestHelper.openDatabase(MigrationTestHelper.java:203)
at android.arch.persistence.room.testing.MigrationTestHelper.runMigrationsAndValidate(MigrationTestHelper.java:193)

I'm using (versions.arch being 1.0.0):

implementation "android.arch.persistence.room:runtime:${versions.arch}"
annotationProcessor "android.arch.persistence.room:compiler:${versions.arch}"
androidTestImplementation "android.arch.persistence.room:testing:${versions.arch}"

Need to count the number of emails in a string using Capybara/RSpec

So I have an application which holds multiple entries that are strings of comma separated emails. The strings live in text area elements where they can be modified. The application uses JavaScript to modify these strings, I need to use Capybara to watch verify that a target string has the correct number of emails in it. To illustrate what I mean here's my Cucumber (assuming the target list starts with a 5 email string):

When I remove the 3rd email under list one
Then I should see 4 emails under list one
When I click the "Cancel" button for list one
Then I should see 5 emails under list one

I can pretty easily grab the string with Capybara like so:

expect(page).to have_css(".css-selectors textarea")

but I don't know what to do from there. I need to be able to assert that the number of emails in the string is in fact changing to the desired number. I need to split the string and count the number of emails to see if they match the target number, but everything I've tried leads to a race condition where Capybara checks the value before the JS can finish updating. I've looked into passing a filter block to the have_css call but I can't find documentation on how that would work, or if it's even the right tactic. And so I'm out of ideas here.

Failing Maven test JUnit5 test programmatically

I do execute my Maven tests with JUnit5, where all the test classes have the

@ExtendWith({ProcessExtension.class})

annotation. This extension must fail test methods according to a special logic in the if it is the case. But I have no idea how.

The method

@Override
public void afterEach(ExtensionContext context) {
    ...
}

gets this context parameter but the is no way to fail the already executed test method. How could I notify the Maven that the method has failed?

KI

Jest testing component getting "TypeError: (0 , _reactRouter.withRouter) is not a function"

This is a whopper.

I recently updated from react-router 3 to react-router 4. My single page app compiles via webpack just fine, and I can navigate my local dev version just fine in the browser.

However, tests that involve components that are wrapped with the withRouter HOC fail.

Specifically, if the component being tested has a descendant component that uses the withRouter HOC, you can't even import withRouter. A console log shows that withRouter is imported as "undefined"

The folder has the following files.

app/
├── src/
    ├── LoginContainer.jsx
    ├── LoginForm/
        ├── index.js
        └── LoginForm.jsx

LoginContainer (A react container component)

import React from 'react';
import PropTypes from 'prop-types';
import LoginForm from './LoginForm';

export default class LoginContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentForm: props.form };
    this.changeForm = this.changeForm.bind(this);
  }

  changeForm(form) {
    // handle when someone changes something.
  }

  render() {
    return (
      <section>
        <LoginForm {...this.props} changeForm={this.changeForm} data-form={this.state.currentForm} />
      </section>
    );
  }
}

LoginForm/index.js (basically a HOC that wraps LoginForm.jsx)

import LoginForm from './LoginForm';
import { withRouter } from 'react-router';

// NO MATTER WHAT I DO...
// withRouter is undefined.
// If I do import * as bob from 'react-router'
// bob then equals { default: {} }
// bob is blank!

export default withRouter(LoginForm);

For some reason, I can't import withRouter when testing. All other modules import just fine, only withRouter is causing issues.

  • react-router and react-router-dom are both installed as dependencies
  • Other components that use things like Link or Route pass tests just fine

Button outcomes in Zombie.js tests

I'm trying to write some tests for my bowling scorecard. I mainly want to use it to check the totals of various score entry combinations. But I'm finding it difficult in getting the correct syntax to refer to the buttons.

I'm also wondering if I should give each bowl a separate id tag to make the expect easier. If not I would have to find a way of using an index number of the spans to refer to that.

index.html

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="css/styles.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <title>Bowling Scorecard</title>
</head>

<body>

  <h2>Bowling Scorecard</h2>

  <div class="scorecard">
    <table>
      <tr class="frame-title-container">
        <th></th>
        <th>Frame 1</th>
        <th>Frame 2</th>
        <th>Frame 3</th>
        <th>Frame 4</th>
        <th>Frame 5</th>
        <th>Frame 6</th>
        <th>Frame 7</th>
        <th>Frame 8</th>
        <th>Frame 9</th>
        <th>Frame 10</th>
      </tr>
      <tr class="score-container">
        <td id="name">Player 1</td>
        <td class="frame-one">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-two">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-three">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-four">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-five">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-six">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-seven">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-eight">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-nine">
          <div><span class="first"></span>&emsp;<span class="second"></span></div>
          <br>
          <div class="total"></div>
        </td>
        <td class="frame-ten">
          <div><span class="first"></span>&emsp;<span class="second"></span>&emsp;<span id=frame-ten-third></span></div>
          <br>
          <div class="total"></div>
        </td>
      </tr>
    </table>
  </div>
  <br>
  <div class="score-inputs">
    <form class="buttons">
      <input id="0" class="button" type="button" value="0"></input>
      <input id="1" class="button" type="button" value="1"></input>
      <input id="2" class="button" type="button" value="2"></input>
      <input id="3" class="button" type="button" value="3"></input>
      <input id="4" class="button" type="button" value="4"></input>
      <input id="5" class="button" type="button" value="5"></input>
      <input id="6" class="button" type="button" value="6"></input>
      <input id="7" class="button" type="button" value="7"></input>
      <input id="8" class="button" type="button" value="8"></input>
      <input id="9" class="button" type="button" value="9"></input>
      <input id="10" class="button" type="button" value="10"></input>
    </form>
  </div>

  <script src="src/interface.js"></script>

</body>

</html>

styles.css

table {
  border-collapse: collapse;
  border: 1px solid black;
}

th {
  border: 1px solid black;
}

td {
  text-align: center;
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

.innercell {
  height: 50px;
  width: 50px;
}

input {
  width: 50px;
  height: 25px;
}

.button[disabled] {
  background-color: #ccc;
}

interface.js

$(document).ready(() => {
  var allSpans = $("span");
  var totalClass = $(".total");
  var frameBowlIndex = 0;
  var frameTotalIndex = 0;
  var scoreCardArray = [];
  var spare = false;
  var strike = false;
  var runningTotal = 0;

  $(".button").click(function() {
    var bowlValue = $(this).val();
    updateScore(bowlValue);
  });

  var updateScore = function(bowlValue) {
    bowlValue = parseInt(bowlValue);
    scoreCardArray.push(bowlValue);
    hideButtonsIfSumOverTen(bowlValue);
    addSingleScoreToPage(bowlValue);
    ifStrikeNextBowlZero(bowlValue);
    calculateTotals();
    frameBowlIndex++;
  };

  var calculateTotals = function() {
    if (hasEvenIndex(scoreCardArray)) {
      addBowlsToTotal();
      addBonus();
      addTotalToPage(runningTotal);
      spareOrStrikeChecker();
      frameTotalIndex++;
      resetButtons();
    }
  };

  var addBonus = function() {
    if (spare) {
      addSpareBonus();
    }
    if (strike) {
      addStrikeBonus();
    }
  };

  var addBowlsToTotal = function() {
    var currentFrameTotal = bowlIndexFromLast(1) + bowlIndexFromLast(2);
    runningTotal += currentFrameTotal;
  };

  var bowlIndexFromLast = function(index) {
    return scoreCardArray[scoreCardArray.length - index];
  };

  var spareOrStrikeChecker = function() {
    var firstBowl = bowlIndexFromLast(2);
    var secondBowl = bowlIndexFromLast(1);
    isStrike(firstBowl, secondBowl);
    isSpare(firstBowl, secondBowl);
  };

  var isSpare = function(firstBowl, secondBowl) {
    if (firstBowl + secondBowl === 10 && secondBowl !== 0) {
      spare = true;
    }
  };

  var isStrike = function(firstBowl, secondBowl) {
    if (firstBowl === 10) {
      strike = true;
    }
  };

  var ifStrikeNextBowlZero = function(bowlValue) {
    if (bowlValue === 10 && !hasEvenIndex(scoreCardArray)) {
      frameBowlIndex++;
      addSingleScoreToPage(0);
      scoreCardArray.push(0);
    }
  };

  var addSpareBonus = function(total) {
    if (spare) {
      var firstBowlBonus = bowlIndexFromLast(2);
      var newPrevTotal = getPrevTotal() + firstBowlBonus;
      editPrevTotalToPage(newPrevTotal);
      runningTotal += firstBowlBonus;
      spare = false;
    }
  };

  var addStrikeBonus = function() {
    if (strike) {
      currentTotalBonus = bowlIndexFromLast(1) + bowlIndexFromLast(2);
      var newPrevTotal = getPrevTotal() + currentTotalBonus;
      editPrevTotalToPage(newPrevTotal);
      runningTotal = newPrevTotal + currentTotalBonus;
      strike = false;
    }
  };

  var getPrevTotal = function() {
    return parseInt(totalClass[frameTotalIndex - 1].innerText);
  };

  var hideButtonsIfSumOverTen = function(bowlValue) {
    if (bowlValue !== 10) {
      var remainingPins = 10 - bowlValue;
      var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

      array.forEach(function(value) {
        if (value > remainingPins) {
          $(`#${value}`).hide();
        }
      });
    }
  };

  var resetButtons = function() {
    $(".button").show();
  };

  var hasEvenIndex = function(array) {
    return array.length % 2 == 0;
  };

  var sumArray = function(array) {
    return array.reduce((a, b) => a + b, 0);
  };

  var addSingleScoreToPage = function(bowlValue) {
    bowlsSpan().innerText = bowlValue;
  };

  var addTotalToPage = function(total) {
    totalSpan().innerText = total;
  };

  var editPrevTotalToPage = function(total) {
    prevTotalSpan().innerText = total;
  };

  var bowlsSpan = function() {
    return allSpans[frameBowlIndex];
  };

  var totalSpan = function() {
    return totalClass[frameTotalIndex];
  };

  var prevTotalSpan = function() {
    return totalClass[frameTotalIndex - 1];
  };
});

intergration-test.js

const Browser = require("zombie");
const assert = require("assert");

url = "http://localhost:8080/";

describe("User visits page", function() {
  const browser = new Browser();

  before(function() {
    return browser.visit(url);
  });

  describe("zombie js works", function() {
    it("title of page should be Bowling Scorecard", function() {
      browser.assert.text("title", "Bowling Scorecard");
    });
  });

  describe("elements exist on page", function() {
    it("there is are containers on the page", function(done) {
      browser.assert.element(".scorecard");
      browser.assert.element(".frame-title-container");
      browser.assert.element(".score-container");
      done();
    });
  });

Top two tests pass, but I want the bottom one something like that.

  describe("button outcomes", function() {
    it("clicking a button shows it on the scorecard", function(done) {
      browser.pressButton("1");
      browser.assert.text("span", "1");
      done();
    });
  });
});

This gives me an error of;

1) User visits page
       button outcomes
         clicking a button shows it on the scorecard:

      AssertionError [ERR_ASSERTION]: '' deepEqual '1'
      + expected - actual

      +1

      at assertMatch (node_modules/zombie/lib/assert.js:24:212)
      at Assert.text (node_modules/zombie/lib/assert.js:370:7)
      at Context.<anonymous> (test/intergration-test.js:31:22)

It might be easier to clone this repo and run zombie there. That will not include the third test attempt, just the two passing ones.

git clone git@github.com:puyanwei/bowling-scorecard.git
cd bowling-challenge
npm install
npm start
npm test

I'm sure that my application has a lot of bad practices, but for now I'm just focusing on getting my tests working so that I can refactor later on. Thanks in advance.

GoogleSignIn in Firebase Test Lab: com.google.android.gms.common.api.ApiException: 12501

I would like to inquire if the shack has passed or has the solution to this situation. The Beta APP performs the authentication correctly, however when running tests in the Firebase Test Lab I always receive the authenticity failure along with the warning: com.google.android.gms.common.api.ApiException: 12501

test scenario for profile uploading process

i have been having issue putting the test scenario together... i will appreciate your input to finding solution to this thank you.

write scenarios in an excel spreadsheet to test the profile photo uploading process on the WalletHub account provided below. Sign in and go to the settings page https://wallethub.com/home/settings/ in order to do so. Create all the possible scenarios that would thoroughly test that the profile photo function is working correctly for a wide diversity of photos. Be specific with the instructions you provide for your scenarios and provide as much detail as possible so that another tester would be able to follow your instructions without any questions. As you go through the uploading process, you must confirm each time that the image becomes visible on the profile page, https://wallethub.com/profile/3020219i/ Next to each testing scenario please record if it worked ok and if not what issue you observed. Sign into https://wallethub.com/ with: Username: test_inscomp@evolutionfinance.com Password: Abcd123* Please don't change the credentials and use just the ones provided.

Ensure mysql transaction fails

I want to test a script what it does when MySQL transaction fails. So I want to simulate transaction failure on COMMIT.

Image the script opens a transaction, makes some queries, and then commits the transaction. I want to implant some extra query to the transaction, to ensure the transaction will fail on COMMIT. So I can test how the script recovers from the transation failure.

I don't want to use explicit ROLLBACK. I want to simulate some real-life case when a commit fails. The exact DB structure is unimportant. It may adapt to the solution.

RSpec: NameError: uninitialized constant

I am new in RSpec and I'd just like to test my controller. I wrote my test that way:

RSpec.describe ServicesController do
  describe "GET index" do
    it "renders the index template" do
      get :index
      expect(response).to render_template("index")
    end
  end
end

But my controller isn't recognized by RSpec, I get this error:

NameError: uninitialized constant ServicesController

In found examples I can find require line, which maybe could solve this problem, but as far as I can see, it concerns only files in lib folder, while my controller path is app/controllers/services_controller.rb. I tried to add it with path ../app/controllers/services_controller.rb, to go out from lib folder, but that doesn't work. What should I do? That's very basic case, but I wasn't able to find any help on the Web.

How can I start any test class in the activity with the "startInstrumentation" code?

I am trying to write automation for my android device. when I search from the internet I see that I can Test Class(for exmple AirplaneMode) with startInstrumentation in the Activity Class(AirplaneActivity). However, what I have not been able to do. It prints "NOK" in the Activity Class. Can you help me enter the StartInstrumentation parameter incorrectly?

 @RunWith(AndroidJUnit4.class)
    public class AirplaneMode {
    private static UiDevice mDevice;
    private static Context mContext;

    @BeforeClass
    public static void init() throws IOException, UiObjectNotFoundException {

      mDevice=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        mContext = InstrumentationRegistry.getContext();
    }

    @Test
    public void test1() throws UiObjectNotFoundException, IOException {

        mDevice.openQuickSettings();

    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        mDevice.pressHome();

    }
}


// MyActivity
public class AirplaneActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(getApplicationContext(),"airplane",Toast.LENGTH_LONG).show();

        if (startInstrumentation(new ComponentName("com.evrim.myapp.test/android.support.test.runner.AndroidJUnitRunner", "com.evrim.myapp.AirplaneMode"), null, null))
            Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_LONG).show();
        else Toast.makeText(getApplicationContext(),"NOK",Toast.LENGTH_LONG).show();
    }

}

Testing spring security post. Full authentication is required to access this resource

I'm testing the login method in Spring Security. I want to get the status of 200, but comes 401.

@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
@AutoConfigureMockMvc
public class AuthenticationTest {

@Autowired
private MockMvc mockMvc;

@Test
public void loginWithCorrectCredentials() throws Exception {
    RequestBuilder request = post("/api/login")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("username", "user")
            .param("password", "password");
    mockMvc.perform(request)
            .andExpect(status().isOk())
    .andExpect(cookie().exists("JSESSIONID"));
}

Logs:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /api/login
   Parameters = {username=[user], password=[password]}
      Headers = {Content-Type=[application/x-www-form-urlencoded]}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 401
    Error message = Full authentication is required to access this resource
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains], WWW-Authenticate=[Basic realm="Spring"]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-01-30 13:28:17.471  INFO 3988 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@6ac13091 testClass = AuthenticationTest, testInstance = ua.com.kidspace.controller.AuthenticationTest@752b69e3, testMethod = loginWithCorrectCredentials@AuthenticationTest, testException = java.lang.AssertionError: Status expected:<200> but was:<401>, mergedContextConfiguration = [WebMergedContextConfiguration@5e316c74 testClass = AuthenticationTest, locations = '{}', classes = '{class ua.com.kidspace.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@6d2a209c key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@42607a4f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@64485a47, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7276c8cd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@306279ee, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@178398d7, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@24b1d79b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

java.lang.AssertionError: Status 
Expected :200
Actual   :401

I read a lot of resources, but I can not fix "Full authentication is required to access this resource". The application.properties added. How can this problem be solved?

security.user.password=password
security.user.name=username
management.security.enabled=false

Jmeter CookieManager not storing cookies for next request

I am trying to use JMeter Cookie Manager to use in requests after login request but Jmeter doesn't send cookies with the requests.

This is the response of the first request

Response headers:
HTTP/1.1 200 OK
Date: Tue, 30 Jan 2018 11:40:27 GMT
Server: Apache
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept
Set-Cookie: DGSession=EwhG3kW21VtEnWSbuiZghmgGSSevZVb4xq5M6SMG37JElbbX_vns!650282103; domain=example.com.tr; path=/; HttpOnly
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE, HEAD
Access-Control-Allow-Origin: 
Access-Control-Max-Age: 1728000
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json;charset=UTF-8

This is the request JMeter sends after the above request

POST https://example.com.tr/digitalgate_hesabim/login/startLogin.json

POST data:
{

  "clientSecret" : "345345-456456-dsfds-r456456"

}

[no cookies]  --> As you see cookies are not set

Request Headers:
Connection: keep-alive
Content-Type: application/json
Content-Length: 58
Host: example.com.tr
User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_111)

What might be causing this problem?

Meteor mocha test subscriptions

I'm currently working on writing client-side tests for my application using practicalmeteor:mocha. Therefor I need to insert a record into a mongo collection before every step.

Following the concepts of meteor, I wrote some meteor methods to insert/update/delete the records. If I want to test the expected behaviour, I assume I have to call the appropiate method (to insert a record for example) and then have to wait for the subscription to synchronize the record to the client so I can verify the insert.

I tried a few things but none of them seems to work:

describe('a topic', function() {
    beforeEach(async function(done) {
        let res = await new Promise((resolve, reject) => {
            Meteor.call('topics.createNew', function(err, res) {
                if(err) return reject(err);
                resolve(res); //res is the _id from the generated record
            });
        });

        //subscribe to single record (the one just created)
        let subscription = Meteor.subscribe('topics.details', res); 

        //i assume this runs every time the publish function calls ready and therefor is also run when the new record is published
        Tracker.autorun((computation) => {
            let count = TopicsCollection.find({}).count();
            //console.log('topic count: ' + count);                

            if(subscription.ready() && count === 1) {
                computation.stop();
                done();
            }
        });
    });
});

I logged the counted documents and had luck when i wrapped the autorun-Funktion into a Promise but in neither of both cases, done() was called causing a timeout in mocha.

I already had a look on this question but I think it doesnt really help in my situation since I wait for every possible callback and I'm working with a plain Collection and the guy in the question above uses an accounts-package.

Can anyone suggest a better/working solution for this problem?
Thanks in advance! :D

Testing a custom BCryptPasswordEncoder class

I have a class that looks like this

@Component
public class SecurityUtility {

    private final String SALT = "salt";

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
    }

    @Bean
    public String randomPassword() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();

        while (salt.length() < 18) {
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;
    }
}

What can I do to test such a class and how do I go about it , normally I have been doing unit tests but this class , don't know what type of test or how to go about it . Thank you in advance for any suggestion

RUBY API GET And Delete All Strings That Match Pattern

For the purposes of QA. Im trying to query my own API and delete strings that match a pattern.

During our QA regression tests, a large number of a certain string are created which all match a pattern similar to "QATest" followed by a random set of numbers.

Before the test runs again, Id like to get all of those strings through the API and delete them.

Can any one set me on the right path to do this and where I would start.

I can currently GET one. But not all. So I suppose I need to loop the GET request somehow. Put them in all in array and delete all in the array that match the pattern. But there might be better ways to do it.

Anyone have any ideas? I use Ruby and the rest-client gem. But Im open to other gems if they are better.

Testing image.onload with vue-test-utils and jest

I have a vue component that loads image in a created hook and then fires "ready" event in image.onload function.

I want to test if the event is fired after image is loaded. But I can't. I changed function's code to use callback so I could test it asynchronously.

Here is my code:

created() {
  this.load();
},
methods: {
  load(callback) {
    const image = new Image();
    image.onload = () => {
      this.$emit('ready');
      callback();
    };
    image.src = this.content.imageSrc;
  },
},

And my test code:

test('@ready - emitted after image is loaded', (done) => {
  const wrapper = shallow(ViewerComponent, {
    propsData: {
      content: {
        imageSrc: 'example.png',
      },
    },
  });

  jest.mock('example.png', () => 'example.png');

  wrapper.vm.load((error) => {
    expect(wrapper.emitted().ready.length).toBe(1);
    done(error);
  });
});

But wrapper.emitted() is always empty object.

Is there any way to test event fired in image.onload function?

How to have isolated tests with @ngrx/store

I've been writing a library which is supposed to work both with redux and @ngrx/store, so I am writing integration tests to guarantee that.

I have only one scenario which can be found here.

Having redux tests is very simple since you can just do:

import { createStore, combineReducers } from 'redux';

const store = createStore(
  combineReducers({ reducerName: reducerFunction });
);

store.dispatch({ type: 'Hello World' });

expect(store.getState().greetings)
  .toBe('Hello World');

How can I do the same with ngrx-store? Every resource I found seems to require a full angular environment, including module bootstrapping, components, etc...

Is there any way to have a similar scenario for it?

lundi 29 janvier 2018

Mocha, how to test async code without UnhandledPromiseRejectionWarning

I'm testing my server-side api endpoints with mochajs and I can't figure out how to do it properly.

I started with code that had the following logic:

it('test', (doneFn) => {

    // Add request handler
    express.get('/test', (req, res, next) => {

        // Send response
        res.status(200).end();

        // Run some more tests (which will fail and throw an Error)
        true.should.be.false;

        // And that's the problem, normally my framework would catch the
        // error and return it in the response, but that logic can't work
        // for code executed after the response is sent.
    });

    // Launch request
    requests.get(url('/test'), (err, resp, body) => { // Handle response

        // I need to run some more tests here
        true.should.be.true;

        // Tell mocha test is finished
        doneFn();
    });
});

But the test doesn't fail (I'm guessing because doneFn() is being called in a different tick?).

So I googled around and found that my problem could be solved using promises, and it does, now the test fails. This is the resulting code:

it('test', (doneFn) => {

    let handlerPromise;

    // Add request handler
    express.get('/test', (req, res, next) => {

        // Store it in a promise
        handlerPromise = new Promise(fulfill => {

            res.status(200).end();

            true.should.be.false; // Fail

            fulfill();
        });
    });

    // Send request
    requests.get(url('/test'), (err, resp, body) => {

        // Run the other tests
        true.should.be.true;

        handlerPromise
            .then(() => doneFn()) // If no error, pass
            .catch(doneFn); // Else, call doneFn(error);
    });
});

But now I end up with a deprecation warning because the error is handled in a different process tick than the one it was thrown.

The errors are: UnhandledPromiseRejectionWarning and PromiseRejectionHandledWarning

What am I doing wrong here?

How can i Create an automated testing program for my database

i am trying to learn testing environments and i would like to know if there is a way to create a java back-end application that will preform automated data entries into my database for me. I want to try do this to force out any errors in my code. Or are there any frameworks that might be able to do this for me?

i am using netbeans 8.1 with a MySql database(version 5.7.20). I have also used the Speedment ORM framework to connect the two.

Any help or suggestions would be great thank you!

NetBeans library, create a command line app for it

I have created a Java library with NetBeans 8.1.

Now I want to create (inside the library sources) a Java application to test it.

Note that jUnit is not what I need. I want just a command line application which I will use for manual (not automated jUnit) testing of my library.

How to create an application inside the library source?

Reopen Java window after hiding it on close

I'm building an application, and the biggest problem that I'm having that needs to be attended to asap is the reopening of the application. I'm not sure how to word this so sorry if it sounds weird.

I can launch my application just fine. It creates the main window. I'm also using the setDefaultCloseOperation(HIDE_ON_CLOSE) I have also tried DISPOSE_ON_CLOSE but they both have the same effect. So when I close it the window closes out. However, when I click on the icon in my dock the window won't open back up. Any advice is greatly appreciated thanks.

Testing MongoDB error path using Mocha

I am writing tests for a express route with MongoDB backend. Let's take a stub of the get functionality:

getAllResources() {
  return new Promise((resolve, reject) => {
    this.books.find({}).toArray()
      .then(docs => {
        resolve({
          status: 200,
          response: docs
        });
      })
      .catch(err => {
        reject({
          status: 500,
          data: 'Error'
        });
      })
  })
}

Now, I have a test like:

it('getAllResources should return empty array', async function() {
  let result = await sut.getAllResources();
  should.exist(result.status);
  should.exist(result.response);
  result.response.should.have.length(0);
});

But the scenario if the DB errors out is missed. Hence I am missing coverage on that segment. With all the routes I see a significant amount of coverage miss and want to improve it. I'm not sure how I can mock the Mongo functions.

I am currently using mongodb ^3.0.1, mocha ^5.0.0, chai ^4.1.2, sinon ^4.1.6, istanbul ^0.4.5. I am not using any in memory alternative for testing, but instead using collections with prefixes.

How do I load a custom module in Rails minitest?

On Rails 5.1, I have this module:

app/datatables/financing/merchants_datatable.rb

and in my merchants_controller.rb file, I have this code:

def index
    ...
    respond_to do |format|
        format.html
        format.json { render json: Datatables::Financing::MerchantsDatatable.new(view_context) }
    end
end

When I try to run my test/controllers/merchants_controller_test.rb, I run into this error:

NameError: uninitialized constant Financing::MerchantsController::Datatables

How can I load my merchants_datatable.rb module in my tests?

Thanks!

Different return to __cmp__ override in Python

I am writing some test cases to a __cmp_ Python override. My code looks like this:

def __cmp__(self, other):
    if self.name == other.name: 
        return 0
    return -1

When I test this way:

self.assertEqual(0, first_tail > first_tail)
self.assertEqual(0, first_tail < first_tail)

The test answers OK. But when I try:

self.assertEqual(0, first_tail == first_tail)

I get this error:

True != 0

Expected :0
Actual   :True

How to pass User Interaction in Cucumber CLI test

I have a delete script that deletes data and while doing so prompts to ask for proceed. I want to pass both my command and the user interaction "Y" in cucumber-cli

Scenario: Delete customer should delete all data Given the input When running the command """ abc delete """ Then the job should finish without throwing an error

I have tried echo Y | abc delete abc delete <<< Y printf Y | abc delete

But none seems to work inside scala-cucumber. It works only on terminal. What could be the problem?

That's my O/p

Press 'Y' to continue... Exception in thread "main" java.io.EOFException: Console has reached end of input at scala.io.StdIn$class.readChar(StdIn.scala:93) at scala.io.StdIn$.readChar(StdIn.scala:229)

Rails Minitest ActionView::Template::Error: undefined method for nil:NilClas

Been trying to debug this for two days and I'm just stuck. I have a view that I'm trying to test in rails and the view works perfectly when I test manually in the browser but I keep getting this error in my controller test:

ActionView::Template::Error: undefined method "name" for nil:NilClass Here is the full error message.

Here's the test (test/controllers/quotes_controller_test.rb):

  test "should get quotes index as browse" do
    get browse_path
    assert_response :success
  end

It's breaking where I render this partial (views/quotes/browse.html.erb):

  <% if @recent_quotes.any? %>
    <aside class="recent-quotes browse-quotes col-7">
      <%= render @recent_quotes %>
    </aside>
  <% end %>

The partial looks like this (views/quotes/_quote.html.erb):

<blockquote id="quote<%= quote.id %> blockquote">
  <small class="text-muted">
    <%= link_to quote.topic.name, artist_path(quote.topic) %>
  </small>
  <p class="mb-0"><%= link_to quote.content, quote_path(quote) %></p>

  <footer class="blockquote-footer">
      <cite title="Source">
        <%= link_to quote.speaker.name, quote.source %>
      </cite>
  </footer>
</blockquote>

And the controller action looks like this (controllers/quotes_controller.rb):

  def browse
    @artists = Artist.all
    @recent_quotes  = Quote.all.limit(7)
  end

Again, everything works great in the browser, but I can't get that simple test to pass. If I remove the partial it passes, so the route is working fine. I think that the test is just looking for the name method in the first call to quote.topic.name and not finding it.

But it's working in the browser, so I can't figure out what I'm doing wrong with this test.

Is it a good idea to use global variables for test data values?

First, a bit of context:

I have a class with a series of methods performing tests on a set of files.This class also has a setUpClass method where those files are created.

Over the lifetime of this class, names like fake.txt, foobar, etc. have been used, but they are all string literals used at three or four places and not actual variables.

I recently decided to change one of those string literals into something that better reflects its use (foobar to initial_value for example), but one of the test failed since I forgot to rename one of the occurrence of foobar.

To avoid facing this issue anymore, I decided to replace all of the string literals by global variables. For example:

TEST_FILE = 'fake.txt'

However, I found that this change make the test suite way less readable for a number of reasons:

  • Previously, it was easy to scan what was a file name and what was a file content because we alway used file extensions to indicate file names (i.e., foo.txt is a file, bar is what would be written in foo.txt). My change makes it harder to distinguish between the two at first glance.
  • Due to syntax highlighting of string literals, it was easy to scan where those fake values were used. Using variables makes them less distinguishable.
  • Variable names usually take more space (i.e., f.write('bar') over f.write(FAKE_FILE_CONTENT), with some more extreme examples in the actual code.

On the one hand (and considering the points I just made), the complexity of the file is low enough so we can use string literals without much more issue than forgetting one occurrence. On the other hand, it is unclear if this file is going to evolve at a later time, and I feel like it would be easier to fix the issue now (if we decide to fix it at all).

What are the pros and cons of the two approaches (beyond what I listed), and is there a preferred solution?

Jenkins Cobertura (with gcov) - what do the coverage statistics mean?

I'm currently writing unit tests for a Qt project. I wanted to use the statistics provided in Jenkins through the Cobertura plugin (underneath gcov is used to get the stats).

:~$ gcov -v gcov 5.4.0 20160609

:~$ gcc -v gcc version 5.4.0

However after I looked at the table (see below) I was really surprised to see the poor coverage especially of conditionals. For the first one (see Coverage Breakdown by File) I thought I was actually done, since the code has only three ifs(each with a single condition) and my tests covers all (checked this also through debugging just to make sure). So I am really confused what these numbers actually mean and how to interpret them in order to make my unit tests better.

enter image description here

I've even started thinking that some of the poor results might be due to the use of Qt since it's not exactly pure C++ and all "extras" (slots, signals, MOC files etc.) might be something that gcov can't handle properly.

Parallel or sequentially run tests on Go using the library testify?

There is a group of tests that each have a different option. I have a hunch to the fact that the tests run in parallel and it all depends on the order of the tests. Maybe someone worked with this library and will help. Thank you

Is there a way to not use @MockBean on Spring MVC tests?

I'm trying to test the Rest contract of my Rest Controller using @WebMvcTest, like:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
class MyControllerTest {

The method that I'm testing use only MyFirstService, but inside the class there another two services (MySecondService and MyThirdService) used by two other methods.

The problem is the use of @MockBean. The test class seems like this:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
class MyControllerTest { 

    @MockBean
    private MyFirstService s1; // internal method mocked for the test

    @MockBean
    private MySecondService s2; //never used

    @MockBean
    private MyThirdService s3; //never used

    @Test
    public void testMethod() [
        // mock s1
        // calls rest controller method
    }

}

I think that this solution is not elegant with these annotations... The declared s2 and s3 appears to not be used from who read the code. And every service that is injected in the MyController needs to be there with @MockBean.

So, I have two questions:

  1. Is there a way to not use @MockBean on Spring MVC tests?
  2. Is there a better way to do the same thing, even using @MockBean?