vendredi 31 janvier 2020

How to prevent libtool to add system path (i.e. /usr/lib) to RUNPATH (rpath)?

How to prevent libtool to add system path (i.e. /usr/lib) to RUNPATH (rpath)?

During testing (checking) MPFR libtool adds system path to rpath before testing path, i.e.:

0x000000000000001d (RUNPATH) Library runpath: [/usr/lib:/LFSC/native/src/bmpfr/src/.libs]

As a result, tests can run installed libs (in the first path (system)) instead of testing ones. This happens usually when reinstalling software. Maybe this affects installing of upgrades.

This is because of existing dependency’s .la file, e.g. libquadmath.la

Removing .la files resolves this problem.

But there is no reason at all to add system path into hardcoded RUNPATH.

Is there any way to resolve this problem without deleting .la files?

Unit test method does not use the mocked object when running the test. Instead calls the actual class and method

I have a class to test named ClassToTest. It calls a CloudService to upload file.

public class ClassToTest {
    public String moveFilesToCloud(String path, String documentclass, String objStore) {
        log.info("Moving files to cloud.");
        String docId = StringUtils.EMPTY;
        CloudService service = new CloudService();
        try {
            docId = service.uploadDocument(path,documentclass,objStore,"");
        } catch (CloudException e) {
            log.info("* Error uploading reports to cloud *" + e.getMessage());
        }
        return docId;
    }
}

Below is the test class. The test class has a mocked object for CloudService. When I run the test instead of getting the mocked object, the actual CloudService is executed and fails.

@Mock
CloudService cloudService;

@InjectMocks
ClassToTest classToTest;

@Test
public void testMoveFilesToCloud() throws Exception {
    String pass = "pass";
    when(cloudService.uploadDocument("abc","def","ghi","")).thenReturn(pass);

    String result = classToTest.moveFilesToCloud("abc","def","ghi");

    assertEquals(result,pass);
}

I am expecting the mocked object for CloudService to be used when executing this line -

CloudService service = new CloudService();

Instead, it is actually trying to create a new instance of CloudService.

Where am I going wrong here?

How to write a script easy for apply test on?

I am working on some data work recently. When I try to do some one-time population script, I find it is hard to write tests over this script. In another word, I am struggling to write tests covering all lines of code running quickly. I attach an example below,

I would like to do some id match from source A and source B involving Django models here.

class Matching:
    def __init__(self):
        self.mapping = {}

    def update_mapping_with_id_set(self, id_set, B_record):
        # update the self.mapping

    def match_id(self):
        # some logic to get a matching set

        # Using unmatched set to get the partial matched set
        for each in matching_set:
            query = B.objects.only("id", "first_name", "last_name")

            id_set = set()
            for q in query.all(): # it iterates over all records in db, so it takes time here
                if each.first_name == q.first_name or each.last_name == q.last_name:
                    id_set.add(each.id)

            self.update_mapping_with_id_set(id_set, q)

    def upsert_id(self):
        for a in A.objects.all():
            if a.id in self.mapping.keys():
                a.match_id = self.mapping[a.id]
                a.save()

So the question I would like to re-declare is that how I can add test piece by piece over this structure of code design instead of run the whole class in the test case(it iterates over all records so the test time will last long). Or is there any good design pattern for such a one-time population script?

I would be of appreciation if there is any good general suggestions for my case. Thanks in advance!

BackstopJS testing for the entire application pages

How to test all the pages in backstop JS. I am only able to test one page. Because I am giving just one url and referenceURL. How can we make it test all the pages in the application. Only one screenshot is provided. Need to find all the screenshot and changes in the apllication.

What is memoized in Spek?

Spek documentation references

As a best practice you typically want test values to be unique for each test this can be done by using a lateinit variable and assigning it within a beforeEachTest. lateinit var calculator: Calculator

beforeEachTest {
    calculator = Calculator()
}

To make it more concise, Spek provides memoized to do the same thing:


val calculator by memoized { Calculator() }

What exactly is memoized?

Cypress tests for social login using Deezer-API

I have a React app with Deezer API and I am using Cypress for testing. I don't know how to get access to the popup window in login test.

so the test steps should be as follows:

  • visit localhost:3000
  • click on login button
  • new window will open and then I have to click on sing in with google button but I don't know how to access this window

My example test screenshot

Running tox with different environment variable config

I want to run my test with different values of environment variables. I have this tox.ini, which doesn't do what I want:

# tox.ini

[tox]
envlist = py37-{foo,bar}

[testenv]
description = Tests common
setenv =
    MY_VAR=COMMON
commands =
    env

[testenv:foo]
description = Tests foo
setenv =
    MY_VAR=FOO

[testenv:bar]
description = Tests bar
setenv =
    MY_VAR=BAR 

Above ini produced the following output:

$ tox
GLOB sdist-make: 

***

py37-foo run-test: commands[0] | env

***

MY_VAR=COMMON                                 <<<--- MY_VAR=foo is expected

***

py37-bar run-test: commands[0] | env

***

MY_VAR=COMMON                                 <<<--- MY_VAR=bar is expected

Whats wrong?

I use:

  • Win 10.0.18363 Build 18363
  • Python 3.7.4
  • tox: 3.14.0

Appium testcases on real devices won't recognize the elements they are supposed to click on

