mardi 30 juin 2020

How to sort json files and compare?

I have two json files which are similar but in different order. So the tests are failing while comparing. Can anyone suggest how to sort the json files before comparing them.

I have two json files which are similar but in different order. So the tests are failing while comparing. Can anyone suggest how to sort the json files before comparing them. Thanks in advance.

JSON-1

    {
"RowHeaders":[
     [
            {
                "DimensionName": "Account",
                "Label": "1013ETL",
                "MemberId": "1203"
            },
            {
                "DimensionName": "Measures",
                "Label": "MTD",
                "MemberId": "MTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ],
        
      [
            {
                "DimensionName": "Account",
                "Label": "2010ETL - A/P - Trade",
                "MemberId": "1210"
            },
            {
                "DimensionName": "Measures",
                "Label": "YTD",
                "MemberId": "YTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ],

       [
            {
                "DimensionName": "Account",
                "Label": "3030ETL - Retained Earnings - Beginning of Year",
                "MemberId": "1221"
            },
            {
                "DimensionName": "Measures",
                "Label": "YTD",
                "MemberId": "YTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ]
     ],
    "Status":"Success",
     "StatusMessage":""
    }

JSON-2

{
"RowHeaders":[
       [
            {
                "DimensionName": "Account",
                "Label": "1013ETL",
                "MemberId": "1203"
            },
            {
                "DimensionName": "Measures",
                "Label": "MTD",
                "MemberId": "MTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ],
        
        [
            {
                "DimensionName": "Account",
                "Label": "3030ETL - Retained Earnings - Beginning of Year",
                "MemberId": "1221"
            },
            {
                "DimensionName": "Measures",
                "Label": "YTD",
                "MemberId": "YTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ],
        
        [
            {
                "DimensionName": "Account",
                "Label": "2010ETL - A/P - Trade",
                "MemberId": "1210"
            },
            {
                "DimensionName": "Measures",
                "Label": "YTD",
                "MemberId": "YTD"
            },
            {
                "DimensionName": "Reporting",
                "Label": "Consolidated (CC)",
                "MemberId": "14"
            }
        ]
     ],
"Status":"Success",
 "StatusMessage":""
}

How to test map() result props passed to a child componente through react render function?

Im new in React test and Im blocked in this case of my side-project. I have these components that im working on it. And I need to test, in this specific case, the child component if it returns the text that I want.

function FatherComponent(props) {
  let myItems = props.listOfItems.placeItemsObject; //access a json
  let myMessage = props.listofMessages.messagesObject; //access a json

  return (
    <div>
      {myItems && myItems.length > 0 && (
        <div>
          {myItems.map((item, index) => {
            return (
              <div key={item.itemId}>
                <ChildComponent item={item} myMessage={myMessage} />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export { FatherComponent };
function ChildComponent(props) {
  let myMessage = props.myMessage;
  let item = props.item;

  return (
    <div className="my-new-component">
      {item.itemCount > 1 ? myMessage.aprovedTittle : myMessage.oldTittle}:
    </div>
  );
}

export { ChildComponent };

Im trying to test both scenarios (aprovedTittle and oldTittle), and it keeps returning these error message TypeError: Cannot read property 'itemCount' of undefined, message TypeError: Cannot read property 'aprovedTittle' of undefined and message TypeError: Cannot read property 'oldTittle' of undefined.

describe("ChildComponent", () => {
  const wrapper = mount(<ChildComponent item={item} myMessage={myMessage} />);
  describe("for aprovedTittle case", () => {
    it("should displays 'Approved tittle'", () => {
      const text = wrapper.find('div[className="my-new-component"]').first();
      const expectedText = "Approved tittle";
      expect(text.text()).toBe(expectedText);
    });

    it("should displays 'Approved tittle'", () => {
      const text = wrapper.find('div[className="my-new-component"]').first();
      const expectedText = "Old Tittle tittle";
      expect(text.text()).toBe(expectedText);
    });
  });
});

I guess it seems that it cannot access the props provided by the map loop from the FatherComponent. How do I have to test for that?

JAWS reads Headings as clikable even though parent div has not click handler associated

I am working on accessibility testing for an Angular project. I have some code for a modal that is as below

<div class="modal fade" bsModal #cancelConfirmModal="bs-modal" tabindex="-1" role="dialog"
    attr.aria-label="Cancel Modal" aria-hidden="true">
    <div class="md-dialog modal-md">
        <!-- Modal content-->
        <div class="md-content">
            <div class="md-header">
                <div class="md-title pull-left">
                    <h4 tabindex=0 class="headerBottomMarginNone"> Cancel</h4>
                </div>
                <button type="button" class="close-popup" (click)="hideCancelModal()">
                    <img src="/close.png" alt="Close Icon"
                        (mouseover)="changeCloseIconOnHover('close-popup3')"
                        (mouseout)="changeCloseIcon('close-popup3')" id="close-popup3">
                    <label class="sr-only">Close</label>
                </button>
            </div>
            <div tabindex=0 class="md-body">
                
            </div>
            <div class="md-footer">
                <button type="reset pull-right" class="ts-btn ts-btn-primary no-btm-margin" (click)="revert()">Yes</button>
                <button type="pull-right" (click)="hideCancelModal()"
                    class="ts-btn ts-btn-tertiary margin-left10 no-btm-margin">Cancel</button>
            </div>
        </div>
    </div>
</div>

When I tab over to <h4 tabindex=0 class="headerBottomMarginNone"> Cancel</h4> it reads Cancel heading level 4 clickable. There is no click event on the parent or even its parent. h4 is made tab reachable as per the QA's preference. How do I stop JAWS from announcing clickable??

How to split test and train size

I am trying to feed a CNN model(Human body pose estimation)with a dataset contains 1000 numbers, first, how can I make sure that the number of my datasets is already enough? second, how should i split my data to train and test size? (when I put train size = 0.6 and test_size = 0.4 the network doesnt work well and show me NAN for weights and bias and loss value!)

Expected mock function to have been called one time, but it was called zero times - Jest unit test

I'm trying to write unit test(jest) for my status change API (MolecularJs).Therefor i have tried to mock my db .but i'm getting below error.

expect(jest.fn()).toBeCalledTimes(1)

Expected mock function to have been called one time, but it was called zero times.
  26 |          
> 27 |             expect(mockStatus).toBeCalledTimes(1);
     |                                ^
  28 |             expect(mockStatus).toBeCalledWith({ campaignId: "5ef5746bcb5485210fa1f0fe",status: 0 });
  29 |         });

test.js

describe("Test service", () => {
    let broker = new ServiceBroker();
    let moService=broker.createService(MoService);  

    const mockStatus = jest.fn(params =>    
        Promise.resolve({ campaignId: params.campaignId, status: params.name })
    );

    beforeAll(() => broker.start());
    afterAll(() => broker.stop());
    
    describe("Test Campaign status change API", () => {
        it("should return inactive", async () => {
            moService.adapter.insert = mockStatus;

            let result = await broker.call("inbox.changeStatus", { campaignId: "5ef5746bcb5485210fa1f0fe",status: 0  });
            
        expect(result.status).toBe(0);
            
            expect(mockStatus).toBeCalledTimes(1);
            expect(mockStatus).toBeCalledWith({ campaignId: "5ef5746bcb5485210fa1f0fe",status: 0 });
        });
    });
});

how to write Junit testing for a method that prompts the user for an int

I have a method which asks the user to choose a number between 1 and 7. It uses the Scanner class to take the users input as an int. I saw how to code this for a string, but how would I modify that for int? My method is...

/** * This method asks the player to choose a column 1-7. If the player enters a number

  • outside this range
    • the method will continually ask until a correct number is entered. The column is
  • decreased by one to account for
    • arrays starting at 0 and returned

    • @param turn Player which ever players turn it is, is asked for a column

    • @return int the column is returned after lowered by one */ public static int askForColumn(Player turn) {

      System.out.println("\n\n" + turn.getTag() + " please enter the column number, 1-7, \n" + "where you would like to drop your game piece. "); boolean colCorrect = false; int column = -1; while (!colCorrect){ if(Connect4TextConsole.in.hasNextInt()){ column = Connect4TextConsole.in.nextInt(); colCorrect = true;} else{ System.out.println("Please enter a number 1 through 7."); Connect4TextConsole.in.next();}} while(column < 1 || column > 7) { System.out.println("Please enter a number 1 through 7."); column = Connect4TextConsole.in.nextInt(); } return column - 1; // subtract one to account for array starting at zero }

How to get a wrong password warning with Cypress before it disappears?

Heres my workflow -> type invalid user -> type invalid password -> Click Login -> "Wrong Credentials" box should appear and disappear after some time. The issue is that i cant cy.get() the box before it disappears, i've tried using cy.clock() and cy.tick() but i didnt understood how it properly worked, so how do i get it?

Test JPA repository for void functions and updates and deletes

I working on writing tests for a crud application. I need to test the service and repository for Delete and Update statements. How would I go about mocking the repository for delete and update since they won't be returning data?

For example:

@Override
public void makeUserActive(long userId) {
   try {
       Optional<UserEntity> userEntityList = usersJpaRepository.findById(userId);
       UserEntity userEntity = userEntityList.get();
       userEntity.setIsActive(1);
       usersJpaRepository.save(userEntity);
   } catch (Exception e) {
       logger.error("Cant make active user", e);
   }
 }

How do i test the service that mocks this repository and also the repository itself since it wont be returning a value

Jest: Does not allow mocked method to be overwritten

Given the following test code:

import { MyParentClass } from "MyParentClass";
import { MyClass } from "MyClass";

MyClass.prototype.post = jest.fn(() => Promise.resolve({token: '12345'}));

it('first test: this test will be successful tested ✓', async() => {
    const myParentClass = new MyParentClass();
    await expect(myParentClass.run()).toEqual({token: '12345'});
})

it('second test: this test will fail ×', async () => {
    MyClass.prototype.post = jest.fn(() => Promise.reject({message: 'An error ocurred'}));
    const myParentClass = new MyParentClass();
    await expect(myParentClass.run()).rejects.toEqual({message: 'success'});
})

The "run" method internally makes use of the 'MyClass' class and its "post" method. When I run a code like this, for my second test, I get a message like the following:

"Received promise resolved instead of rejected"

I understand that when the answer for the "post" method is globally defined, it will always take that value, but I also understand that in the second test I am overwriting the behavior of that method, why don't you take it into account?

I know I can also use jest.doMock, but I don't understand the documentation well, could someone help me understand it to apply it to my example?

Where do I run asynchronous code required for test setup in Jest?

I want to dynamically run multiple tests in Jest inside a for-loop but I am not sure where to place the asynchronous code that my test environment requires.

One option that works is to place all asynchronous code inside a test function and execute an assert statement for each iteration of the for-loop.

 describe('Database Testing', () => {

   test(`Testing ${items}`, async () => {

     const items = await getItems(); //<-- asynchronous code

     for (const item of items) {

        expect('hi').toEqual('hi');
     }
   });
 });

However, if the test fails, I will not be able to pinpoint which loop the assert statement failed in. Instead, I would like a structure similar to below where I dynamically run a test for each iteration of the for-loop.

 describe('Database Testing', () => {

   const items = await getItems(); //<-- asynchronous code

   for (const item of items) {

      test(`Testing ${item}`, async () => {
         expect('hi').toEqual('hi');
       });
    };
 });

I am unable to run the asynchronous code due to the synchronous nature of the describe function. Yet, if I use the async keyword in the describe function, I get the error 'Returning a Promise from "describe" is not supported'.

Where should I run the asynchronous code?

How to integration test a RESTful APIs PUT endpoint with TestRestTemplate?

I'm currently working on a Spring Boot CRUD RESTful API with an User entity that consists of two parameters : name and id. Its endpoints are :

  • POST REQUEST IN /users - Create an user
  • GET REQUEST IN /users/{id} - List a specific user by its id
  • GET REQUEST IN /users - List all users
  • PUT REQUEST IN /users/{id} - Update a specific user by its id
  • DELETE REQUEST IN /users/{id} - Delete a specific user by its id

Each endpoint is built with a controller and a service to implement its logic.

I've already wrote unit tests for my controllers and services, now i'm trying to build integration tests to assert that my endpoints work properly as a group of components.

No mocking involved, all this will be done by using the TestRestTemplate and asserting that every operation was executed correctly and every response checked with its expected value.

The following are the tests I've already built :

@SpringBootTest(classes = UsersApiApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();
    HttpHeaders headers = new HttpHeaders();

    private void instantiateNewUser() {
        User userNumberFour = new User();
        userNumberFour.setName("Four");
        userNumberFour.setId(4L);

        ResponseEntity<User> responseEntity = restTemplate
                .postForEntity(createURLWithPort("/users"), userNumberFour, User.class);
    }

    @Test
    public void createNewUserTest() {
        User testUser = new User();
        testUser.setName("Test User");
        testUser.setId(5L);

        ResponseEntity<User> responseEntity = restTemplate
                .postForEntity(createURLWithPort("/users"), testUser, User.class);

        assertEquals(201, responseEntity.getStatusCodeValue());
        assertEquals(responseEntity.getBody(), testUser);
    }


    @Test
    public void listSpecificUserTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.GET, httpEntity, String.class);

        String expectedResponseBody = "{id:4,name:Four}";

        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
    }

    @Test
    public void listAllUsersTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users"),
                HttpMethod.GET, httpEntity, String.class);

        //All instantiated users
        ArrayList<String> expectedResponseBody = new ArrayList<>(Collections.emptyList());
        expectedResponseBody.add("{id:1,name:Neo}");
        expectedResponseBody.add("{id:2,name:Owt}");
        expectedResponseBody.add("{id:3,name:Three}");
        expectedResponseBody.add("{id:4,name:Four}");

        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(String.valueOf(expectedResponseBody), responseEntity.getBody(), false);
    }

    @Test
    public void deleteSpecificUserTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.DELETE, httpEntity, String.class);

        assertEquals(204, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(null, responseEntity.getBody(), false);
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }
}

As you can see, it's missing the PUT request method test, which is the update endpoint. To implement its logic, i need to send a message body with the content that will override the old users characteristics, but how?

This is what i made so far :

    @Test
    public void updateSpecificUserTest() throws JSONException {
    
        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
    
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.PUT, httpEntity, String.class);

        String expectedResponseBody = "{id:4,name:Four Updated}";
    
        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
    }
    

Would appreciate if someone could help with this one, didn't found the answer online.

How to tell if a string contains HTML tags or spaces in JavaScript? [duplicate]

I have a regex to test for HTML tags:

const isValueInvalid = /(<([^>]+)>)/gi.test(value);

But I need to test for spaces (whitespace) in the string as well.

How do I update the regex to cater for that case?

Sending Login Attempts from Multiple Browser and Operating System

Recently, I need to test the our login script from the Multiple Browser and Operating System. I wrote some protection on login module for the credential stuffing or bruteforce attack. For understanding, is this really works or just adds false positive.

How I can send requests to Login modules from the multiple browser and operating system. Do we have any solution available in opensource softwares?

Apollo Client - How to test a component that uses multiple queries, using HOC components that use compose

I am reading over the docs for testing React/Apollo components Link. If the component has one query, it seems pretty simple to test it.

const mocks = [
  {
    request: {
      query: GET_DOG_QUERY,
      variables: {
        name: 'Buck',
      },
    },
    result: {
      data: {
        dog: { id: '1', name: 'Buck', breed: 'bulldog' },
      },
    },
  },
];

it('renders without error', () => {
  renderer.create(
    <MockedProvider mocks={mocks} addTypename={false}>
      <Dog name="Buck" />
    </MockedProvider>,
  );
});

My component is a little different than the one provided in the documentation.

  1. It doesn't use the useQuery hook, instead I am opting for the HOC approach as outlined here.
  2. I have two queries that my function uses, and so I use two graphql functions and combine them together using compose, as recommended in the docs.

My component is exported like this:

export default compose(withQueryA, withQueryB)(MyComponent);

const withQueryA = graphql(QUERY_A, {
    name: "QueryA",
    options: (props) => ({
        variables: {
            foo: props.foo,
        },
    }),
});

const withQueryB = graphql(QUERY_B, {
    name: "QueryB ",
    options: (props) => ({
        variables: {
            bar: props.bar,
        },
    }),
});

What I'm trying to do is provide the mocks object with multiple objects, each containing a request/result for the corresponding query. I just wanted to know if anyone has been testing their components in a similar way or if there is a better suggestion.

const mocks = [
    {
        request: {
            query: QUERY_A,
            variables: {
                foo: "bar",
            },
        },
        result: {
            data: {
                ...,
            },
        },
    },
    {
        request: {
            query: QUERY_B,
            variables: {
                foo: "bar",
            },
        },
        result: {
            data: {
                ...,
            },
        },
    },
];

I'm also confused about what to put in the result object. When I console.log what is actually returned to the component when making a query in production, it has the data plus error, fetchMore, loading, networkStatus. Do I have to put all those things in the mocks as well?

Latency/network related chaos engineering without the use of traffic control (tc)

I have a Fargate managed container running on Amazon Linux 2 and wanted to run some network latency disruptions on it using the tc command. However, it turns out Fargate does not allow Linux capabilities, so I cannot give it the NET_ADMIN privilege to run kernel commands like tc to add latency/jitter. Wondering if there are other workarounds to this? I'm not too familiar with chaos engineering techniques.

ModuleNotFoundError: No module named 'context'

I get the following error when I try to run a pyVows test:

Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\unittest\loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "C:\Program Files\Python38\lib\unittest\loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "D:\Programmierung\Python-Projekte\JourneyMap\JourneyMap\tests.py", line 2, in <module>
    from django_pyvows.context import DjangoHTTPContext
  File "C:\Users\malo0\AppData\Roaming\Python\Python38\site-packages\django_pyvows\__init__.py", line 11, in <module>
    from context import DjangoContext, DjangoHTTPContext
ModuleNotFoundError: No module named 'context'

I installed pyVows and django-pyvows Am I missing something? I found no helpful documentation

Cypress: How to test Windows window to Save a Data?

I have a test that opens a windows pop-up to save the users personal data. Here I want to click "OK"

I tried to use cy.go('forward') but that does not work for windows pop ups.

Windows Window

how to set up android:authorities for testing?

I have the following source code:

FileProvider.getUriForFile(activity, activity.getPackageName() + ".file", file);

and the following in the Manifest.xml:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="app.domain.app-name.file"
    ...
</provider>

which works correctly when the app is running. However, when running instrumented tests, activity.getPackageName() returns my app's package name with ".test" appended to it causing the following exception:

java.lang.IllegalArgumentException: 
Couldn't find meta-data for provider with authority app.domain.app-name.test.file

What is the correct setup that works in both cases?

Logging test gives always the same result regardless of the channels that are defined in the **config** file in Laravel

My test functions are below. I don't have a channel in my config/logging.php file like asdasd but I do have a channel called slack_General. The problem about the test functions is that it gives me the success all the time for the both channel name. But It should give me the error for the first function as it supposed to because I don't have a channel called asdasd. How can I test the logs are asserted succesfully for the specific channels.

https://github.com/timacdonald/log-fake This is the package I downloaded for the logging testing.

public function testSll() {
    Log::swap(new LogFake);
    Log::channel('asdasd')->alert('message');
    Log::channel('asdasd')->assertLogged('alert');
}

public function testSll() {
    Log::swap(new LogFake);
    Log::channel('slack_General')->alert('message');
    Log::channel('slack_General')->assertLogged('alert');
}

That is one data from my collection.

'slack_General' => [
        'driver' => 'slack',
        'url' => env('NOTIF_GENERAL_SLACK_WEBHOOK_URL'),
        'username' => 'xx server',
        'emoji' => ':boom:',
        'level' => 'debug',
    ],

Run all assertions of a test in Cypress

I've a question regarding test structure. The docs clearly state to write tests with multiple assertions instead of multiple tests with single assertions.

But if I want to test if multiple elements are visible the test will fail if the first element was not visible and I therefore have no clue about the other elements. Is there anything I can do to run all assertions?

it("Page should show two actions", () => {
  cy.visit("users/list");
  cy.get("[data-cy=createUser]")
    .should("be.visible")
    .and("have.text", "Create user");
  cy.get("[data-cy=exportUserData]")
    .should("be.visible")
    .and("have.text", "Export data");
});

(Mainly C#) Naming of different parts in a project

Im currently working in a legacy system which I am trying to implement some kind of structure to.
Since the system is more or less a huge monolit with very little ioc that is one of the things Im trying to solve.
And whith these changes I hope to make the system testable which is very hard in its current state.

Since the code were'nt written with testing in mind Ive realized that I have to break big chunks of the code into services, methods etc. This is where my real question comes in.

When you do extract code, how do you name or classify the new files ? Sure in a perfect world it would be that hard but for example:

Ive got a controller. The controller builds up a view-model and returns it to the view. All of that logic is today in the controller itself.

My first idea was to extract the view-model building into a new file, like a service so I can moq it if needed. That service would be split up into alot of methods that handle each and every part of the view-model.
Then I figured that if I put all of those methods in the same file I would have to make them private since the controller doesnt have a need to know about those methods.
Setting them as private makes the code, once again, hard to test.
My thought then were to break out the logic in those into another file so I can have them all public and by doing that my code would be easy to test.

  • Am I heading in the right direction ?
  • How far should you go with all this?
  • What would I call those new files ?
  • Should they all be services ? Handlers ? Helpers ?
  • Maybe they should mostly be services that call other services?

Sorry for the long question but I felt I had to explain it in as much detail as I could since Im pretty sure there may be alot more than one solution to this.

Thanks

/Jhonny

IllegalStateException sometime occures and some time not

I have a test suite for my application, and some of the time when I'm building my project one the tests raises this error, and sometimes, if I run all the tests again, the error doesn't appear. and if I run this specific test seperatly it always passes.

this is the error:

com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalStateException: Interrupted while loading cache item
  at functional.TestFile.init(TestFile.java:32)
Caused by: java.lang.IllegalStateException: Interrupted while loading cache item
  at functional.TestFile.init(TestFile.java:32)
Caused by: java.lang.InterruptedException
  at functional.TestFile.init(TestFile.java:32)

and this is the line which raises the error:

private File testDirectory;
private Injector injector;

@BeforeClass
public void init() throws Exception {
    testDirectory = Files.createTempDirectory(null).toFile();
    injector = Guice.createInjector(Modules.override(new ProductionModule(new ApplicationSettings().getProperties())).with(new TestModule(testDirectory)));
}

the injector line is line num 32.

anyone knows why it is not stable and why sometime ot pass and sometime not?

Issue starting Appium server

An unknown server-side error occurred while processing the command. Original error: Cannot start the application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: The permission to start activity has been denied.Make sure the activity/package names are correct.

Not able to get react component modal in Enzyme and jest

I am getting error while running the test cases of "TypeError: Cannot read property 'find' of undefined"

it('should include modal and settings explorer', () => {
 wrapper = Enzyme.mount(<FormAccess {...wrapperProps} />);
 **expect(wrapper.find(Modal).at(0).prop('isOpen')).toBe(true);**
});

The Code looks like

let wrapper: CdsFormAccessWrapper;
let wrapperProps: CDSFormAccessProps;

 beforeEach(() => {
wrapperProps = {
  hidden: true,
  onClose: jest.fn(),
  formContext: { formId: '', formType: FormType.Main },
  entityDisplayName: '',
  entityName: ''
};
});

Is it possible to rework this function to ignore screenshot dimensions? If yes how?

So I am comparing two environments based on their visual appearance. I run this test on multiple "products".

Lets say I have product with ID 5500 that is on DEV and DEV2 environment. I need the best solution to compare pages between DEV and DEV2 environment based on screenshots of whole page. Right now I'm using AShot which is not working so well because it will throw exception every time the coordinates of getRGB() are not in bound which I think I cannot influence. (If you have any tips how to highlight size differences also, that would really help also)

I have also a function that calculates a percentage difference between mentioned screenshots. Right now it requires both screenshots to have same size... (f.e. Screenshot 1: 1024x1024, Screenshot 2: 1024x1024). That would be the ideal case, but the real cases are that Screenshot 1: 1024x768 and Screenshot 2: 1000x750

Right now this function calculates the percentage difference based on RGB Model. It would be nice if the size difference was taken into account also. Is it possible to include size difference to this function? Function is written like this. (Found here on Stack OverFlow.)

 public double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
    int width = img1.getWidth();
    int height = img1.getHeight();
    int width2 = img2.getWidth();
    int height2 = img2.getHeight();


    long diff = 0;
    System.out.println("THIS IS DIFF BEFORE FOR LOOP: " + diff);
    try {
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
        System.out.println("ERROR: Screenshot dimensions are not same, thus value may be inaccurate");
    }
    System.out.println("THIS IS DIFF AFTER FOR LOOP: " + diff);

    long maxDiff = 3L * 255 * width * height;
    return 100.0 * diff / maxDiff;
}

Difference between Autosar Conformance testing and Acceptance testing

I am very new to Autosar and looking at what needs to be done to test a SUT/DUT (System/Device under test) confirm to Autosar specifications I read the Autosar conformance test specification (Part 1 to 4) and they have a separate link on website that talks of Acceptance test In fact there is no direct link on portal for conformance testing. Only doing a Google search lead to those documents hosted by Autosar.org. So i presume conformance testing is also relevant to device testers

Are Autosar Conformance testing and Acceptance the same ? When is Conformance test done and when Acceptance test are done ?

Thanks

What does the "skipUncaughtErrors" flag mean by server?

In the TestCafe documentation the skipUncaughtErrors flag mentions: uncaught error or unhandled promise rejection occurs on the server during test execution.

What is meant by server here?

I found this flag after we started getting an issue quite randomly, with very little to debug from:

    1) - Error in fixture.beforeEach hook -
       Unhandled promise rejection:
 
       Error: [eval("")] Not JSON response
       at exports.newError

Figured it was worth a try to set skipUncaughtErrors: true and we haven't seen that issue since. Nonetheless, the team is worried about using features we don't understand. :)

lundi 29 juin 2020

Reactjs tests (react testing library)

Can anyone help with how I can test the component below? I am using the testing-library / react library and am having difficulties.



export default function BodyCardConfirmacaoSeguranca({ email, celular }) {
    const [selectedCard, setSelectedCard] = useState(null);

    const handleSelectCard = (value) => {
        if (value === selectedCard) {
            setSelectedCard(null);
        } else {
            setSelectedCard(value);
        }
    };

    return (
        <>
            <CardEnvioCod
                data-testid="email"
                tipoEnvio="email"
                data={email}
                handleSelectCard={() => handleSelectCard('email')}
                selectedCard={selectedCard}
            />

            <CardEnvioCod
                data-testid="sms"
                tipoEnvio="sms"
                data={telefone(celular)}
                handleSelectCard={() => handleSelectCard('sms')}
                selectedCard={selectedCard}
            />
        </>
    );
}

I'm trying something like this:


    it('', () => {
        const { findByTestId } = Render(
            <ThemeProvider theme={AppTheme}>
                <BodyCardConfirmacaoSeguranca />
            </ThemeProvider>,
        );

        const email = findByTestId('email');
        const sms = findByTestId('sms');

        fireEvent.change(email, { selectedCard: 'email' });
        fireEvent.change(sms, { selectedCard: 'sms' });
    });

I need to test the handleSelectCard function and its call on the components

how to test if parameter is undefined and defined react jest testing

With Jest testing I was trying to test if the parameters are undefined or defined. So it can test if the data-testid is available in the DOM. So therefore I created one mockApi that contains objects and one mockApi that contains nothing in order to test both scenarios, but cannot figure out how to do that so this test will incapsulate all the needs I want.

export const Result = ({ data, city }) => {
    if(data === undefined || city === undefined) {
        return (
            <div data-testid="empty-array"></div>
        )
    } else {
        return (
            <div data-testid="weather-array">
                <div className="city-name">{city}</div>
                <div className="weather-info">
                    <div className="temperature">{data.temp}</div>
                    <div>{data.weather[0].main}</div>
                    <div>{data.weather[0].description}</div>
                    <img src={`http://openweathermap.org/img/w/${data.weather[0].icon}.png`} alt={city + ' weather status'}/>
                </div>
            </div>
        )
    }
}

// index.test.js

import React from "react"
import { render } from "@testing-library/react";
import { Result } from './index.js';
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";

import { weatherData } from '../../mock/mockAPI';
import { 
    emptyWeatherApi, 
    emptyCityApi 
} from '../../mock/emptyApi';

test("It should check if there is no data in Result component", () => {
    render(
        <Provider store={store}>
            <Result city={emptyCityApi} />
        </Provider>
    )
    const checkWeatherData = screen.getAllByTestId("empty-array");
    expect(checkWeatherData).toHaveLength(1);
});

test("It should check if there is data in Result component", () => {
    render(
        <Provider store={store}>
            <Result 
                data={weatherData} 
            />
        </Provider>
    )
    const checkWeatherData = screen.getByTestId("weather-array");
    console.log(checkWeatherData);
    // expect(checkWeatherData).toHaveLength(1);
});

check of unit test to service in angular

I have this code:

public getProjects() {
    this.listProjects.getProjects(this.tenant).subscribe((res: any) => {
      this.eventService.get(EventKeys.ProjectSelected).subscribe((dataFilter: any) => {
        const results = _.filter(res, item => {
          const active = item.projectStatus2020 === dataFilter[0];
          const inactive = item.projectStatus2020 === dataFilter[1];
          const terminated = item.projectStatus2020 === dataFilter[2];
          return active || inactive || terminated;
        });
        const check = _.isEmpty(results);
        Iif (check === false) {
          this.items = results;
        } else {
          this.items = res;
        }
      });
    });
  }

I use this code in unit tests:

beforeEach(async(() => {
    projectServiceSpy = jasmine.createSpyObj('ProjectsService', ['getProjects']);
    projectServiceSpy.getProjects.and.returnValue(of({}));

And I don't know How to make it to check this section.

enter image description here

Someone idea?

Writing a unit test with golang

So basically, I am trying to mock a unit test on this function right here.

func searchAuthMethod(sep []oktalib.OktaUserAuthnFactor, s string) bool {
    for _, i := range sep {
         if i.FactorType == s {
             return true
         }
     }
     return false
 }

[]oktalib.OktaUserAuthnFactor being an array of struct from a package name oktalib.

type OktaUserAuthnFactor struct {
    Id         string                      `json:"id"`
    FactorType string                      `json:"factorType"`
    Provider   string                      `json:"provider"`
    Embedded   OktaUserAuthnFactorEmbedded `json:"_embedded"`
}

And below is my unit testing code trying to mockwrite the function.

 type okta struct {
      factor string
  }
 
 type authTest struct {
      str string
      Objects []okta
  }
  
  var authTests = []authTest {
      authTest {
       str: "hi",
       Objects: []okta {
              okta {
                 factor:"hi",
              },
          },
      },
  }
  
  func TestSearchAuthMethod (t *testing.T) {
  
         for _, i := range authTests {
             mockData, err := searchAuthMethod(i.Objects.okta , i.str)
             if err != nil {
                 return err
             }  
             if i.Objects.factor != i.str {
                 t.Error("Values do not match")
             }  
        }   
  }

And throws back these errors when typed go test -v in the terminal

# oktassume [oktassume.test]
./writecreds_test.go:48:26: assignment mismatch: 2 variables but searchAuthMethod returns 1 values
./writecreds_test.go:48:55: i.Objects.okta undefined (type []okta has no field or method okta)
./writecreds_test.go:50:16: too many arguments to return
./writecreds_test.go:52:24: i.Objects.factor undefined (type []okta has no field or method factor)

How can I write my test function to get the test to pass, I have been trying to make this work for 2 weeks, will really appreciate it if anyone can help ^.^

Execution of JAVA BDD automation framework from .net based developer repository

Would appreciate your response.

Is there a possiblity to execute JAVA BDD maven framework in different bitbucket repository of developers code which is in .net?

Your inputs or suggestions are very much helpful.

More Details:

We as automation team developed Maven JAVA BDD framework in our repository (lets say repo1), this is working fine independently. However, developers need our automation framework under developers repository (lets say repo2) which is in other technology which is .net. Purpose of having this integration is whenever there is any change in dev code, automation should trigger corresponding module.

Scraping websites buttons functionality for testing

I have to test a website with puppeteer and jest. While I managed to scrape some basic data via document.querySelector, I am struggling to find out how to scrape the functionality of the buttons. For example, there is a blank white field to insert notes. How and with what do I scrape the functionality?

The testing with jest is not the problem, but to get the data turns out to be a real mess.

How do I tell Jenkins to run a Python Flask application, then Selenium tests, then close the Flask application?

I have a Flask application that spins up my web application to a specific port (e.g., 8080). It launches by running python run.py. I also have a Python file that runs Selenium end-to-end tests for the web app.

This is part of a GitHub repo, and I have it hooked up so that whenever I push/commit to the GitHub repo, it initiates a Jenkins test. Jenkins is using my machine as the agent to run the commands. I have a series of commands in a Pipeline on Jenkins to execute.

Ideally, the order of commands should be:

  1. Spin up the Flask web application
  2. Run the Selenium tests
  3. Terminate the Flask web application

Running Flask and Selenium in parallel in a Jenkins Pipeline

Now, my issue is this: I can use Jenkins to clone the repo to the local workspace on my computer (the agent), and then run the Python command to spin up my web app. I can use Jenkins to run a task in parallel to do the Selenium tests on the port used by the web app.

BUT I cannot figure out how to end the Flask web app once the Selenium tests are done. If I don't end the run.py execution, it is stuck on an infinite loop, endlessly serving up the application to the port. I can have Jenkins automatically abort after some specified amount of time, but that flags the entire process as a failure.

Does anyone have a good idea of how to end the Flask hosting process once the Selenium tests are done? Or, if I am doing this in a block-headed way (I admit I am speaking out of copious amounts of ignorance and inexperience), is there a better way I should be handling this?

JEST - How to test function inside another function

I'm trying to test with Jest, but just check the entire method and not the functions inside it, I've tried it in many ways, nothing else works, how could I do to test the "compare" function from within the scope of the method?

Would I have to pass the compare as a parameter in the store method like that? "async store (req, res, compare)" ??

session.service.spec.ts

describe('SessionService', () => {
  let service: SessionService;
  let repo: Repository<User> 

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [      
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: '7d'}
        })
      ],
      providers: [
        JwtStrategy,
        SessionService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            findOne: jest.fn()
          }
        }
      ],
    }).compile();

    service = module.get<SessionService>(SessionService);
    repo = module.get<Repository<User>>(getRepositoryToken(User))
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('Session', () => {    
    it('check if user has an account', async () => {
      const req = getMockReq({
        body: {
          email: 'email@gmail.com',
          password: '123456789'
        }
      })
      const { res } = getMockRes()

      await service.store(req, res)  

      const password = compare('123456789', req.body.password)

      expect(password).toBeTruthy()   
    })
    
    
  })
});

session.service.ts

 @Injectable()
export class SessionService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService
  ) {}


  async store(req: Request, res: Response): Promise<Response> {
    const { email, password } = req.body

    const user = await this.usersRepository.findOne({ where: { email }})    
    
    if(!user){
      return res.status(400).json({ error: 'Email inválido'})
    }

    const comparePassword = await compare(password, user.password)

    if(!comparePassword) {
      return res.status(400).json({ error: 'A senha está incorreta'})
    }    

    const payload = { 
      sub: user.id
    }

    return res.json({
      id: user.id,
      email,
      password,
      token: this.jwtService.sign(payload)
    })
  }
}

coverage: COVERAGE TEST IMAGE

Relative imports in python 3.8 failing with ImportError: attempted relative import with no known parent package

I am just getting started with Test Driven Development with python and I am having some problems while importing the required files, relative to the current directory. Here's my directory structure:

project/
    api/
    utils/
        __init__.py
        database/
            dbms.py
            groups.py
            __init__.py
       //etc etc
    tests/
        db_test.py

From the db_test.py I want to import the dbms.py file. I tried using relative import like this:

from ..utils.database import dbms

But it fails with this error message:

Traceback (most recent call last):
  File "d:\Scola\tests\db_test.py", line 2, in <module>
    from ..utils.database import dbms
ImportError: attempted relative import with no known parent package

I went through this answer here and added empty __init__.py files to the root directory of the project as well as the tests directory. But the same error is still there. And then I tried using this, but then I got the error that 'utils module not found'. Any ideas?

Thanks.

How to run SpecFlow tests in parallel

I try to run SpecFlow tests with NUnit test runner in parallel. I am using:

  • C# / .Net Core 3.1
  • NUnit as testrunner
  • Specflow

I have added this line on top of a file (as describe here: https://specflow.org/documentation/parallel-execution/):

[assembly: Parallelizable(ParallelScope.All)]

Tests start to execute in parallel but immediately throw an error:

Message: 
    System.ArgumentException : An item with the same key has already been added. Key: NUnitTestProject1.SpecFlowFeature1Steps
Stack Trace: 
    Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
    Dictionary`2.Add(TKey key, TValue value)
    TypeRegistration.Resolve(ObjectContainer container, RegistrationKey keyToResolve, ResolutionList resolutionPath)
    ObjectContainer.ResolveObject(RegistrationKey keyToResolve, ResolutionList resolutionPath)
    ObjectContainer.Resolve(Type typeToResolve, ResolutionList resolutionPath, String name)
    ObjectContainer.Resolve(Type typeToResolve, String name)
    TestObjectResolver.ResolveBindingInstance(Type bindingType, IObjectContainer container)
    lambda_method(Closure , IContextManager , Int32 )
    BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
    TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments)
    TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance)
    TestExecutionEngine.OnAfterLastStep()
    TestRunner.CollectScenarioErrors()
    SpecFlowFeature1Feature.ScenarioCleanup()
    SpecFlowFeature1Feature.AddTwoNumbers() line 8

I tried without SpecFlow (just raw NUnit) and it worked. I also tried with MSTest test runner but got the same exception.

I have made a very tiny example project which you can clone here: https://github.com/davidguidali/specflowerror

Any help would be appreciated. :)

How do I integration test a PUT endpoint?

I'm currently working on a Spring Boot CRUD RESTful API with an User entity that consists of two parameters : name and id. Its endpoints are :

  • POST REQUEST IN /users - Create an user
  • GET REQUEST IN /users/{id} - List a specific user by its id
  • GET REQUEST IN /users - List all users
  • PUT REQUEST IN /users/{id} - Update a specific user by its id
  • DELETE REQUEST IN /users/{id} - Delete a specific user by its id

Each endpoint is built with a controller and a service to implement its logic.

I've already wrote unit tests for my controllers and services, now i'm trying to build integration tests to assert that my endpoints work properly as a group of components.

No mocking involved, all this will be done by using the TestRestTemplate and asserting that every operation was executed correctly and every response checked with its expected value.

The following are the tests I've already built :

@SpringBootTest(classes = UsersApiApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();
    HttpHeaders headers = new HttpHeaders();

    private void instantiateNewUser() {
        User userNumberFour = new User();
        userNumberFour.setName("Four");
        userNumberFour.setId(4L);

        ResponseEntity<User> responseEntity = restTemplate
                .postForEntity(createURLWithPort("/users"), userNumberFour, User.class);
    }

    @Test
    public void createNewUserTest() {
        User testUser = new User();
        testUser.setName("Test User");
        testUser.setId(5L);

        ResponseEntity<User> responseEntity = restTemplate
                .postForEntity(createURLWithPort("/users"), testUser, User.class);

        assertEquals(201, responseEntity.getStatusCodeValue());
        assertEquals(responseEntity.getBody(), testUser);
    }


    @Test
    public void listSpecificUserTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.GET, httpEntity, String.class);

        String expectedResponseBody = "{id:4,name:Four}";

        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
    }

    @Test
    public void listAllUsersTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users"),
                HttpMethod.GET, httpEntity, String.class);

        //All instantiated users
        ArrayList<String> expectedResponseBody = new ArrayList<>(Collections.emptyList());
        expectedResponseBody.add("{id:1,name:Neo}");
        expectedResponseBody.add("{id:2,name:Owt}");
        expectedResponseBody.add("{id:3,name:Three}");
        expectedResponseBody.add("{id:4,name:Four}");

        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(String.valueOf(expectedResponseBody), responseEntity.getBody(), false);
    }

    @Test
    public void deleteSpecificUserTest() throws JSONException {

        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.DELETE, httpEntity, String.class);

        assertEquals(204, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(null, responseEntity.getBody(), false);
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }
}

As you can see, it's missing the PUT request method test, which is the update endpoint. To implement its logic, i need to send a message body with the content that will override the old users characteristics, but how?

This is what i made so far :

    @Test
    public void updateSpecificUserTest() throws JSONException {
    
        instantiateNewUser();
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
    
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                createURLWithPort("/users/4/"),
                HttpMethod.PUT, httpEntity, String.class);

        String expectedResponseBody = "{id:4,name:Four Updated}";
    
        assertEquals(200, responseEntity.getStatusCodeValue());
        JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
    }
    

How to change stub for RSpec

I have a stub that returns a 422 for this test. This is in order to generate a modal that asks the user if they are sure they want to continue. When they click "yes, continue" I'd like the stub to return 200 and for the test to take the user back to the main page. How could I do that? When I try putting in the stub I want, it seems the stub that was written last is the one that gets used. Seems like I cannot do both. It seems that when the save-refund-confirmation-button gets clicked, the 422 stub is called a second time. I want the 200 stub to be used.

scenario 'successfully saves refund when user clicks yes continue on similar refund', js: true do
      save_payer_refund_success_request = stub_request(:post, /remittances/).to_return(status: 200)
      save_payer_refund_fail_request = stub_request(:post, /remittances/).to_return(status:422, body: {error: "SIMILAR_REMITTANCE"}.to_json)
      visit record_refund_check_by_payer_remittances_path

      #Test fils out the form here

      page.find_by_id('refund_record').click
      wait_for_ajax
      expect(save_payer_refund_fail_request).to have_been_made # <--- This works
      expect(page).to have_content 'A refund from this payer with this number with the amount of $' + @refundTotalAmount + ' and date of ' + @EFTCheckDate + ' already exists in Value-Based Reimbursement. Are you sure you want to record this refund?'
      page.find_by_id('save-refund-confirmation-button').click
      wait_for_ajax
      expect(save_payer_refund_success_request).to have_been_made # <--- Fails here
      expect(page).to have_content 'Refund check ' + @checkNumber + ' to payer has been saved.'

Expecting 1, actual 0.9999999999999996 in NodeJS, Chai [duplicate]

I have a test with NodeJS / Chai:

it('#getSum', () => {
        const a = 6.77
        const b = 3.77
        const c = 1
        const d = 1
        const result = a - b - c - d
        const expected = 1
        expect(result).to.equal(expected)

    });

that fails telling me :

AssertionError: expected 0.9999999999999996 to equal 1
Expected :1
Actual   :0.9999999999999996

Why is it happening ? When I use my fingers, result is 1.

SImple and universal test case for sorting algorithm illutrations

I'm not very good at memorizing the sorting algorithm codes. So I usually just draft the process before I write them down. Sometimes the test case isn't good for drafting for they sometimes involve too many steps or just doesn't cover corner cases.

What are the good test cases for drafting each sorting algorithms? It would be nice if there's one test case that can illutrate all algorithms easily.

Automated testing via Burp Suite

I use Burp Suite to testing my application, but every request send manually and it isn't comfortable. Can I automate my test cases some way? Is it possible to use java scripts in Burp Suite Repeater (or via another extension)? For example script send first request, parse response, then send second one which depends on first. Any other language except java ?

How can I test CSV uploader API that developed by Flask (without mock)?

I try to test my CSV uploader POST API endpoint that implemented with Flask, but I can't simulate the same behavior that I do when sending CSV file to API by curl.

Simple API endpoint by Flask:

@app.route("/uploader", methods=["POST"])
def csv_uploader():
    csv_file = next(iter(request.files.values()))  
    stream = io.StringIO(csv_file.stream.read().decode("utf-8"), newline=None)
    data = []

    for data_row in csv.DictReader(stream):
        data.append(data_row)
    
    return {"message": f"({len(data)}) data row were uploaded!"}

Curl command that I use:

curl -F 'file=@./file.csv' 127.0.0.1:5000/uploader

Additional information: The requests.files ( that give us the flask ) is ImmutableMultiDict([('f', <FileStorage: 'file.csv' ('application/octet-stream')>)])

My attempt of test:

def test_endpoint_works_as_expected(self, client):
test_csv_file = FileStorage(
    stream=BytesIO("id,first_name\n1,jakab".encode("utf-8")).read(),
    filename="test_financial_file.csv",
)

resp = client.post(
    "/uploader", 
    data={"file": test_financial_file},
    headers={'Content-Type': 'application/octet-stream'}
)

assert resp.status_code == 200
assert resp.json == {"message": "(1) data row were uploaded!"}

( where the client is a Flask test-client fixture and FileStorage is a data structure that werkzeug gives us )

The problem is that even though I send the request to my API, nothing arrives in the files of Flask's request object.

How can I test my uploader API and simulate the behavior of file upload? ( without mocking )

Trying to Write a Basic Test for QNX Functions MsgReceive(), MsgSend(), and MsgReply()

I am attempting to write a simple test case exercising MsgReceive(), MsgSend(), and MsgReply() but I feel like I am fundamentally misunderstanding how these functions work. Here is my attempt:

printf("Testing MsgReceive()...\n");
printf("Receives message and place it into a buffer.\n");
chid = ChannelCreate(_NTO_CHF_SENDER_LEN);
if(chid == -1){
    printf("ChannelCreate FAILED!");
}
coid = ConnectAttach(0, 0, chid, _NTO_SIDE_CHANNEL, 0);
pid = fork();
if(pid == -1){
    return;
}
            
if(pid == 0){
    msgSend = MsgSend(coid, writemsg, 13, buffer, 13);
    if(msgSend == -1){
        printf("Child FAILED: %d\n", msgSend);
    }
}
else{
    msgRec = MsgReceive(chid, buffer, 13, NULL);
    printf("Sent Message: %s\n", buffer);
    if(msgRec == -1){
        printf("Parent FAILED: %d\n", msgRec);
    }
}
if(pid == 0){
    if(ChannelDestroy(chid) == -1){
        printf("ChannelDestroy() failed.\n");
    }
}

I create a channel and then connect the process to the channel. I fork and have the child send the message and the parent receive it. But I can never get the child to send. It always fails.

Can I use a Class/Methods to run through an array of WP Customizer settings to register them?

I have an array of WordPress Theme Customizer settings that I want to register and output to the Theme Customizer, and they all register fine, and they all work perfectly.

This is where my problem is, $wp_customize->add_setting won't seem to pass the Theme Checker plugins' checks, it doesn't seem to like using a variable in place of an ID for the setting, even though the variable contains the setting name. When I'm looping through the array I have, everything works fine in the Theme Customizer (all settings, control, sections and panels that I'm registering are there, and working and updating and even refreshes in the preview window), but in the Theme Checker plugin, I get this error repeated 100's of times when the tests are run:

Warning: preg_match(): No ending delimiter '$' found in I:\xampp\htdocs\basic\wp-content\plugins\theme-check\checkbase.php on line 110

The line that is causing the problem is the one that registers the settings:

$wp_customize->add_setting( $set_name, $items['setting'] );

The "ending delimiter" that it's referring to is for the $set_name, but I can't find a way of passing this without these errors appearing, even though the functionality of the Theme is working perfectly. Is there some sort of way that I can make the add_setting() method take my variable which holds my setting name?

The tests do complete, and it shows this related to the problem:

REQUIRED: Found a Customiser setting called $set_name in theme-customizer.php that did not have a sanitisation callback function. Every call to the add_setting() method needs to have a sanitisation callback function passed.

It seems to be passing the literal variable name, rather than it's contents, however, the Customizer functions as expected, and registers/saves the settings in the correct names that I've given in the array of settings.

Can anyone help please?

Convolutional neural networks: prevent cheating in the test phase

I am building a convolutional neural network for image classification. Images are stored in two distinct folders:

  1. training images (8000 files)
  2. test images (2000 files)

Clearly, I need a training set, a validation set and a test set. The first solution is splitting the images in the first folder into a training group and a validation group while using the images in the second folder for testing purposes:

training_datagen     = ImageDataGenerator(rescale = 1./255, validation_split =  0.2)
test_datagen         = ImageDataGenerator(rescale = 1./255)
train_generator      = train_datagen.flow_from_directory(training_path,target_size = (150,150), batch_size = 20, subset = "training", class_mode = "binary") 
validation_generator = train_datagen.flow_from_directory(training_path,target_size = (150,150), batch_size = 20, subset = "validation", class_mode = "binary") 
test_generator       = test_datagen.flow_from_directory(test_path,target_size = (150,150), batch_size = 20, class_mode = "binary") 

This approach becomes problematic when I want to augment my training images because operations like stretching, zooming etc. will be also applied to my validation set. Indeed, one could simply split the first folder into two separate folders (e.g. 6000 images for training, 2000 images for validation) and use ImageDataGenerator() for each folder without the "validation_split" parameter. However, I am not allowed to modify the folder structure, that is, I cannot reorganize the images. My idea is to split the 2000 images in the second folder into a validation set and a test set:

train_datagen   = ImageDataGenerator(rescale            = 1./255,
                                     rotation_range     = rotation_range,
                                     width_shift_range  = width_shift_range,
                                     height_shift_range = height_shift_range,
                                     shear_range        = shear_range,
                                     brightness_range   = brightness_range,
                                     zoom_range         = zoom_range,
                                     horizontal_flip    = horizontal_flip,
                                     fill_mode          = fill_mode)

test_datagen         = ImageDataGenerator(rescale = 1./255, validation_split =  0.5)
train_generator      = train_datagen.flow_from_directory(training_path,target_size = (150,150), batch_size = 20, subset = "training", class_mode = "binary") 
validation_generator = test_datagen.flow_from_directory(test_path,target_size = (150,150), batch_size = 20, subset = "test", class_mode = "binary") 
test_generator       = test_datagen.flow_from_directory(test_path,target_size = (150,150), batch_size = 20, subset = "validation",class_mode = "binary") 

and use the first 1000 images for validation and the remaining 1000 images for testing. Am I cheating in the test phase by doing this?

Thank you!

Mac Sandboxing and quick testing

I develop an app for macOS. Is it possible to quickly enable Sandboxing for my app for testing? Currently I have to sign the app and send it for notarization - it takes a lot of time.

Maybe some command in Terminal? I don't use XCode, only XCode Command Line Tools and Lazarus/Freepascal.

Why cant Python package hypothesis_regex find attribute 'defines_strategy' in hypothesis.strategies?

I am using hypothesis-5.18.3 and hypothesis-regex-0.3.1 in my python test to generate strings.

My code looks like this:

from hypothesis import given
from hypothesis_regex import regex

@given(regex(r"^[0-9]$"))
def test_functions_with_different_params(num):
...

The second line fails to import hypothesis_regex

File "...Python\Python38\lib\site-packages\hypothesis_regex.py", line 143, in <module>
@hs.defines_strategy
AttributeError: module 'hypothesis.strategies' has no attribute 'defines_strategy'

Is there a version mismatch between hypothesis and hypothesis_regex? I couldn't find any details in the documentation. I tried uninstalling both packages and installed the dependency via hypothesis_regex. Still the same error. Did anyone face this issue?

how to write unit testing in angular for DOM events with set Interval

inactivityTime = () => {
        this.events.forEach(event => {
        document[event] = () => {
            this.idleTime = false;
        };
    });
    const timeout = () => {
        if (this.idleTime) {
            console.log('Call API to kill session');
        }
        this.idleTime = true;
    };
    setInterval(timeout, 90000);

i have to write unit test for above function where set Timeout is called for inactivity period how to do that.

inactivityTime = () => {
            this.events.forEach(event => {
            document[event] = () => {
                this.idleTime = false;
            };
        });
        const timeout = () => {
            if (this.idleTime) {
                console.log('Call API to kill session');
            }
            this.idleTime = true;
        };
        setInterval(timeout, 90000);
i have to write unit test for above function where set Timeout is called for inactivity period how to do that.

dimanche 28 juin 2020

Black box test cases for function which finds intersection of two planes

I'm trying to solve the following task in preperation for Software Engineering exam, but i am stuck.

We want to evaluate a function which finds the intersection of two planes. Input parameter is two vectors, each composed of 3 noncollinear points that define a plane. As a result, the function returns a vector of cross-section, which consists of a minimum number of points to uniquely define the cross-section. In case of an error, the function returns an exception. A point is always represented with integer values for x,y and z coordinate. Suggest test cases to verify correct operation of the function and explain them.

I know I'm supposed to use black box testing and use boundary analysis or equivalence partitions, but i really don't know how to deal with this task other than that. Usually the examples given for these testings are much simpler than this.

How do I test if action is being called in redux

enter image description hereCurrently I want to test if this action is being called, and the reason is because this action only empty the array. So in order to test this action function I want to check if this is being called once. So I was thinking of using toHaveBeenCalled(1). Not sure if this is the right one to use that in here.

import * as actions from '../actions/index';
import { types } from '../actions/index';
import { fixedApi } from '../mock/mockAPI';

describe('actions', () => {
    it('should create an action and check if action named clearArray is being called', () => {
        
        const expectedAction = {
            type: types.CLEAR_ARRAY
        }
        expect(actions.clearArray()).toHaveBeenCalled()
        
    });
})

WebTestClient configured with wrong port

I have written integration tests in Spock. Configured Spring boot context to random port. Documantation claims that then sprig should inject me properly configured WebTestClient instance however when i'm trying to make a call by those "autoconfigured instance I have error given below:

Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:8080
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Request to POST http://localhost:8080/sign-up [DefaultWebClient]

Here is my code: BaseIntegrationTest

@SpringBootTest(webEnvironment = RANDOM_PORT, classes= QuizItApplication.class)
@ContextConfiguration
@EnableConfigurationProperties
abstract class BaseIntegrationSpec extends Specification {

Class using WebTestClient:

@Component
class WebTestClientWrapper {

    @Autowired
    private WebTestClient webTestClient

    @Autowired
    private ObjectMapper objectMapper

How to solve problem (testing with mutants in java)?

I have to implement algorithm for finding mutants in code. From input file, i have to reading some code for example;

public static void main(String[] args){
  int s = 0; 
  for (int i = 0; i < x.length; i++) { 
    s = s + x[i]; 
  } 
  System.out.println(s);
}

I have to create mutants using two rules: replacement of arithmetic operations and replacement of variables of the same type. For example: in the code above we have line with code s=s+x[i]; The + sign should be replaced by the - sign, so the first mutant would be;

public static void main(String[] args){
  int s = 0; 
  for (int i = 0; i < x.length; i++) { 
    s = s - x[i]; 
  } 
  System.out.println(s);
}

Second mutant would be;

public static void main(String[] args){
  int s = 0; 
  for (int i = 0; i < x.length; i++) { 
    s = s / x[i]; 
  } 
  System.out.println(s);
}

And so for each sign. Do the same with replacement of variables of the same type.

Mutants must be written to the output file.

I need a solution in Java. Please help?

Testcafe in azure devops with specific URL

I am trying to e2e-testcafe in my azure devops uisng IAAC(Infra as a code) for java-script code. So i have different stages build, test and deploy to different environments. After deploying to test environment (Storage account) I need to e2e in that deployed code. So i am using below steps for that jobs: my azure-pipeline.yml has below

- job: e2e_tests
  pool:
    vmImage: 'Ubuntu 16.04'
  steps:
  - task: NodeTool@0
    inputs:
      # Replace '10.14' with the latest Node.js LTS version
      versionSpec: '10.14'
    displayName: 'Install Node.js'
  - script: npm install
    displayName: 'Install TestCafe'
  - script: npm test
    displayName: 'Run TestCafe Tests'
  - task: PublishTestResults@2
    inputs:
      testResultsFiles: '**/report.xml'
      testResultsFormat: 'JUnit'
---------------------------------------------------
my test.js: 

import { Selector } from 'testcafe';
const articleHeader = Selector('#article-header');
const header = Selector('h1');
fixture `Getting Started`
    .page `localhost:8080`
          
test('My first test', async t => {
    await t
        .expect(header.innerText).eql('Welcome to Your new App');
});

But here its running the tests from my test.js which is part of application and all the tests are running in localserver of the agent which is being used by azure devops for me here its windows server. But now i want to pass the URI to npm test and while it goes to my application its again picking up localhost:8080 and executing in local. So can some one help me running e2e test in the url which i pass which indeed will be the url of storageaccount? like my command should be in azurepipelines.yaml

npm run test --URL

and in my test.js it should pick up above URL i passed in Yaml while running in the pipeline.

How would I create a function to test my Tree before an algorithm runs?

For the following code below, I am looking for some sort of way to add testing data. How would I go about creating a function to check that the Huffman Tree is checked and confirmed as working before the algorithm executes? Thanks in advance for any help!

#Huffman Coding Algorithm

string = input("Please Enter a Phrase Consister of Letters and or Spaces: " + "\n")
print("")


#Creating the tree nodes
class HuffmanTree(object):
    
    def __init__(self, left = None, right = None):
        self.left = left
        self.right = right
    
    def child(self):
        return(self.left, self.right)
    
    def nodes(self):
        return (self.left, self.right)

    def __str__(self):
        return "%s_%s" % (self.left, self.right)

#Main function for Huffman coding. 
def Huffman_Compression(node, left = True, binString = ""):
    if type(node) is str:
        return {node: binString}
    (left, right) = node.child()
    dt = dict()
    dt.update(Huffman_Compression(left, True, binString + "0"))
    dt.update(Huffman_Compression(right, False, binString + "1"))
    return dt

#Calculating the frequency of characters 
freq = {}
for c in string:
    if c in freq:
        freq[c] += 1
    else:
        freq[c] = 1
        
freq = sorted(freq.items(), key = lambda x: x[1], reverse = True)

nodes = freq

while len(nodes) > 1:
    (key1, c1) = nodes[-1]
    (key2, c2) = nodes[-2]
    nodes = nodes[:-2]
    node = HuffmanTree(key1, key2)
    nodes.append((node, c1 + c2))
    
    nodes = sorted(nodes, key = lambda x: x[1], reverse = True)
    
huffmancoding = Huffman_Compression(nodes[0][0])

print(" Characters | Huffman Output ")
print("-------------------------------")

for (char, frequency) in freq:
    print(" %-4r |%12s" % (char, huffmancoding[char]))

How to manually create a new transaction for each spawned thread in Springboot @DataJpaTest?

First of all, please be aware that this question is closely related to this other one. I have a springboot application with a @Transactional(propagation=Propagation.REQUIRES_NEW) CreateUser service. Then, I have @DataJpaTest integration test in which I intend to test the system's behavior under a highly concurrent scenario. However, the test is not passing and the problem seems to be related with the fact that spawned threads (I'm using a FixedThreadPool with 10 threads) cannot see each other's DB modifications. As far as I know, every @DataJpaTest creates its own transaction, and I tried to create a new transaction for each concurrent executed task without any success so far...

Could someone please help with this?

SpringBoot Application:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    // ...

    @Bean
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public CreateUser createUserService(@Qualifier("JpaUserRepository") UserRepository userRepository,
                                        @Qualifier("JpaReferralRepository") ReferralRepository referralRepository,
                                        RegisterReferredUser registerReferredUser) {
        return new CreateUser(userRepository, referralRepository, registerReferredUser);
    }
}

Test:

@DataJpaTest(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Repository.class))
public class JpaTest {

    // ...
        
    @Test
    void createUser_shouldWorksProperlyUnderConcurrentExecution() throws InterruptedException {

        EntityManager entityManager = this.entityManager.getEntityManager();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        EmailAddress referrerUserEmail = EmailAddress.of("john.doe@sample.com");
        User referrerUser = createUser.execute(new CreateUserCommand(referrerUserEmail.getValue(), null));
        String referralCode = referrerUser.getReferralCode().getValue();
        entityManager.getTransaction().commit();
        int maxIterations = 1000;

        for (int i = 0; i < maxIterations; i++) {
            int emailSeed = i;
            executor.submit(() -> {
                // I'd like to start a new transaction for each concurrent executed task here
                createUser.execute(new CreateUserCommand(anEmailAddress(emailSeed), referralCode));
            });
        }

        executor.shutdown();
        if (!executor.awaitTermination(20, TimeUnit.SECONDS)) {
            fail("Executor didn't finish in time");
        }

        assertThat(this.entityManager.getEntityManager().createQuery("from JpaUser").getResultList().size())
                .isEqualTo(maxIterations + 1);
        referrerUser = getUser.execute(referrerUser.getId());

        assertThat(referrerUser.getRewardsCounter()).isEqualTo(RewardsCounter.ZERO);
        assertThat(referrerUser.getCredit()).isEqualTo(Credit.of(1000));
    }

Testing LoginBloc with bloc_test library and debounce time

I'm testing my Flutter application and in particular the BLoC responsible of the logic behind the login form. I used the same code that can be found on the flutter_bloc library documentation examples (https://bloclibrary.dev/#/flutterfirebaselogintutorial).

This is the code for the LoginState:

part of 'login_bloc.dart';

/// Here is a list of the possible [LoginState] in which the [LoginForm] can be:
/// [empty]: initial state of the [LoginForm]
/// [loading]: state of the [LoginForm] when we are validating credentials
/// [failure]: state of the [LoginForm] when a login attempt has failed
/// [success]: state of the [LoginForm] when a login attempt has succeeded
class LoginState extends Equatable {
  final bool isEmailValid;
  final bool isPasswordValid;
  final bool isSubmitting;
  final bool isSuccess;
  final bool isFailure;

  bool get isFormValid => isEmailValid && isPasswordValid;

  const LoginState({
    @required this.isEmailValid,
    @required this.isPasswordValid,
    @required this.isSubmitting,
    @required this.isSuccess,
    @required this.isFailure,
  });

  factory LoginState.empty() {
    return LoginState(
      isEmailValid: true,
      isPasswordValid: true,
      isSubmitting: false,
      isSuccess: false,
      isFailure: false,
    );
  }

  factory LoginState.loading() {
    return LoginState(
      isEmailValid: true,
      isPasswordValid: true,
      isSubmitting: true,
      isSuccess: false,
      isFailure: false,
    );
  }

  factory LoginState.failure() {
    return LoginState(
      isEmailValid: true,
      isPasswordValid: true,
      isSubmitting: false,
      isSuccess: false,
      isFailure: true,
    );
  }

  factory LoginState.success() {
    return LoginState(
      isEmailValid: true,
      isPasswordValid: true,
      isSubmitting: false,
      isSuccess: true,
      isFailure: false,
    );
  }

  LoginState update({
    bool isEmailValid,
    bool isPasswordValid,
  }) {
    return copyWith(
      isEmailValid: isEmailValid,
      isPasswordValid: isPasswordValid,
      isSubmitting: false,
      isSuccess: false,
      isFailure: false,
    );
  }

  LoginState copyWith({
    bool isEmailValid,
    bool isPasswordValid,
    bool isSubmitEnabled,
    bool isSubmitting,
    bool isSuccess,
    bool isFailure,
  }) {
    return LoginState(
      isEmailValid: isEmailValid ?? this.isEmailValid,
      isPasswordValid: isPasswordValid ?? this.isPasswordValid,
      isSubmitting: isSubmitting ?? this.isSubmitting,
      isSuccess: isSuccess ?? this.isSuccess,
      isFailure: isFailure ?? this.isFailure,
    );
  }

  @override
  List<Object> get props => [
        isEmailValid,
        isPasswordValid,
        isSubmitting,
        isSuccess,
        isFailure,
      ];

  @override
  String toString() {
    return '''
    LoginState {
      isEmailValid: $isEmailValid,
      isPasswordValid: $isPasswordValid,
      isSubmitting: $isSubmitting,
      isSuccess: $isSuccess,
      isFailure: $isFailure,
    }''';
  }
}

This is the code for the LoginEvent:

part of 'login_bloc.dart';

/// List of [LoginEvent] objects to which our [LoginBloc] will be reacting to:
/// [EmailChanged] - notifies the BLoC that the user has changed the email.
/// [PasswordChanged] - notifies the BLoC that the user has changed the password.
/// [Submitted] - notifies the BLoC that the user has submitted the form.
/// [LoginWithGooglePressed] - notifies the BLoC that the user has pressed the Google Sign In button.
/// [LoginWithCredentialsPressed] - notifies the BLoC that the user has pressed the regular sign in button.
abstract class LoginEvent extends Equatable {
  const LoginEvent();

  @override
  List<Object> get props => [];
}

class EmailChanged extends LoginEvent {
  final String email;

  const EmailChanged({@required this.email});

  @override
  List<Object> get props => [email];

  @override
  String toString() => 'EmailChanged { email :$email }';
}

class PasswordChanged extends LoginEvent {
  final String password;

  const PasswordChanged({@required this.password});

  @override
  List<Object> get props => [password];

  @override
  String toString() => 'PasswordChanged { password: $password }';
}

class Submitted extends LoginEvent {
  final String email;
  final String password;

  const Submitted({
    @required this.email,
    @required this.password,
  });

  @override
  List<Object> get props => [email, password];

  @override
  String toString() => 'Submitted { email: $email, password: $password }';
}

class LoginWithGooglePressed extends LoginEvent {}

class LoginWithCredentialsPressed extends LoginEvent {
  final String email;
  final String password;

  const LoginWithCredentialsPressed({
    @required this.email,
    @required this.password,
  });

  @override
  List<Object> get props => [email, password];

  @override
  String toString() =>
      'LoginWithCredentialsPressed { email: $email, password: $password }';
}

And this is the code for the LoginBloc:

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import 'package:rxdart/rxdart.dart';

import '../../../utils/validators.dart';
import '../../repositories/authentication/authentication_repository.dart';

part 'login_event.dart';
part 'login_state.dart';

/// BLoC responsible for the business logic behind the login process. In particular this BLoC will
/// map the incoming [LoginEvent] to the correct [LoginState].
class LoginBloc extends Bloc<LoginEvent, LoginState> {
  /// Authentication repository that provides to the user the methods to sign-in
  /// with credentials and to sign-in with a Google account.
  final AuthenticationRepository authRepository;

  LoginBloc({@required this.authRepository}) : assert(authRepository != null);

  @override
  LoginState get initialState => LoginState.empty();

  // Overriding transformEvents in order to debounce the EmailChanged and PasswordChanged events
  // so that we give the user some time to stop typing before validating the input.
  @override
  Stream<Transition<LoginEvent, LoginState>> transformEvents(
    Stream<LoginEvent> events,
    TransitionFunction<LoginEvent, LoginState> transitionFn,
  ) {
    final nonDebounceStream = events.where((event) {
      return (event is! EmailChanged && event is! PasswordChanged);
    });
    final debounceStream = events.where((event) {
      return (event is EmailChanged || event is PasswordChanged);
    }).debounceTime(Duration(milliseconds: 300));
    return super.transformEvents(
      nonDebounceStream.mergeWith([debounceStream]),
      transitionFn,
    );
  }

  @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is EmailChanged) {
      yield* _mapEmailChangedToState(event.email);
    } else if (event is PasswordChanged) {
      yield* _mapPasswordChangedToState(event.password);
    } else if (event is LoginWithGooglePressed) {
      yield* _mapLoginWithGooglePressedToState();
    } else if (event is LoginWithCredentialsPressed) {
      yield* _mapLoginWithCredentialsPressedToState(
        email: event.email,
        password: event.password,
      );
    }
  }

  Stream<LoginState> _mapEmailChangedToState(String email) async* {
    yield state.update(
      isEmailValid: Validators.isValidEmail(email),
    );
  }

  Stream<LoginState> _mapPasswordChangedToState(String password) async* {
    yield state.update(
      isPasswordValid: Validators.isValidPassword(password),
    );
  }

  Stream<LoginState> _mapLoginWithGooglePressedToState() async* {
    try {
      await authRepository.signInWithGoogle();
      yield LoginState.success();
    } catch (_) {
      yield LoginState.failure();
    }
  }

  Stream<LoginState> _mapLoginWithCredentialsPressedToState({
    String email,
    String password,
  }) async* {
    yield LoginState.loading();
    try {
      await authRepository.signInWithCredentials(
        email: email,
        password: password,
      );
      yield LoginState.success();
    } catch (_) {
      yield LoginState.failure();
    }
  }
}

Now I'm trying to test this bloc using the bloc_test library, and in particular I'm testing the EmailChanged. As you can see from the LoginBloc code I added a debounce time of 300 milliseconds before mapping this event to the correct state.

For testing this event I used this code:

import 'package:covtrack/business/blocs/login/login_bloc.dart';
import 'package:covtrack/business/repositories/authentication/authentication_repository.dart';
import 'package:covtrack/utils/validators.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:bloc_test/bloc_test.dart';

class MockAuthenticationRepository extends Mock
    implements AuthenticationRepository {}

void main() {
  group('LoginBloc', () {
    AuthenticationRepository authRepository;
    LoginBloc loginBloc;
    String email;

    setUp(() {
      authRepository = MockAuthenticationRepository();
      loginBloc = LoginBloc(authRepository: authRepository);
      email = 'johndoe@mail.com';
    });

    test('throws AssertionError if AuthenticationRepository is null', () {
      expect(
        () => LoginBloc(authRepository: null),
        throwsA(isAssertionError),
      );
    });

    test('initial state is LoginState.empty()', () {
      expect(loginBloc.initialState, LoginState.empty());
    });

    group('EmailChanged', () {
      blocTest(
        'emits [LoginState] with isEmailValid true',
        build: () async => loginBloc,
        act: (bloc) async => bloc.add(EmailChanged(email: email)),
        wait: const Duration(milliseconds: 300),
        expect: [LoginState.empty().update(isEmailValid: true)],
      );
    });
  });
}

When I run the test I get this error:

✓ LoginBloc throws AssertionError if AuthenticationRepository is null
✓ LoginBloc initial state is LoginState.empty()
Expected: [
            LoginState:    LoginState {  
                isEmailValid: true,  
                isPasswordValid: true,  
                isSubmitting: false,  
                isSuccess: false,  
                isFailure: false,  
              }
          ]
  Actual: []
   Which: shorter than expected at location [0]

package:test_api                             expect
package:bloc_test/src/bloc_test.dart 143:29  blocTest.<fn>.<fn>
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         blocTest.<fn>.<fn>
dart:async                                   runZoned
package:bloc_test/src/bloc_test.dart 135:11  blocTest.<fn>

✖ LoginBloc EmailChanged emits [LoginState] with isEmailValid true

I don't understand the reason why no state at all is emitted.

Testing a function that contains stderr, stdout and os.Exit()

I'm building an UI for cli apps. I completed the functions but I couldn't figure out how to test it.

Repo: https://github.com/erdaltsksn/cui

func Success(message string) {
    color.Success.Println("√", message)
    os.Exit(0)
}

// Error prints a success message and exit status 1
func Error(message string, err ...error) {
    color.Danger.Println("X", message)
    if len(err) > 0 {
        for _, e := range err {
            fmt.Println(" ", e.Error())
        }
    }
    os.Exit(1)
}

I want to write unit tests for functions. The problem is functions contains print and os.Exit(). I couldn't figure out how to write test for both.

This topic: How to test a function's output (stdout/stderr) in unit tests helps me test print function. I need to add os.Exit()

My Solution for now:

func captureOutput(f func()) string {
    var buf bytes.Buffer
    log.SetOutput(&buf)
    f()
    log.SetOutput(os.Stderr)
    return buf.String()
}

func TestSuccess(t *testing.T) {
    type args struct {
        message string
    }
    tests := []struct {
        name   string
        args   args
        output string
    }{
        {"Add test cases.", args{message: "my message"}, "ESC[1;32m"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            want := tt.output
            got := captureOutput(func() {
                cui.Success(tt.args.message)
            })
            got := err
            if got.Error() != want {
                t.Error("Got:", got, ",", "Want:", want)
            }
        })
    }
}

How to count the number of times the spring boot loads on spring tests?

I've a app with spring boot tests, can I enforce the number of times that spring boot is loaded? so if someone will load another spring boot I'll will warn about it.

samedi 27 juin 2020

Mocking useState hook to test component/passing data to my test

I have the following component I'm trying to test. The GoogleLogin component is coming for a third party library but I'm just wondering how I can test the loading part? I want to set/mock the loading data and test if the loading component is shown on screen.

const GoogleLoginButton: React.FC = () => {
    const [googleLoading, setGoogleLoading] = useState<boolean>(false)

    const googleResponseSuccess = () => {
        setGoogleLoading(false)
    }

    const googleResponseError = () => {
        setGoogleLoading(false)
    }

    return (
        <>
            {googleLoading && <InlineLoader />}

            <GoogleLogin
                onSuccess={googleResponseSuccess}
                onFailure={googleResponseError}
            />
        </>
    )
}

Does anybody have a good way of doing this? any help would be appreciated!

How do I test authentication from a UI app to Laravel Passport?

My application authenticates just fine using the Nuxt OAuth module. However, when trying to test the same conditions, it fails. Here is my error:

{
  "error":"invalid_grant",
  "error_description":"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.",
  "hint":"",
  "message":"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}

This is the code for my test:

<?php
...
class LoginTest extends TestCase
{

    use RefreshDatabase, WithFaker;

    protected $user, $client, $accessToken, $oauth_access_tokens_table;
    public $mockConsoleOutput = false;

    public function setUp() : void
    {
        parent::setUp();

        $this->user = factory('App\User')->create(['password' => 'password']);

        $this->artisan('passport:install', [
            '--no-interaction' => true
        ]);
        $this->artisan('passport:keys', ['--no-interaction' => true]);

        $this->accessToken = $this->user->createToken('authToken')->accessToken;

        $this->client = DB::table('oauth_clients')->find(2); // password grant client
    }

    public function testAUserCanAuthenticateViaApi()
    {
        $client = Passport::actingAsClient($this->client, ['*']);

        $payload = [
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'username' => $this->user->email,
            'password' => 'password',
            'scope' => '',
        ];

        $headers = [
            'accept' => 'application/json, text/plain, */*',
        ];

        $response = $this->post('/oauth/token', $payload, $headers);

        $this->assertAuthenticatedAs($this->user);
    }
}

I can confirm that the client exists and that the data is there as it should be. I am sure that there is a better way to do this, but I have struggled for several hours and I feel that I am missing something fundamental. At this point, I am simply trying to successfully fetch a token. Thank you in advance for looking at this.

Testing react component that is dependent on Stateful Context Providers chain in React Testing Library

I'm aware of this, but it's not my case.

Example:

<AuthProvider>
  <SessionProvider>
    <AnotherProvider>
      <OneMoreProvider>
        <MyComponent />

All of these providers are actually regular React Components with state and effects, that fetch some data via GraphQL and pass that data as a 'value' prop to MyContext.Provider in return statement.

This enforces me to create lots of mocks for modules that are being used in all of these providers, just to render my own component in testing env.

Any thoughts about what can be done to avoid creating so many mocks?