I wrote some tests for a react native app, provided here and there some testIDs (was working with testProps, so fine for Android and iOS) and tests were running smoothly on virtual devices (iOS Simulator and Android emulator). Now I have build an apk file and ipa from the react native app and if I want to run the appium tests on a real device with the (until now) perfectly working appium tests, the test doesn't seem to find the accessibility labels. I also inspected the pages with the appium inspector, but it doesn't seem to find the provided accessibility labels in the apk file. The logs aren't helpful either since it's just saying :

    [MJSONWP (b824eb6b)] Calling AppiumDriver.findElements() with args:
    ["accessibilityid","nextbutton.button","b824eb6b-2100-4e76-bf55-4c1fc341555a"] 
    [BaseDriver] Valid locator strategies for this request: xpath, id, class name, 
    accessibility id, -android uiautomator [BaseDriver] Waiting up to 0 ms for condition [WD 
    Proxy] Matched '/elements' to command name 'findElements' [WD Proxy] Proxying [POST 
    /elements] to [POST http://localhost:8200/wd/hub/session/c4a35d0d-d5be-4849-
    a3fc-13364f4fc77c/elements] with body: {"strategy":"accessibility 
    id","selector":"nextbutton.button","context":"","multiple":true} [WD Proxy] Got response 
    with status 200: {"sessionId":"c4a35d0d-d5be-4849-a3fc-13364f4fc77c","value":[]} [MJSONWP
    (b824eb6b)] Responding to client with driver.findElements() result: [] [HTTP] <-- POST 
    /wd/hub/session/b824eb6b-2100-4e76-bf55-4c1fc341555a/elements 200 102 ms - 74 [HTTP] 
    [HTTP] --> POST /wd/hub/session/b824eb6b-2100-4e76-bf55-4c1fc341555a/elements [HTTP] 
    {"using":"accessibility id","value":"nextbutton.button"}

Environment

Appium version: 1.15.1
Desktop OS/version used to run Appium: MacOS Catalina
Real device or emulator/simulator: Android 7, Galaxy S6 edge
#

Anyone else experienced this issue?

TestCafé data driven tests with login

I had written some tests using for loops and recently discovered this handy doc page that describes how to write data-driven tests.

https://devexpress.github.io/testcafe/documentation/recipes/create-data-driven-tests.html

I'm now trying to refactor my tests but running into a problem. The purpose of the test is to log in as a bunch of different accounts, and then verify whether certain page elements exist. (I recognize that this is a heavy hammer to use, but our app has a huge number of permissions and the combinations often get forgotten when developing new features, so this seemed like the quickest way to get at the actual truth of what is on the screen for a real user).

My old tests look something like this:

test('Account manager', async (t) => {
  const existingItems = [
    [mediaSidePanel.customize, 'Customize'],
    [mediaSidePanel.stats, 'Stats'],
    [mediaSidePanel.download, 'Download'],
    [mediaSidePanel.delete, 'Delete'],
  ];

  const notExistingItems = [
    [mediaSidePanel.adminTools, 'Admin Tools'],
  ];

  await t
    .useRole(advAccountManager)
    .navigateTo(`https://${accountKey}.wistia.io/medias/${mediaHashedID}`);

  await Promise.all(existingItems.map(async item => await t
    .expect(item[0].exists).ok(`${item[1]} should exist for an Account Manager`)));

  await Promise.all(notExistingItems.map(async item => await t
    .expect(item[0].exists).notOk(`${item[1]} should not exist for an Account Manager`)));
  });

The test works fine except for the obvious problems of having loops in tests: I need to have thorough diagnostic messages to ensure I know which element actually is failing, and worse, if something early in the loop fails, the test ends, and I have no way of knowing if there would have been subsequent failures.

I started trying to refactor this by pulling all of the existing/non-existing items into an array defined in a separate file and wrote this:

import * as dataSet from '../helpers/rolePermissions';

fixture `Advanced Account Manager`
  .page `https://app.wistia.io/logout`
  .beforeEach(async (t) => {
    await t
      .useRole(advAccountManager);
  });

dataSet.advAccountManager.project.forEach(data => {
  test.page `https://${accountKey}.wistia.io/projects/${projectHashedID}`(`Project - ${data.name}`, async t => {
    if (data.present) {
      await t
        .expect(await data.selector.exists).ok(`${data.name} should exist for an Account Manager`);
    }
    else {
      await t
        .expect(await data.selector.exists).notOk(`${data.name} should not exist for an Account Manager`);
    }
  });
});

It works perfectly in that it gets rid of the biggest problem and keeps running the tests even if an earlier one fails. It introduces a much bigger problem, however. This is now considerably slower because it has to log in every single time it iterates through the test. I am already using Roles, as you can see, to try to speed things up, but it is still painfully slow comparatively. I don't want to continue down this refactoring path if it ultimately isn't going to pan out.

Is there a way to have the best of both worlds? Ideally, I would like to do the following:

  • log in once at the beginning of the fixture
  • stay on the page without reloading
  • iterate through all the relevant selectors
  • continue iterating even if an individual test fails

property-based testing in java :jqwik vs junit-quickcheck vs QuickTheories

I'm trying to implement some property-based test in java,thus, I find that there are 3 tools allowing this :

and I'm confused which one to use, therefore does anyone have any experience/feedback of one of those?

How to test a method that save an object to the database with hibernate?

I wrote CRUD app (Notebook), and now I'm learning how to test my code. I wrote some tests using mocks, but in this case Idk how to test for example my method -> addNote. I searched a few pages with testing CRUD but I have not found similar code to this.

This is my Controller:

@Controller
public class NoteController {


private NoteService noteService;

@Autowired
public NoteController(NoteService noteService) {
    this.noteService = noteService;
}

@GetMapping("/notebook")
public String getNotebook(Model model)
{
    model.addAttribute("notes",noteService.getNotes());
    model.addAttribute("newNote",new Note());
    return "main-view";
}

@PostMapping("/notebook/add-note")
public String addNote(Model model, @ModelAttribute Note note)
{
    if(note.getTitle()==null || note.getTitle() == null)
    {
        model.addAttribute("errorMessage","You have to fill in the title and text, to save the note");
    }
    else {
        noteService.saveNote(note.getTitle(), note.getText());
    }
    return "redirect:/notebook";
}

@GetMapping("/notebook/{id}")
public String getNoteById(Model model, @PathVariable Long id)
{
    Note note = null;
    try {
        note = noteService.findNoteById(id);
    }
    catch (Exception e)
    {
        model.addAttribute("errorMessage","Note not found");
    }
    model.addAttribute("note", note);
    return "show-note";
}

@RequestMapping(value = "/notebook/{id}/edit", method = {RequestMethod.POST,RequestMethod.GET})
public String editNoteById(Model model, @PathVariable Long id,@ModelAttribute Note updatedNode)
{
    if(updatedNode!=null)
    {
        noteService.update(updatedNode);
    }
    Note note = null;
    try {
        note = noteService.findNoteById(id);
    }
    catch (Exception e)
    {
        model.addAttribute("errorMessage","Note not found");
    }
    model.addAttribute("edit",true);
    model.addAttribute("note", note);

    return "show-note";
}

@PostMapping("/notebook/{id}/delete")
public String deleteNote(@PathVariable Long id)
{
    noteService.deleteNote(id);
    return "redirect:/notebook";
}

And the only thing I was able to test with the addNote method was redirection:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApiTest {

@Autowired
MockMvc mockMvc;

@Test
public void addNote() throws Exception {

    mockMvc.perform(post("/notebook/add-note")
            .param("title","mmtitle")
            .param("text", "mmtext"))
            .andExpect(redirectedUrl("/notebook"));

}

As you can see, I also use param, which creates a new object in my database, but I don't know how to check it using test. Can you tell me how can I do it, or link me any source, where I can learn testing with mocks?

Xcode Simulator: How do I get the settings "Screen time"?

I try to test in app purchases with sandbox users. Unfortunately I always get the error "Cannot connect to itunes store". All bug fixes I've seen mention you should reset some settings in the "Screen time" section of the settings app. However, I don't have any screen time in the settings app. What am I missing? iOS version is 13.3 of the test device. I've also tried to login to the itunes account with the sandbox user, but this doesn't work of course. So what am I missing?

enter image description here

Unable to login to Jenkins the second time after system restart

I am trying to login to my Jenkins. I have downloaded the jenkins.msi file and have configured some jobs to run the test automation framework. This job was scheduled and it works fine daily. Now i have restarted the system and not sure how to login again. My local system has the .jenkins folder. Can i do something to login back to the jenkins dashboard. Please share your ideas.

Thanks in advance!

trying to use two different text to locate the same element using .withText for different environment

Is this the correct way to find the element using two different texts, since that element has two different texts for two different environments.

.find(div).withText(/text1 || text2/)

Karma with Angular Project return empty code coverage report when relocate tests

Because I don't need to test the used Angular base template and only need to test the base components and services, I relocated to the src/tests folder with the same inner structure of the app folder. Then I changed my test.ts file in order to reference the new path.

const context = require.context('./tests', true, /\.spec\.ts$/);

If I run the next command:

ng test

I can get all tests passing, but if I run the next command:

ng test --code-coverage=true

It generates the report and I can see that, but with empty results.

How can I do to reference the new tests path?

tests inside function calls or for statements in clojure not running

I wrote code that looks something like this

(testing "check that for all these roles there's an alert"
    (binding [*profile* account-exceeded-limits]
      (let [overview-page (overview-container sample-form
                                              :role readonly-no-download)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))
      (let [overview-page (overview-container sample-form
                                              :role dataentry)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))
      (let [overview-page (overview-container sample-form
                                              :role editor)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))
      (let [overview-page (overview-container sample-form
                                              :role member)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))
      (let [overview-page (overview-container sample-form
                                              :role collaborator)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))
      (let [overview-page (overview-container sample-form
                                              :role readonly)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))))

I need to refactor this code to make it drier.

So I tried this

(testing "check that for all these roles theres an alert"
    (for [role [dataentry readonly-no-download editor member collaborator
             readonly]]
      (let [overview-page (overview-container sample-form
                                              :role role)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning")))))

It seemed that tests were not ran.

I also tried this:

(testing "check that for all these roles theres an alert"
(map (fn [role]  (let [overview-page (overview-container sample-form
                                              :role role)]
        (is (dommy/has-class?
             (-> overview-page (sel1 [:div#export-list-panel :.panel-body
                                      :.alert]))
             "alert-warning"))) [dataentry readonly-no-download editor member collaborator
             readonly])))

again, it still seemed that tests were not ran.

What could be causing this? is there a way I can make this test dryer? should I be trying to make tests dryer?

jeudi 30 janvier 2020

How to reuse steps definition of one feature file implementation in another one?

I am having the below folder structure

folder root
    features
         file1.feature
         file2.feature
    source
         file1.py
         file2.py

The implementation of file1.feature is in file1.py and file2.feature is in file2.py. I was trying to reuse a step in file1.feature in file2.feature. I tried importing the function directly in file2.py as below

from source.file2 import method1

However it resulted in the below error getting triggered

    def _find_step_function(request, step, scenario, encoding):
        """Match the step defined by the regular expression pattern.

        :param request: PyTest request object.
        :param step: Step.
        :param scenario: Scenario.

        :return: Function of the step.
        :rtype: function
        """
        name = step.name
        try:
            # Simple case where no parser is used for the step
            return request.getfixturevalue(get_step_fixture_name(name, step.type, encoding))
        except pytest_fixtures.FixtureLookupError:
            try:
                # Could not find a fixture with the same name, let's see if there is a parser involved
                name = find_argumented_step_fixture_name(name, step.type, request._fixturemanager, request)
                if name:
                    return request.getfixturevalue(name)
                raise
            except pytest_fixtures.FixtureLookupError:
                raise exceptions.StepDefinitionNotFoundError(
                    u"""Step definition is not found: {step}."""
                    """ Line {step.line_number} in scenario "{scenario.name}" in the feature "{feature.filename}""".format(
                        step=step,
                        scenario=scenario,
>                       feature=scenario.feature,
                    )
                )    pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "User is logged-in". Line 6 in scenario "Scenario 1" in the feature "../Features/file1.feature

Is there any way to effectively reuse the steps of one feature file in another one

Omegaup Java Test Cases

Hi I am trying to make a contest on omegaup for a class of students with questions based on java, but dont know how to set up java test cases on it for the problems. I know how to do it for C, but not java. I know you have to put .in and .out files in a cases folder, but like how does this work? I made the test cases in junit5 and it works fine, but I just dont know how to put java test cases on omegaup using the certain format they ask for. Any help would be gladly appreciated. Thanks. https://omegaup.com/

Why does my Test not pass for passing a null List? [duplicate]

I am working in C# building a form application. I have a method that takes in a type of List and returns a hashtable. I am trying to throw an argument exception if the the list is null. My program works the way it should and returns the results I need.

This is the error

Message:   Expected: <System.Exception>
  But was:  <System.NullReferenceException: Object reference not set to an instance of an object.
   at WordOccurenceCalculator.WordCalculator.CalculateOccurrences(List`1 List)
public void CalculateOccurrencesShouldThrowException() {

            List<string> list = null;
            WordCalculator calc = new WordCalculator();

            Assert.Throws<Exception>(delegate { calc.CalculateOccurrences(list); });
}


 public Hashtable CalculateOccurrences(List<string> List)
        {
            if ( List.Count == 0)
            {
                throw new System.ArgumentException("Invalid Input");
            }

            if (List == null)
            {
                throw new System.ArgumentException("Invalid Input");
            }


            Hashtable table = new Hashtable();
            int counter = 1;
            int j = 1;
            for (int i = 0; i < List.Count; i++)
            {
                for(j = i + 1 ; j <= List.Count; j++)
                {
                   if(j < List.Count){
                if (List[i] == List[j])
                {
                    counter++;
                }
            }
                }
                if (!table.Contains(List[i]))
                {
                    table.Add(List[i], counter);

                }
                counter = 1;

            }

            return table;
        }

Which load test products allow cookie injections

The endpoint I am trying to hit is an URL, however I need to set a cookie in the load test call. Which load testing product can I use to achieve this? In the load test results I will primarily be looking for the average response time, actual page load time. It would be nice if I could also get telemetry data for other calls in the trace (the way we get it in Web Page test).

On a side note, is there a way to perform load tests using https://www.webpagetest.org/ ?

Kotlin MockK: How to capture a Runnable passed to ExecutorService?

I have a @WebMvcTest which tests a @RestController that needs a special ExecutorService @Bean provided in a library, i.e. not present in the slice.

I didn't want to turn it into a full @SpringBootTest so I wanted to use just CompletableFuture.runAsync(). So I tried this:

    every {
        //val captureLambda = captureLambda<Function<T>>()
        val captureRunnable = capture(slotRunnable)
         eventsExecutorService.submit(captureRunnable)
    } returns CompletableFuture.runAsync(slotRunnable.captured)

But it fails, saying that lateinit var "captured" was not initialized.

Is this expected? Is this the right way to do it? Or am I missing something?

Jasmine Test Fails - But log suggests otherwise

This test is throwing the error Expected spy phone to have been called. - the mock class method is being called as demonstrated by the log in the terminal. The mock class is not being called by any other tests. I assume I am missing something simple here, but I am not sure why formatSpy in the test is failing.

My Provider in TestBed.ConfigureTestingModule:

        {provide: FormatService, useClass: FormatServiceMock},

My Mock Class:

        export class FormatServiceMock {
             phone() {
               console.log('format phone');
               return;
            }
       }

My Function Being Tested:

    public getPhone(): string {
        if (this.data && this.data.settings) {
            return this.format.phone(this.data.settings.phone);
        } else {
            return '';
        }
    }

My Test:

        it('should call format service', () => {
            service.data = data;
            service.getPhone();
            let formatSpy = spyOn(format, 'phone').and.callThrough();
            expect(formatSpy).toHaveBeenCalled();
        });

My Output:

LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6): Executed 28 of 87 SUCCESS (0 secs / 1.477 secs)
LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6) EnvironmentService getPhone should call format service FAILED
    Expected spy phone to have been called.

Can't find appium ID because all the IDs are showing up as squares

Appium is showing all the IDs I'm putting into my code as simple squares. Like, real s.

Tried to start recording myself selecting elements so I could check if the IDs are being actually found or if Appium is just with some issue, but even the code on the recorder displays an  on the xPath.

Output from the recorder:

let el3 = await driver.elementByXPath("(//XCUIElementTypeOther[@name=\"\"])[2]"); await el3.click();

Fiddle for the output appium displays when I tried to record myself selecting an element:

https://jsfiddle.net/3pLfhdmn/

Running on iOS, Xcode Version 11.3.1 (11C504). My application is built on react-native.

Here's how I'm trying to slip the IDs into the code:

<Button onPress={() => this.setState({ routeName: GLOBALS.NAVIGATOR.GUIAS_PENDENTES })} style= badge name='teste' testID='teste' accessibilityIdentifier='teste' vertical> { renderIf(this.state.qtdePendencias > 0, <Badge style=><Text>{this.state.qtdePendencias}</Text></Badge>) } <MaterialCommunityIcons name="alert-outline" style= /> </Button>

Mockito.verify doesn't work with Lombok @Delegate

So I experience the following behaviour when trying to verify calls on mock (same for spy) which uses Lombok @Delegate inside:

public class SomeClass {

    @Delegate
    private final Map<String, String> map;
...
}

Test:

@Mock //same for @Spy ..
private SomeClass someClassMock;

@Test
void someTest() {
    ...
    verify(someClassMock, times(0)).put(anyString(), anyString()); // <-- NullPointerException
}

Looks like Mockito doesn't understand that "put" method comes from the underlying delegated class. Any ideas how to make it work?

Is there a page with datasets to test algorithms?

I'm looking exactly for time series with anomalies to test detect anomalies, but with not constant difference in time between observations. For example stock indexes, or currencies exchange rates, but with outliers.

Trying to post a request

Trying to post a request and validate its status. However, is showing this error:

java.lang.AssertionError: 1 expectation failed. JSON path staus doesn't match. Expected: OK Actual: null

PLEASE I NEED URGENT ANSWER

{
    "location":{
        "lat" : -38.383494,
        "lng" : 33.427362
    },
    "accuracy":50,
    "name":"Frontline house",
    "phone_number":"(+91) 983 893 3937",
    "address" : "29, side layout, cohen 09",
    "types": ["shoe park","shop"],
    "website" : "http://google.com",
    "language" : "French-IN"
}

AndroidX Test - ActivityScenario API Destroy the activity starightaway

I have been trying to move my Robolectic test cases to Android X Test. I've followed the documentation but unable to launch the activity through Activity Scenario Launch API.

https://developer.android.com/reference/androidx/test/core/app/ActivityScenario

http://robolectric.org/androidx_test

protected void setupActivity() {
      ActivityScenario<VisitorExemptionActivity> scenario = ActivityScenario.launch(VisitorExemptionActivity.class);
        scenario.moveToState(Lifecycle.State.CREATED);// Activity destroyed before reaching to this point.
}

Above code does not call any android life cycle except onStart , throw following exception and destroyed the activity straight away.

java.lang.IllegalStateException: Cannot move to state "CREATED" since the Activity has been destroyed already

When I tried the same code with Robolectric. It work fine and call all life Cycle. oncreate , onstart and onResume.

protected void setupActivity() {
activityController = Robolectric.buildActivity(VisitorExemptionActivity.class).setup();
activityController.get();
}

Above code call all the life cycle.

Please can you explain to me what I am doing wrong.

Thanks in advance.

can someone teach me about this mock test step by s

the code

  1. How to make the "PodcastwasPurchased"?
  2. What is the output of this mocking test?

python: create a test for reading invalid YAML file

I am trying to create a test in Python, I want to create a mock for opening YAML file, and mock its content to be an illegal YAML and assert the exception.

I tried mocking:

    def test_illegal_yaml_file(self):
        with patch('os.path.isfile', return_value=True):
            with patch('__main__.open', mock_open(read_data='wifi_password 12345678')):
                myObj = MyClass()
                params = myObj.get_params()
                # TODO catch exception with assert here

and inside MyClass:

    def get_params(self):
        path = "configuration.yaml"
        params = None
        if os.path.isfile(path): # os.path.isfile is mocked here to be True
            params = self.get_parameters(path)
        return params

    def get_parameters(self, path):
        try:
            params = self.load_params_from_yaml(path)
        except Exception as e:
            Log.error('Invalid YAML file, error: {}'. format(e))
            return None
        return params

    @staticmethod
    def yaml_load(camera_configuration):
        return yaml.load(camera_configuration, Loader=yaml.FullLoader)

I also tried using IO straight to the inner function:

    def test_illegal_yaml_file(self):
        un_valid_yaml = io.BytesIO('param 12345678')
        params = MyClass.yaml_load(un_valid_yaml)
        self.assertIsNone(params)

and inside MyClass:

    @staticmethod
    def yaml_load(camera_configuration):
        return yaml.load(camera_configuration, Loader=yaml.FullLoader)

How can I mock it correctly so an exception of invalid YAML file is thrown?

Run a single case test with maven in parallel [BASH]

I need to run n times the same test case and count the number of times the test pass or fail. I wrote the following snippet of code:

CONCATNAME=$CLASSNAME”#”$METHODNAME
PASSTEST=0
FAILTEST=0
TOSEARCH="BUILD SUCCESS"
i=0
for i in $( seq 1 $NROUNDS )
do
    echo "exec command: mvn -Dtest="$CONCATNAME" test"
    message=$(mvn -Dtest=$CONCATNAME test)
    if echo "$message" | grep -q "$TOSEARCH"; then
        PASSTEST=$((PASSTEST+1))
    else 
        FAILTEST=$((FAILTEST+1))
    fi
done

but the execution takes several minutes to complete. Is it possible without modifying the POM.xml file to run the mvn -Dtest command in parallel?

How to test a maven service wich needs another service in java?

I have searched two days for an answer. I tried @Mock, @InjecktMock and @Spy with different additional things, but nothing worked how it was described in tutorials. Many Questions I found dealt with a Problem in Angular, this is my first spring-boot/maven project and have never worked with Angular.

I have a Basic Service for some values I want to be able to change only there but need them in multiple other services. I have written a shortened example of the base structure I want to test and I included the workaround I found for the moment, but would love to know how experienced programmers would go about this.

I have my configuration Service:

@Service
public class ConfigService {
    private final int initialLength = 4;

    public int getInitialLength() {
        return initialLength;
    }

    public double getInitialSquared() {
        return Math.pow(4,2);
    }

}

And another Service using it:

@Service
public class OtherService {

    @Autowired
    ConfigService configService;

    // How I surpassed it for now is overloading and only testing the second function
    String printLine() {
        return printLine(configService.getInitialLength());
    }

    String printLine(int length) {
        StringBuilder output = new StringBuilder();
        for (int i = 0; i < configService.getInitialLength(); i++) {
            output.append("-");
        }
        return output.toString();
    }

}

And my Test for now:

class OtherServiceTest {

    @injectMocks
    OtherService otherService = new OtherService();

    @Test
    void printLine() {
        AssertEquals("----", OtherService.printLine(4));
    }

}

Using CSS Attribute-Selector *= with wildcards

What I currently have is the following selector-specification:

const cssSelector = "td[id*=someTableName--currentState-anotherSpecificationBla-rows-row1-col]";

It works basically, but I would like to remove the middle-part of the search-string to something like this:

// Having 'someTableName' somewhere in the id-value AND further to the left "row1-col" ...

const cssSelector = "td[id*=someTableName*row1-col]";

Shall be: The middle-part replaced with some kind of wild-card.

Is that possible with CSS-selectors? Or does it have to be one continuous string?

Jest/Enzyme React branches

I`m trying to test a focus function and the test coverage tells me about branches. Here is the component

import React, { Component } from 'react';

import Input from '../../components/common/input/Input';
import Button from '../../components/common/button/Button';
import isEmpty from '../../components/common/utils/isEmpty';

class Form extends Component {
  state = { input: '', error: ''};

  onChange = e => this.setState({ ...this.state, input: e.target.value });
  onFocus = () => !isEmpty(this.state.error) && this.setState({ ...this.state, error: '' });

  onSubmit = e => {
    e.preventDefault();
    if(isEmpty(this.state.input)) return this.setState({ ...this.state, error: 'error' });
  };

  render() {
    const { input, error } = this.state;
    return (
      <form noValidate onSubmit={this.onSubmit} data-test='form'>
        <Input
          name='text'
          label='City'
          value={input}
          onChange={this.onChange}
          onFocus={this.onFocus}
          error={error}
          test='input'
        />
        <Button text='Search' isLoading={false} type='submit' />
      </form>
    );
  };
};

export default Form;

and the test file

import React from "react";
import { mount } from 'enzyme';
import Form from "../../../layout/navbar/Form";

const setComponent = (props) => {
  const component = mount(<Form {...props} />);
  return component;
}

describe("Navbar `Form` component", () => {
  let component;

  beforeEach(() => {
    component = setComponent();
  });

  it('Renders without errros', () => {
    expect(component).toMatchSnapshot();
  });

  describe('`onFocus` func call to clear errors', () => {
    it('Clears the error state if any', () => {
      component.find(`button[type='submit']`).simulate('click');
      component.find(`[data-test='input']`).simulate('focus');
      expect(component.state().error).toEqual('');
    });
  });

});

the test is passing but when I test coverage I have a branch on line 11, which is the onFocus function

how can I test the other branch when I have no error in the state?

basically the onfocus => if ERROR setState(...this.state, error: '' )

thank you

I enabled rerunFailingTestsCount Surefire feature. How do I configure Jenkins CI to show the rich test data?

I found out about rerunFailingTestsCount feature in Surefire (commit). When a test fails, the runner tries to rerun it up to a specified number of times. If any of these reruns succeed, the test is considered PASSED, but FLAKY.

This feature implements extension to the JUnit XML report format, with additional attributes in the test result.

How can I configure Jenkins CI to meaningfully show the newly gained test data about my testing?

I would like to be able to monitor my flaky tests, so I can maintain general overview of what's going on, and later so I can prioritize fixing the ones that slow the build the most.

Unexpected Spock failure on File.createTempFile()

I have these lines in a given block of a test/feature:

log.debug( "subdir1 |$subdir1| class ${subdir1.class}")
File.createTempFile​( 'blub', 'odt', subdir1 )

The log message is:

2020-01-30 08:34:47,433 - 1404 ms [Test worker] DEBUG core.IndexCreationSpec [core.IndexCreationSpec] $spock_feature_1_26:706 
subdir1 |/tmp/junit8540540913300320698/subdir1| class class java.io.File

But I'm getting the following Spock fail on the createTempFile line:

groovy.lang.MissingMethodException: No signature of method: static java.io.File.createTempFile​() is applicable for argument types: (String, String, File) values: [blub, odt, /tmp/junit8540540913300320698/subdir1] Possible solutions: createTempFile(java.lang.String, java.lang.String, java.io.File), createTempFile(java.lang.String, java.lang.String), createNewFile(), createTempDir(), createTempDir(java.lang.String, java.lang.String)

This method of File is not one I use very often. There are workarounds to create Files with temporary filenames. But I'm simply baffled by the Spock fail. Is it a Spock failure (i.e. should I submit a bug report)?

mercredi 29 janvier 2020

Changing a jest mock on a specific test

I'm trying to write unit tests for a custom React hook that connects to Firebase. Since I don't want to actually connect to Firebase when running my tests, I've mocked Firebase and Firebase/app. They're super simple mocks, only returning the functions the code actually uses.

// __mocks__/firebase.js
export default {
  analytics: jest.fn(),
  storage: jest.fn()
};
// __mocks__/firebase/app.js
const auth = jest.fn().mockReturnValue({
  currentUser: {
    getIdTokenResult: jest.fn().mockReturnValue({
      claims: jest.fn()
    })
  },
  onIdTokenChanged: jest.fn()
});

export default {
  initializeApp: jest.fn(),
  auth
}

This works fine for some of my tests, but in some cases I need to change values in the mocked file. In a specific case, I want to make sure errors are caught if something goes wrong with Firebase, so I want to make the value of currentUser be false instead (which causes my hook to throw an error so I can test that.

However, I can't figure out how to change the mocked file for one specific test, while leaving it the same for the other tests.

Here's an example of my test file

import { renderHook, cleanup } from '@testing-library/react-hooks';
import useFirebase from 'src/App/useFirebase';

/*
 * For some reason, jest.mock('firebase') doesnt use my custom mock files,
 * so I have to explicitly tell jest which files to use
 */
jest.mock('firebase', () => jest.requireActual('../../../__mocks__/firebase'));
jest.mock('firebase/app', () => jest.requireActual('../../../__mocks__/firebase/app'));

afterEach(cleanup);

test('returns rejected promise if theres an error', async () => {

  // Trying to override the mocked module, with a slightly different one.
  // However, useFirebase.js still uses the first mocked module
  jest.mock('firebase/app', () => ({
    auth: jest.fn().mockReturnValue({
      currentUser: false
    }),
    initializeApp: jest.fn()
  }));

  expect.assertions(1);
  const { result } = renderHook(() => useFirebase());

  // verifyGroup is a function in useFirebase(), that I'm trying to make return
  // a rejected promise
  await result.current.verifyGroup()
    .catch(e => {
      expect(e).not.toBeNull();
    });
});

Nothing I seem to do causes useFirebase.js to use my second mock instead of my first one.

How can I achieve this?

I am Testing the Electron Desktop application using Spectron. I want to click and select the path from dialog box,and dialog message box

describe('Playlist', function () { this.timeout(100000000000)

it('Playlist Screen', async () => { // await app.client.waitUntilWindowLoaded(10000) wait(2000) await app.client .setValue('#username', 'sony95007@gmail.com').pause(1000) .setValue('#password', '123456').pause(1000) .element('#btn-login').isEnabled() .click('#btn-login') // await app.client.waitUntilWindowLoaded(10000) wait(10000) await app.client.windowByIndex(0);
await app.client.click('//[@id="headercontent"]/div/div[2]/div[1]/ul/li[2]/a').pause(3000) await app.client.click('//[@id="headercontent"]/div/div[2]/div[1]/ul/li[2]/div/a').pause(3000) // await app.client.waitUntilWindowLoaded(10000) wait(10000) await app.client.click('/html/body/div[2]/div/div[1]/div/div[1]/div/button[1]').pause(3000) .setValue('#plname','Newpaylist').pause(2000) .click('//*[@id="Button1"]').pause(2000) // await app.client.waitUntilWindowLoaded(10000) wait(5000) // HERE DIALOG BOX OPENING, NEED TO SELECT PATH AND CLICK ON DIALOG BOX BUTTONS })

Is there a better way to write information from a for loop to .txt file?

I'm building a URL Checker that finds broken URLS that I give it then sends an email to me with the results. This is my end result. I had to create another file to write to inside of my for loop then send that file. It works but is there a cleaner way to do this and not have two .txt files and not overwrite what is in the original testurls.txt?

import requests
import smtplib
from email.message import EmailMessage


with open ("testurls.txt", "r") as txt_file:
    for urls in txt_file:
        request = requests.get(urls)
        try:
            request.raise_for_status()
        except Exception as error:
            error = 'There was a problem: %s' % (error)

            with open("listurls.txt", "r+") as f:       
                f.truncate(0)                           #Deletes the files pre existing data
                f.writelines(error+ "\n")               #Writes the new data
            f.close()
        else:
            pass
with open("listurls.txt", "r") as file_to_send:
    msg = EmailMessage()
    msg.set_content(file_to_send.read())

msg['Subject'] = "Here are the list of URLs that don't work"
msg['From'] = 'andrewtalbotprogramming@gmail.com'
msg['To'] = 'andrewtalbotprogramming@gmail.com'

s = smtplib.SMTP_SSL(host='smtp.gmail.com', port=465)
print("Enter Your Password To Continue")
password = input('')
s.login('andrewtalbotprogramming@gmail.com',password)

s.send_message(msg)
s.quit()

Winforms(C#) application security Testing Tools

can any one suggest me the security testing tools for winforms application. Please share the security testing checklist also for the winforms application.

Way to execute scripts in MongoDB 4.2+ using mongodb java driver

Some of my automated tests use real MongoDB database connection, and prior to version 4.2, they had applied initialization script (which contains some indexes and constraints) using db.eval() command, but with the release of 4.2 eval got removed.

Is there another way to repeatedly setup MongoDB environment for auto tests?

(Using embedded Mongo is a undesirable, because I need replica set for several operations, and embedded replica set startup/initialization takes about thirty seconds for each set of tests.)

High quality test cases for Sudoku Solver

I'm making my own version of Sudoku Solver. Are there any open source test cases that I can use to test the efficiency of my algorithm (I don't just want randomized test cases. I want test cases that are marked easy, medium, hard).

Thank you very much!

Get tests running time with Jest

is there any way to know how long my tests take without doing it programmatically with Jest?

To be clear, I know that if I add a variable to get the current time before each test and then log this when my test completes I'll get this information, but I want this automatically, maybe with some Jest configuration.

So, any help on this?

React - functional component, test if a function is called onChange (with Jest and Enzyme)

I have a simple functional component which I need to test.

const Product = () => {
    const handleOnChange = (value) => {
        console.log(value);
    }

    return (
        <div>
            <input type="text" onChange={(e) => {handleOnChange(e.target.value)}} />
        </div>
    )
}

I'd like to test if "handleOnChange" function is called when the input changes its value. I tried that:

let wrapper;
beforeEach(() => {
    wrapper = shallow(<Product />);
});
describe('Product interactions', () => {
it('should call handleOnChange function on input change', () => {

  const mockedhandleOnChange = jest.fn(); 
  wrapper.handleOnChange = mockedhandleOnChange;
  wrapper.find('input').simulate('change', {target: {value: 10}});
  expect(mockedhandleOnChange).toHaveBeenCalledTimes(1);    
});

});

Of course it doesn't work as I cannot reach the function via "wrapper.handleOnChange".

Please help!

Weird eval result when using test

Got a variable called a:

unset b
a="b"

Trying to take this statement:

if test -n "$(eval \$${a})"; then echo Y; fi
# Outputs nothing

which works nicely - it evaluates \$${a} to $b, which is empty and doesn't echo.

Trying to convert the above into something similar to this:

eval "if test -n \$${a}; then echo Y; fi"
# Outputs "Y"

which doesn't work - but even weirder:

eval "if test -z \$${a}; then echo Y; fi"
# Outputs "Y"

Why is this? How is the same statement outputting Y for both the above? Can I format the first statement as I've tried to using eval throughout?

Testing Library: How to get parent node that has a child with Text

In Testing Library, I'm trying to find a way to find elements whose children match a criteria:

<div class="classA">
    <div class="classB">
        <div class="classC">
            some text
        </div>
    </div>
    <div class="classB">
        <div class="classC">
            more text
        </div>
    </div>
</div>

And I would like to find

<div class="classB">
    <div class="classC">
        some text
    </div>
</div>

I tried: getByText(container, 'some text', {selector: 'classB'}) but it returns

<div class="classC">
    some text
</div>

What am i missing to find the container/component/parent that would contain this text

USB 2.0 Signal Integrity Test using EHCI HSET Software

I am trying to test USB 2.0 Signal integrity (Eye Diagram). For doing that, USB IF Forum lets you download the EHCI HSETT Software from their website. However, I am not able to use it due to one persistent problem: No Host Controllers Found

Even though I have tried reinstalling the software, checking that I have the right 64-bit version and loaded the compliance driver manually(which keeps showing that it has errors in the device manager), I still get the same error. anyone that can help with getting this running?

Laravel - Testing API with data dependencies

I'm working on a Laravel application with authentication. The application also has an API. Now I want to test all the API endpoints of the application. The Problem is, that the some Endpoints Need data in the database to "work" with.

How is it possible to test such an application? Do I have to test the application in the correct order to archieve something like that?  

For example:  

  1. create user
  2. create new post
  3. edit new post
  4. create new user
  5. comment post of user 1
  6. login with user 1
  7. see comments of post
  8. delete post

Or is it possible to simulate stuff like this so I don't Need a specific order?

I saw that Laravel has build in HTTP testing, but I don‘t know how to handle the data dependencies.   Thanks for your help!

Have Ruby pull the last downloaded file of specific file type

I'm trying to run an automation test and the end download a document and puts the document file name into console. I'm having trouble helping it locate the most recent document. I'm using ruby and cucumber. Currently running on Firefox. Below is my specific step-def language that works to pull a file, but not exactly the most recent file:

When(/^I can see the file name of download pdf from the (.+) directory displayed on the console 
screen$/) { |path| 
 Dir.foreach(path) do |fname|
if fname.include?(".pdf")
  @file_name = fname
  break
end

end
puts @file_name }

How to mocking the implemented methods of a class under test in Spring Boot with Mockito

I am unsure after much reading how to test the class below.

I have given a basic example...but assuming the class/implemented method could produce a more complex object (not just a String as below), how can I mock the interface so I can inject a mock in to the class to test various class behaviours?

For example, in the oversimplified below...if the length of the 'sayHello' was more than 500chars when calling the class 'getSayHelloLength()', I may want to Assert a 'HelloTooLongException' is thrown.

/**
 * MyClass implements MyInterface.
 */
public class MyClass implements MyInterface {

    public int getSayHelloLength() {
        return sayHello().length();
    }

    //I want to change/Mock the return of the implemented interface.
    @Override
    public String sayHello() {

        //Do some magic and some code an eventually return something based upon 'input'
        // Magic
        // More magic.


        return "My Class to Test Says Hello!";
    }
}

The interface:

public interface MyInterface {
    String sayHello();
}

I am using JUnit5:

class MyClassTest {

    @InjectMocks
    private MyClass myClass;

    @BeforeEach
    void setUp() {
    }

    @Test
    void getSayHelloLength() {
        //Mock the interface 'myClass' implements as to test various "hellos" outputs.
    }
}

Testing Vue When Not Using Single File Components/Webpack

Most of the documentation for testing Vue seems to be focused on the SPA/Vue-CLI use case. I am adding Vue to an existing Flask/Jinja rendered project. As such, the template for my root Vue instance is defined in the html file. I've been able to test individual components using the methods outlined in vue test utils without a build step. However, most of the logic is defined in the root instance options (i.e. showCondition variable or toggle method below).

Would I need to move the template definition from the html page (as defined inside of #app) to a template string inside of Vue instance options? Or is there a way to just mock the template for testing purposes? Also, interested in hearing approaches others take for testing Vue non Vue-CLI/SPA projects.

I realize the more modern way is to just use Vue for the entire front end. That is probably what I will use for my next project. But I'd like to find a way to add testing to the Vue front end functionality without requiring a full rebuild.

Thanks in advance.

Code is below or see here for JSfiddle

html file

<html lang="en">
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="module" src="static/main.js"></script>
  </head>
  <body>
    <div id="app">
      <p v-show="showCondition">Server side generated content, visibility based on vue condition</p> 
      <button type="button" v-on:click="toggle_message">Toggle</button>
    </div>
    <p>Server side content outside of vue target div</p>
  </body>
</html>

main.js

new Vue({
    el: '#app',
    data: {
       showCondition: false,
    },
    methods: {
       toggle_message: function(){
            this.showCondition = ! this.showCondition;
         },
    },
});

How to test exceptional behavior with Puppeteer?

Many have experience with generic automated tests with Puppeteer. This is mostly about imitating user behavior on web pages and asserting results. But what if you need to test representation of errored state, which you cannot (or don’t know how to) trigger by a user action? For example, we have a form. When user submits the app sends a POST request to the server and shows success messages as soon as the server responds with 200 OK. That is the expected behavior. Yet, in real world the server may happened to be down or respond with Internal Error. Imagine the app covers gratefully this case. But how we would reproduce it with Puppeteer?

How can I test the speed of encryption algorithms like (AES, DES, 3DES)


I want to use spark or Ambari to test the speed of encryption between some algorithms?

Good test framework for unit testing on Nuxt, Vue, Express, Mongoose, and GraphQL

I'm looking for a good unit test framework. The web app development is based on Nuxt(Vue), Express, and GraphQL.

So, I would need to test:

  • UI - Nuxt on the front-end
  • models => Mongoose
  • resolvers => GraphQL
  • endpoint => GraphQL
  • Any back-end function => Express

Nuxt seems suggesting to use AVA test framework. So far, it is kind of hard to set up all of these using AVA.

What would be the best test framework to use for this web app?

Unity testing Singleton with NUnit

I have a Unity Project which should create a HoloLens Application. Now i want to test some of my Code in Unity with NUnit. I created some PlayMode tests

public class Test
{
    private GameObject empty;

    [SetUp]
    public void BeforEveryTest()
    {
        empty = new GameObject();
        empty.AddComponent<MainController>();
    }
    // A Test behaves as an ordinary method
    [Test]
    public void MainControllerGetInstance()
    {
        Assert.IsNotNull(MainController.Instance);
    }
}

This is the Singleton I want to test

public class MainController : Singleton<MainController>
{

[SerializeField]
private GameObject SomePref;

private void Start()
{
    SomePrefab.SetActive(true);
} 
}

I get an error that SomePref is not set to an instance of an object, but I can't set it up because its a private seralizedfield. Now what is good practice to erase that error. I know, I could use Resource.Load in the Start Methode from MainController, but is this the good way?

Why dll injection dont work on Windows 10?

:) Has Windows 10 adopted techniques against DLL injection? I am injecting into a user process like notepad but the dll is not started. I see that the thread is created by the return of createRemoteThread but does not open the selected dll (messageBox). I'm in windows 10 64Bit but I'm compiling both dll and injector in 32 bit. Thanks very much !! :) :)

Here the code: Dll File

*****************************************************************

#include <Windows.h>



BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{

if (ul_reason_for_call == DLL_PROCESS_ATTACH)
        MessageBox(0, L"Hello From testlib!", L"Hello", MB_ICONINFORMATION); 

    return TRUE;
}
*************************************************************

#include <iostream>
#include <Windows.h>

int main()
{
    // path to our dll
    LPCSTR DllPath = "D:\\projects\\standardinjection\\release\\testlib.dll";

    // Open a handle to target process
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 17344);

    // Allocate memory for the dllpath in the target process
    // length of the path string + null terminator
    LPVOID pDllPath = VirtualAllocEx(hProcess, 0, strlen(DllPath) + 1,
        MEM_COMMIT, PAGE_READWRITE);

    // Write the path to the address of the memory we just allocated
    // in the target process
    WriteProcessMemory(hProcess, pDllPath, (LPVOID)DllPath,
        strlen(DllPath) + 1, 0);

    // Create a Remote Thread in the target process which
    // calls LoadLibraryA as our dllpath as an argument -> program loads our dll
    HANDLE hLoadThread = CreateRemoteThread(hProcess, 0, 0,
        (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"),
            "LoadLibraryA"), pDllPath, 0, 0);

    // Wait for the execution of our loader thread to finish
    WaitForSingleObject(hLoadThread, INFINITE);

    std::cout << "Dll path allocated at: " << std::hex << pDllPath << std::endl;
    std::cin.get();

    // Free the memory allocated for our dll path
    VirtualFreeEx(hProcess, pDllPath, strlen(DllPath) + 1, MEM_RELEASE);

    return 0;
}

acceptance test with Wiremock to create api request creates instantiate error

I am trying to mock an api request using Wiremock and run a few acceptance tests in my project. But I used the instructions from the site "https://www.baeldung.com/cucumber-rest-api-testing" for the same. i have the classes in the same heirarchy too. what am i missing? below is the stepdefnition class:

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.github.tomakehurst.wiremock.WireMockServer;
public class StepDefinition {

    private static final String CREATE_PATH = "/validate";
    private static final String APPLICATION_JSON = "application/json";

    private final InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("cucumber.json");
    private final String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();

    private final WireMockServer wireMockServer = new WireMockServer(options().dynamicPort());
    //WireMockServer wireMockServer = new WireMockServer();
    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    @When("^users upload data on a project$")
    public void usersUploadDataOnAProject() throws IOException {
        wireMockServer.start();

        configureFor("localhost", wireMockServer.port());
        //configureFor("localhost", 8080);
        stubFor(post(urlEqualTo(CREATE_PATH))
                .withHeader("content-type", equalTo(APPLICATION_JSON))
                .withRequestBody(containing("testing-framework"))
                .willReturn(aResponse().withStatus(200)));

        HttpPost request = new HttpPost("http://localhost:" + wireMockServer.port() + "/validate");
        StringEntity entity = new StringEntity(jsonString);
        request.addHeader("content-type", APPLICATION_JSON);
        request.setEntity(entity);
        HttpResponse response = httpClient.execute(request);

        assertEquals(200, response.getStatusLine().getStatusCode());
        verify(postRequestedFor(urlEqualTo(CREATE_PATH))
                .withHeader("content-type", equalTo(APPLICATION_JSON)));

        wireMockServer.stop();
    }'''

I tried a mvn install gives me the below exception:

<testcase classname="Scenario: Data Upload to a web service" name="When users upload data on a project" time="0.042">
    <error message="Failed to instantiate class com.example.rest.StepDefinition" type="cucumber.runtime.CucumberException">cucumber.runtime.CucumberException: Failed to instantiate class com.example.rest.StepDefinition
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:46)
    at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:32)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:299)
    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:91)
    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 cucumber.api.junit.Cucumber.runChild(Cucumber.java:93)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:37)
    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.api.junit.Cucumber.run(Cucumber.java:98)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    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:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:40)
    ... 38 more
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.apache.http.conn.ssl.AbstractVerifier.&lt;init&gt;(AbstractVerifier.java:60)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.&lt;init&gt;(AllowAllHostnameVerifier.java:43)
    at org.apache.http.conn.ssl.AllowAllHostnameVerifier.&lt;clinit&gt;(AllowAllHostnameVerifier.java:45)
    at com.github.tomakehurst.wiremock.http.HttpClientFactory.createClient(HttpClientFactory.java:60)
    at com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.&lt;init&gt;(ProxyResponseRenderer.java:59)
    at com.github.tomakehurst.wiremock.core.WireMockApp.buildStubRequestHandler(WireMockApp.java:139)
    at com.github.tomakehurst.wiremock.WireMockServer.&lt;init&gt;(WireMockServer.java:73)
    at com.example.rest.StepDefinition.&lt;init&gt;(StepDefinition.java:43)
    ... 43 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 51 more

I have the below dependencies in my pom.

<dependencies>

     <!-- utils -->

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

        <!-- http client -->

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>${httpcore.version}</version>
        </dependency>

    <!-- Wiremock dependency-->
        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
            <version>${wiremock.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock-jre8</artifactId>
            <version>2.23.0</version>
            <type>pom</type>
            <scope>test</scope>
        </dependency>

         <!-- Test Cucumber -->  
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>

      <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>java-hamcrest</artifactId>
            <version>2.0.0.0</version>
            <scope>test</scope>
      </dependency>

  </dependencies>

  <build>
        <finalName>rest-testing</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <parallel>classes</parallel>
                    <threadCount>4</threadCount>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.temyers</groupId>
                <artifactId>cucumber-jvm-parallel-plugin</artifactId>
                <version>5.0.0</version>
                <executions>
                    <execution>
                        <id>generateRunners</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>generateRunners</goal>
                        </goals>
                        <configuration>
                            <glue>
                                <package>com.example.rest</package>
                            </glue>
                            <featuresDirectory>src/test/resources/Feature/</featuresDirectory>
                            <parallelScheme>SCENARIO</parallelScheme>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

Need to export manual test runs execution results from AzureDevOps to any Format

We need to export the lastest run with every step's and it's attachments in AzureDevOps. It is a 300 Test Cases run/execution report that needs to be approved, as we have many use cases, it is not pausible to go one run by one run and download every attachment step and print it by hand.

I tried exporting TestPlans, the export from Test Plan does not apply in this case as it does not care about the runs steps and its attachments. I do not see a solution with the new AzureDevOps run Page,

Would like to know if I am missing any configuration option or if there is an API or even product to export the data. e.g. Example one of many Runs to save in Report Many

I saw other similar questions but still missing how to export runs reports with it's steps and attachment. Image below,

Example of one of the 300 runs to export

Many Thanks

mardi 28 janvier 2020

website keep the previous session even after closing browser tab

i'm testing an old website and i'm facing an issue and not sure how to describe well , but here's the scenario :

1- I open the URL for first time

2- I click on any button ( for example Forget my password button ) and page will redirected to Forget my password page

3- I close the browser tab

4- I open the same URL from step 1 ( Homepage URL ) , here it will redirected me to Forget my password page

Why it keeps the session ? i'm not sure what this issue is calling and i can't find similar issue like this one. please don't suggest to clear cache because i have to do this every time + i can't press Back and Next button in the browser.

Finding Edge Cases and Exceptions

While solving medium/hard problems on competitive programming sites, I tend not to have a problem with the logic and my code, more often than not, does well with the same input. However, my code often passes only some test cases. This is because, I tend to ignore the exceptions i.e. the few cases where my code doesn't work. As I can't access the expected o/p, I'm not able to look where it's going wrong. How to get better at finding such edge cases and exceptions, and make my code immune to them?

I understand this might go away as I keep coding, but am looking for ways to learn it faster and better. I use C++, if that helps.

What are some good example projects of testing done well in Rust code? [closed]

Looking for a github link to a well designed and organised test folder. Projects that use the standard asserts and test attributes built into Rust. Not an external testing framework.

How to test angluar app with node.js backend

recently i've been learning some angular and node js. I've created something like marketplace using this two. https://github.com/MrRav3n/Angular-Marketplace here is my respository.

I'm writting because i want to start my journey with testing. I've read already some basics tutorials but i still havent found angluar + node.js testing. You know.. i dont want to test node.js and angular separately. Is there posibility to test only angluar.js app (wait for callbacks etc) and doing it in some way test node.js? I dont know if i said everything understandable. Sorry for that.

Thanks in advance!

PS. i'm looking for some exaples from web (you can just pass a link or smth) or example with my code (products.service.ts is component i would like to test, server.js is my backend) ^^

What does Undefined index mean: SELENIUM HUB in Selenium with phpunit?

I am trying to use katalon with selenium with the export for phpunit (since selenium removed it) to do a user test and it is coming out to me that Undefined index: SELENIUM_HUB, could you tell me to laugh the same? I'm looking for and I can't find something to clarify how to solve. This the code with the error.I'm using wamp as a localhost and I don't know if it can be on that side the problem Thanks

  <?php
namespace Test;

use PHPUnit\Framework\TestCase;
use Facebook\WebDriver;
require_once('vendor/autoload.php');

class ProbandoLaPagTest extends TestCase
{
    /**
     * @var WebDriver\Remote\RemoteWebDriver
     */
    private $webDriver;

    /**
     * @var string
     */
    private $baseUrl;

    /**
     * init webdriver
     */
    public function setUp():void
    {
        $desiredCapabilities = WebDriver\Remote\DesiredCapabilities::chrome();
        $desiredCapabilities->setCapability('trustAllSSLCertificates', true);
        $this->webDriver = WebDriver\Remote\RemoteWebDriver::create(
            $_SERVER['SELENIUM_HUB'],
            $desiredCapabilities
        );
        $this->baseUrl = $_SERVER['SELENIUM_BASE_URL'];
    }

    /**
     * Method testProbandoLaPag
     * @test
     */
    public function testProbandoLaPag()
    {
        // open | http://turi/ | 
        $this->webDriver->get("http://turi/");
        // click | link=Contacto | 
        $this->webDriver->findElement(WebDriver\WebDriverBy::linkText("Contacto"))->click();
        // click | id=nombre | 
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("nombre"))->click();
        // type | id=nombre | Ezequiel
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("nombre"))->sendKeys("Ezequiel");
        // type | id=apellido | Ledesma
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("apellido"))->sendKeys("Ledesma");
        // type | id=email | ezequiel.ledesma026@gmail.com
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("email"))->sendKeys("ezequiel.ledesma026@gmail.com");
        // click | id=telefono | 
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("telefono"))->click();
        // type | id=telefono | 47347866
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("telefono"))->sendKeys("47347866");
        // click | id=mensaje | 
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("mensaje"))->click();
        // type | id=mensaje | Se prueba escribiendo un mensaje 
        $this->webDriver->findElement(WebDriver\WebDriverBy::id("mensaje"))->sendKeys("Se prueba escribiendo un mensaje");
        // click | name=submit | 
        $this->webDriver->findElement(WebDriver\WebDriverBy::name("submit"))->click();
    }

    /**
     * Close the current window.
     */
    public function tearDown():void
    {
        $this->webDriver->close();
    }

    /**
     * @param WebDriver\Remote\RemoteWebElement $element
     *
     * @return WebDriver\WebDriverSelect
     * @throws WebDriver\Exception\UnexpectedTagNameException
     */
    private function getSelect(WebDriver\Remote\RemoteWebElement $element): WebDriver\WebDriverSelect
    {
        return new WebDriver\WebDriverSelect($element);
    }
}

Moving Repository from Git and Bitbucket, how to test this process that its done properly? (icludes history, tags, commits,etc)

Our Org is moving prohjects from GIT to Bitbucket, hence our the process is complete. We need to test that nothing missing once the copy is done in Bitbucket. (it should be as is of Git)

Comparing XAMPP and php -S localhost:8000, they look very different

I've set up local testing using both XAMPP and php -S localhost:8000. When I compare the website that is produced from both, the website behaves and looks different from each other. However, the same codebase hosted on the web server looks completely fine and behaves alright.

How am I supposed to know if my changes will work properly on the actual web server if they don't show up properly during local testing?

I'm forced to test locally because my co-workers don't seem to know how to set up the dev environment for me to edit the files on a staging server accurately.... Please help!

Assert Laravel Command is Called in Test

I call Laravel commands from a Laravel command. It works, but I want to test if the subcommands A and/or B are called.

Below a simplified version:

final class HandleActions extends Command
{
    public function handle()
    {
        foreach ($items as $item) {
            if ($item->price * 2.24 > 100) {
                $this->call('order:reprocess'); // command A
            }

            if (!$item->stock) {
                $this->call('order:cleanup'); // command B
            }
        }
    }
}

I test this command like so (simplified), so I know that the main command is excited successfully.

    $this->artisan('command')->assertExitCode(0);
    // How do I assert command A is fired?
    // How do I assert command B is fired?

I want to assert that subcommand 1 is fired and/or subcommand 2 fired. But how to do this?

How to run jest test inside other test block?

For example I have 2 test, how can I test one depend on another one? Sometimes, we want to have some E2E test, which could reproduce same test steps.

What I think right now is using separate function for testing, but if there is a quick way to run other test with one statement which would be great.

test('test1', () => {
})
test('test2', () => {
  // run test1 here
})

Inspec command not printing the memory of a server

By executing from inspec.backend.run_command. It's only printing CPU and not memory if i use awk in $memory.

Here is my code:

control 'nodes_certs' do
impact 0.7
title 'nodes_certs'
desc 'An optional description...'

nodecert=inspec.backend.run_command("name() { local cpu=$(nproc); local mem=$(free -g | awk \'/Mem/ {print $2}\'); echo $cpu; echo $mem ; }; name\'").stdout

print nodecert

end

Here is output:

16

Profile: tests from mem.rb (tests from mem.rb) Version: (not specified) Target: local://

 No tests executed.

How to insert data into a table in testcafe

I have a page with with a table. I want to make an automation test with testcafe + javascript and insert values into the rows.

Tried with addCustomMethods as in https://devexpress.github.io/testcafe/documentation/test-api/selecting-page-elements/selectors/extending-selectors.html but it doesnot seem to work as it doesnot get the table and returns undefined.

So how do I insert values to multiple rows in a table?

How to create test suites in Android-Studio using AndroidJUnit4?

There are some UI tests. It is necessary to find an opportunity to somehow group them and call for execution by groups. Perhaps there is some option how to group tests through annotations in the BDD approach and run different test groups through annotations? Or what other way to break tests into suites what would it was convenient to call one suite for one environment, and the second suite for regression, for example.

Angular testing: Method returning an observable is successfully tested, but test coverage still marks it as noncovered statement

I want to test this method:

public getAll(): Observable<Array<Todo>> {
    return this.$http.get<Array<Todo>>('http://5def6a2502b2d90014e1b38a.mockapi.io/api/v1/todos/');
}

I've written a test for this method:

it('should return array of todos', (done: DoneFn) => {
    const mockedValue = [new Todo('Test')];
    spyOn(service, 'getAll').and.returnValue(of(mockedValue));
    service.getAll().subscribe((value) => {
        expect(value).toBe(mockedValue);
        done();
    });
});

When i run ng test, this test is marked as successful, but code-coverage still marks it like an uncovered test:

enter image description here

Why? And how I can cover it?

How to resolve the error "Unexpected Element: CDATA" while running test step thru groovy script?

I'm running test suite which contains 15 test steps mixed with groovy script and soap request steps.

It runs perfectly when I'm running manually where as its giving the error message like "Unexpected Element: CDATA" while executing thru the groovy script.

Groovy Script:

for(tc in testsuite.testCaseList)
{
   for(stp in tc.testStepList)
   {
      if (!stp.isDisabled())
      {
         testRunner.runTestStep(stp)

         def assertionList = stp.getAssertionList()
         ..........
      }
   }
}

Get Response Data thru another groovy script step:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def responseHolder = groovyUtils.getXmlHolder("requestName#Response")
def appId = responseHolder.getNodeValue("//*:application/*:applicationId")

testRunner.testCase.testSuite.setPropertyValue("AppId",appId)

Could anyone give me your suggestion to resolve this issue?

Thanks
Karunagara Pandi G

How to check if a server is accepting invalid cookies?

i'm currently testing a web system that used to accept invalid cookies. This was tested by simply opening the browser inspector and changing them. After that the cookie never changed back to the correct value or had any other side effects.

Since this was identified as potential security problem changes were made to not accept invalid cookies. When i change the cookie value now it immediately changes back to the original value after loading a new page. This seems like correct behaviour but i'm kinda lacking the validation that the wrong value is not being accepted by the server.

So how can i check this? What do i need to watch in the inspector to see if the wrong value was not just corrected but also discarded by the server? Is that even possible with just the inspector or do i need access to the server in order to check it?

Thanks for your help!

Python image difference with vertical tolerances

I can compare 2 images and find the area where they for instance if a name is missing from a credit card the program will draw a red box around the area where the images differ.

But I am currently visually testing website with screen shots, and often when one web element is missing the other elements get shifted upwards, thus breaking the image comparison algorithm.

Is there a way of comparing 2 images with vertical tolerance ?

P.S. I know blink-diff by yahoo has this function

Creating an Abstract Interface around DB Connection

I was reading this article on Unit Testing. It seems pretty straightforward, but there was a section that interested me and I wanted to see if someone could please provide an explanation or example of what this means. I think I understand it but maybe not well enough.

Write test cases that are independent of each other. For example, if a class depends on a database, do not write a case that interacts with the database to test the class. Instead, create an abstract interface around that database connection and implement that interface with a mock object.

What does it mean to:

  1. create an abstract interface around the db connection?
  2. then implement it with a mock object?

I am more questioning the first part (1) but if someone can explain both parts that would be helpful. Thanks.

lundi 27 janvier 2020

Reportportal - nightwatch-cucumber agent

Is there reportportal nightwatch-cucumber agent available? My app needs the nightwatch-cucumber agent to push the report to reportportal. If not, is there any work around for it? Below is the list of current available agents. https://github.com/reportportal?utf8=%E2%9C%93&q=javascript&type=&language= I have used the agent-js-cucumber but that would not push the report. I have also tried agent-js-nightwatch without much luck.

Automated Testing (Desktop) using Selenium in C#/xUnit

How can we do as I am very new to both Selenium and C# x Unit testing

How to test @Model data classes from Jetpack Compose?

I'm trying to test a mapper function between my UI layer and my Domain layer.

But I get an exception thrown of java.lang.IllegalStateException: Not in a frame

This exception goes away if I change my UIModel to have a val instead of a var but then it is useless with the model updates that Jetpack Compose offers.

Is there a way to test this type of mapper?

import androidx.compose.Model
import org.junit.Assert.assertEquals
import org.junit.Test

class DataModelMapperTest {

    @Test
    fun `data model to ui model`() {
        val model = DataModel(5)
        val uiModel = UIModel(5)

        assertEquals(uiModel, model.toUIModel())
    }

    @Test
    fun `ui model to data model`() {
        val model = DataModel(5)
        val uiModel = UIModel(5)

        assertEquals(model, uiModel.toDataModel())
    }

}

@Model
data class UIModel(var value: Int)

data class DataModel(val value: Int)

fun DataModel.toUIModel(): UIModel = UIModel(this.value)

fun UIModel.toDataModel(): DataModel = DataModel(this.value)

Django.core.exceptions.ImproperlyConfigured: Error running functional_tests.py

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

my functional tests:

from selenium import webdriver
from lists.models import Item
from selenium.webdriver.common.keys import Keys
import time
import unittest
import os



class NewVisitorTest(unittest.TestCase):
def setUp(self):
    self.browser = webdriver.Firefox()
def tearDown(self):
    self.browser.quit()

def test_can_start_a_list_and_retrieve_it_later(self):
    self.browser.get('http://localhost:8000/')
    # She notices the page title and header mention to-do lists
    print(self.browser.title)
    self.assertIn('lists', self.browser.title)
    header_text = self.browser.find_element_by_tag_name('h1').text
    self.assertIn('list', header_text)

    inputbox = self.browser.find_element_by_id('id_new_item')
    self.assertEqual(
    inputbox.get_attribute('placeholder'),
    'Enter a to-do item'
    )
    inputbox.send_keys('Buy peacock feathers')
    inputbox.send_keys(Keys.ENTER)
    time.sleep(1)
    table = self.browser.find_element_by_id('id_list_table')
    rows = table.find_elements_by_tag_name('tr')
    self.assertIn('1: Buy peacock feathers',[row.text for row in rows])
    self.assertIn('2: Use a peacock feather', [row.text for row in rows])
    self.fail('Finish the test!')


def check_for_row_in_list_table(self,row_text):
    table = self.browser.find_element__by_id('id_list_table')
    rows = table.find_element_by_tag_name('tr')
    self.assertIn(row_text,[row.text for row in rows])    
    inputbox.send_keys(Keys.ENTER)
    time.sleep(1)
    self.check_for_row_in_list_table('1:Buy a peacock feather')
    inputbox = self.browser.find_element_by_id('id_new_item')
    input.send_keys('Use peacock feathers to make a fly')
    inputbox.send_keys(Keys.ENTER)
    time.sleep(1)
    self.check_for_row_in_list_table('1:Buy a peacock feather')
    self.check_for_row_in_list_table('2: Use a peacock feather')


if __name__ == '__main__':
unittest.main(warnings='ignore')

my models :When I try to run functional_tests I get the error.

from django.db import models


class Item(models.Model):
text = models.TextField(default='')

my settings file . I have included the list app in my INSTALLED_APPS too.

import os


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'xyz'

DEBUG = True

ALLOWED_HOSTS = []


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'lists.apps.ListsConfig',
]

Nock: Not intercepting on BitBucket but intercepts localhost

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

Test function in React functional component with Jest and Enzyme

I need to test a private function from a functional component, but I could not find a way to do it, someone can help? Thanks

This is my component code:

const PageHeader = props => {
  const { navLinks, toolTitle } = props;
  const { tool, toolGlobal } = toolTitle;
  const { authData, setAuthData } = useAuth();

  const [dropdownOpen, setDropdownOpen] = useState(false);
  const toggle = () => setDropdownOpen(prevState => !prevState);
  const logout = () => setAuthData('');

  return (
    <Header {...props}>
      <Container fluid>
        <Row className="align-items-center border-bottom pl-4">
          <Col sm="auto" className="d-flex">
            <h5 className="text-muted pr-2 mb-0 border-right">{toolGlobal}</h5>
            <h5 className="mb-0 pl-2 font-weight-bold">{tool}</h5>
          </Col>
          <Col className="d-flex align-items-center justify-content-center pl-0">
            <PageNav navLinks={navLinks} />
          </Col>
          <Col sm= className="d-flex align-items-center pl-0">
            <Dropdown isOpen={dropdownOpen} toggle={toggle}>
              <DropdownToggle tag="span" data-toggle="dropdown" aria-expanded={dropdownOpen}>
                <Button color="outline">
                  <i className="fas fa-user-circle text-black-50" />
                </Button>
              </DropdownToggle>
              <DropdownMenu right>
                <DropdownItem disabled>{authData.user_name}</DropdownItem>
                <DropdownItem divider />
                <DropdownItem onClick={logout}>Logout</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </Col>
        </Row>
      </Container>
    </Header>
  );
};

I need to test the logout function

My test code:

describe('PageHeader', () => {
  useAuth.mockImplementation(() => context);

  const wrapper = shallow(<PageHeader />, { context });

  beforeEach(() => {
    wrapper.setProps({});
  });

... ...

  it('logout the user on DropDownItem Logout button', () => {
    // wrapper.setContext(context);
    /* Here I want to click the loguot button as 
       wrapper
         .find('Dropdown')
         .find('DropdownItem:last-child')
         .simulate('click');
       And then check the authData to findout if the
       logout function was called but nothing works */

    console.log(wrapper.context());
  });
});

I've got this error ShallowWrapper::context() can only be called on wrapped nodes that have a non-null instance

I've tried everything to test that function, nothing works as I hope, please help.

Thanks in advance