vendredi 31 juillet 2020

Writing Mocha Chai Test cases for NodeJs Controllers

I am new to unit testing. I am trying to write test cases for controller.js files for nodejs microservices files. I am unable to understand where I am going wrong. Always throws an error "TypeError: Cannot read property 'empId' of undefined" for 2 of these properties.

This is the controller code:

const crmgDetails = db.crmgResource_details;
const employeeProposal = db.employee_Proposal;
const Op = db.Sequelize.Op;
const raDetails = db.crmgRaSheet_entity;
let results = [];
Sequelize = require('sequelize')

exports.findOne = (req, res) => {
    console.log(req.body.empId);
    crmgDetails.findAll({where: {
        resEmployeeNumber: req.body.empId
    }
    })
       .then(data => {
           res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

exports.findMatchingDemandsForRmg = (req,res) => {
    let proposedDemands = [];
    
    employeeProposal.findAll({
        where: {
            emp_id: req.body.empId,
            demandSbu : req.body.sbu
        }
    }).then(proposedEmployee => {
        console.log('proposedEmployee',proposedEmployee);
        if(proposedEmployee.length === 0){
            crmgDetails.findAll({
                where: {
                    resEmployeeNumber: req.body.empId,
                    demandSbu: req.body.sbu
                }
            }).then(matchingDemands => {
                
                console.log('matchingDemands  ',matchingDemands)
                proposedDemands = matchingDemands;
                
            })
        }
        else{
            console.log("crmg Employee")
            console.log(proposedEmployee)
            
            
                for(let employee of proposedEmployee){
                
                        crmgDetails.findOne({
                            where: {
                                demandUid: employee.demandUid,
                                resEmployeeNumber: req.body.empId,
                                demandSbu: req.body.sbu
                            }
                        }).then( crmgProposed=> {
                            proposedDemands.push(crmgProposed);
                        })
                
                    
                }
            
        }
        setTimeout(() => {
            console.log(proposedDemands)
        res.send(proposedDemands);
        }, 3000);
        
        
    }).catch((err)=>{
        res.status(500).send({
            message:
              err.message || "Some error occurred while retrieving tutorials."
          });
    })

}

exports.getResourceAllocationDetails = (req,res) => {
    employeeProposal.findAll({
        include: {
            model: raDetails
        },
        where: Sequelize.and(
            {activeFlag : true},
            Sequelize.or({status:"Accepted By RMG"},
            {status:"Rejected"}
        ))
    }).then(employees => {
        res.send(employees)
    })
}

This is the test file I tried to write without my head:

const CrmgRaSheetModel = require('../controllers/crmgResource_Details.controller')
describe('Check for succcessful fetech API call', () => {
  it('property getResourceAllocationDetails should be called', async () => {
    CrmgRaSheetModel.getResourceAllocationDetails((res) => {
      expect(res).to.be.an('object')
              return res.json()
          })
  });
  it('property findMatchingDemandsForRmg should be called', async () => {
    CrmgRaSheetModel.findMatchingDemandsForRmg((res) => {
      expect(res).to.be.an('object')
              return res.json()
          })
  });
  it('property findOne should be called', async () => {
    CrmgRaSheetModel.findOne((res) => {
      expect(res).to.be.an('object')
              return res.json()
          })
  })
})

Spring Boot + Liquibase Test Profile Configuration

I am trying to create a test in-memory h2 database that has schema changes from my liquibase change log. When I run my app, it seems that nothing really happens with the h2 database, and that the liquibase change log is only applied to the main postgresql database in my applications.yml file. I've tried naming the test config file application.yml (in test/resources) and application-test.yml to no success. I've also tried changing the active profile in both application.yml and application-test.yml

application.yml file in project root directory:

spring:
profiles:
    active: test
datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    username: postgres
    password: postgres
    driver-class-name: org.postgresql.Driver
liquibase:
    changelog: classpath:db/changelog/db.changelog-master.xml
jpa:
    hibernate:
        ddl-auto: validate

application-test.yml

spring:
liquibase:
    changelog: classpath:db/changelog/db.changelog-master.xml
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
    user: sa
    password:
    drop-first: true
jpa:
    hibernate:
        ddl-auto: none

Test file:

@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("test")
public class SchemaMigrationApplicationTests {

    @Test
    public void contextLoads() {
    }

}

Dependencies:

implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.liquibase:liquibase-core'
testImplementation 'junit:junit:4.12'
implementation 'junit:junit:4.12'
runtimeOnly 'org.postgresql:postgresql'
runtimeOnly 'com.h2database:h2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}

Laravel nova basic testing gives 403

I'm writing my first functional tests with Laravel Nova.

Here is my

/** @test **/
    public function super_admin_has_ui_access()
    {
    $this->user = factory(\App\User::class)->create(['profile_id' => 1, 'company_id' => 1, 'operation_id' => 1,]);
    $this->actingAs($this->user);
        $this->user->update(['email' =>'julien@email.fr',  'profile_id' => 1]);
        $response = $this->get('/nova-api/users/1');

        $response->assertStatus(200);
    }

    $this->user = factory(\App\User::class)->create(['profile_id' => 1, 'company_id' => 1, 'operation_id' => 1,]);
    $this->actingAs($this->user);

But nova is getting me:

Expected status code 200 but received 403.
Failed asserting that 200 is identical to 403.

When I try manually to log with this user (superadmin ), I can access this url.

Is there something I have to configure with phpunit ?

a data monitoring infrastructure to ensure integrity of data

We work on some important, financial data(= it is transactional data in the databases world ) and do a lot of transformations and processing on them and save the result to different sorts of filesystems, databases, and so on.

we want to do different kinds of tests on our output data to ensure the integrity of data preserved based on input data. how can we approach this issue in big data? what is your advice? is there any framework to use?

thank you in advance

How does @AutoConfigureTestDatabase work with Postgres and opening new sessions in tests?

I have a bit of a silly question that has been really stressing me out these past few days. We have a a test integration suite on one of our services that uses

 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

for each test. We will have a local Postgres set up and we set the configuration in properties file. So we configure an entity manager and persist and flush set up data, we're able to do integration tests against the service and it all works great.

However whenever I debug one of these tests, I never see the data in my actual local database. I'll query the tables and they're all empty. I can see that in the entity manager it has a persistence context with all of the pre-set up data, but that doesn't make sense that we aren't really using the database? I know we are because if we change a column in the database the test will fail if the Entity hasn't been updated or vice-versa.

The reason why this is stressing me out is because I have written some code for a hibernate-search feature and in there I open a new session with the EntityManagerFactory

Session session = (this.fullTextEntityManager.unwrap(Session.class)).getSessionFactory().openSession();
 

Do the hibernate search query and when the service is running it works great. I have to create this new session because for some reason we had a single fullTextEntityManager bean that we were sharing across the service and it was pulling up old data whenever did a search due to it saving the search data in the persistence context, and in a multi-instance environment that just caused a lot of issues.

However now that I create this new session, our integration tests fail because it is unable to find the data due to it not pulling from our configured EntityManager for our test suite. I guess I'm just wondering with this @AutoConfigureTestDatabase , how come I can't find any data when I open a new session and where does the data go? Shouldn't it be flushing data to the database and why don't I ever see data in there?

pandas assert_frame_equal fails to compare two identical dataframes

I am trying to use assert_frame_equal for tests by comparing the function return dataframe to a dataframe read from a csv file. The csv file was created from the dataframe that this function returns:

results = my_fun()
results.to_csv("test.csv", mode="w", sep="\t", index=False)

Therefore, I assume they should be identical. Now, in the test I have the following code.

results = my_fun()
test_df = pd.read_csv("test.csv", sep="\t", header="infer", index_col=False, encoding="utf-8")
assert_frame_equal(results.reset_index(drop=True), test_df.reset_index(drop=True), check_column_type=False, check_dtype=False)

What I get is the following exception:

E   AssertionError: DataFrame.iloc[:, 0] (column name="document_id") are different
E
E   DataFrame.iloc[:, 0] (column name="document_id") values are different (100.0 %)
E   [left]:  [1, 1, 1, 2, 2, 2, 2, 2]
E   [right]: [1, 1, 1, 2, 2, 2, 2, 2]

I am scratching my head. What is the actual difference here?

How to test entities which have not null foreign key constraints

I have a dozen of tables like Product, Category, Customer, Order, ... with not null relationships to one another. I created ORM and right now I am in the middle of tests.

However I find it pretty tedious, because in order to test for example Order entity which has to belong to Customer (namely perform persist operation) I have to create Customer instance as well. Lets go further: because Order cannot exist separately to Product I have to create Product and add it to Order. Product has to be in some Category, and so on. So you can see a chain of mandatory relationships, which makes testing individual entity very difficult.

Natural solution would be to defer constraint check to commit (Oracle):

alter session set constraints=deferred;

However I found a piece of information that Hibernate doesn't care of deferring (support for deferred constraint).

Does it mean, that persistence testing has to be so problematic or I can do it better/different?

I believe that db constraints are sacred, so resigning from them, because hibernate does not support it sounds bad.

TestCafe Studio: How do I import ES modules so I can use them in a TestCafe Script?

I want to use imported functions in TestCafe Scripts (which are basically copied into the test method). To me these scripts would be great to create reusable code snippets.

But I did not find a place where I could import a module which is then added to the import statements in the header of the test file.

An example:

I have a test-function I use for visual regression tests. It basically takes a screenshot of the page and compares it to a screenshot stored on disk. Since this also includes reading and writing files from/to disk using nodes fs API and calling packages like graphicsmagik, it quickly becomes a huge script. I might be able to copy it into a a TestCafe Script block, but it is not reusable and hardly scales.

Is there something I missed?

Of course I could create some command-line task that adds the import line to the top of all generated js files. But the test would only work after someone made them js files and ran my script. It would not be possible to run these tests directly from TestCafe Studio.

Basic Test is failing on Laravel 7

I'm trying to code my first test.

I tried to run the out-the-box test:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

with

php artisan test

But I get:

➜  acc git:(master) ✗ php artisan test

   PASS  Tests\Unit\ExampleTest
  ✓ basic test

   FAIL  Tests\Feature\ExampleTest
  ✕ basic test

  Tests:  1 failed, 1 passed

  Expected status code 200 but received 500. Failed asserting that 200 is identical to 500.

  at tests/Feature/ExampleTest.php:18
    14|     public function testBasicTest()
    15|     {
    16|         $response = $this->get('/');
    17| 
  > 18|         $response->assertStatus(200);
    19|     }
    20| }
    21| 

When I go to chrome to : http://localhost:8000 I get a 200.

Why is it happening ?

Data Testing / REST Assured / Java Unit Testing

So in the past I have worked with rest assured and other java frameworks.

This is more an open ended question in what is the best / modern way to test data either sql / oracle ...etc

So the basics would be is you need to confirm data in a table is equal to a specific string / int / boolean ...etc. The test needs to be able to run via maven or something that can be integrated into a Jenkins type of environment so that it will be run on every build.

What would you suggest is the best way to achieve this any idea or tools that you have used would be welcome.

I have searched around and most people are just doing normal unit tests. But if i wanted to test production data that should remain static what would you suggest or are the best practices.

Thanks Flenters

Testcafe- Upload file getting status 222 with no response and no errors in logs

I am trying to upload a file using testcafe script but its going in infinite loop. I am not getting what's wrong with my code, while all other functionalities except upload are working fine.

const click_upload=Selector('input[name="logo"]')
const upload_logo=Selector('input[name="logo"],input[inputtype="file"]')

test
    ('upload file step 3',async t=>{
        await t
        .useRole(somerole)
        .navigateTo('https://xyz.in/')
        .click(click_upload)// Upload button has a css 
        .wait(5000)
        .setFilesToUpload(upload_logo,[
            './_uploads_/image.png'
            ])
        .wait(12000)

    })

Its going in infinite loop and it's never ending, I even tried to add .debug() and check but no help. I am getting status code 222 in api call, and empty response. i.e in upload there is no api call going, I have checked on console and I am not getting any errors, If I try manually its working.

Test specific file using Jest

In my project folder I have lots of subfolders with js code and test.js file in each of them. I want to be able to test specific file. For example, let's say in our project folder we have 'fib' folder:

C:.
└───exercises
    └───fib
            fib-test.js
            index.js

Now, from the exercises folder I execute jest command:

jest fib\fib-test.js

And I get:

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\exercises
  62 files checked.
  testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 26 matches
  testPathIgnorePatterns: \\node_modules\\ - 62 matches
  testRegex:  - 0 matches
Pattern: fib\fib-test.js - 0 matches

If I do just jest, I'll get all tests ran. If I move fib folder out of the exercises folder it works as expected. Here is the code for all of the files:

index.js:

function fib(n) {}

module.exports = fib;

test.js:

const fib = require('./index');

test('Fib function is defined', () => {
  expect(typeof fib).toEqual('function');
});

test('calculates correct fib value for 1', () => {
  expect(fib(1)).toEqual(1);
});

test('calculates correct fib value for 2', () => {
  expect(fib(2)).toEqual(1);
});

test('calculates correct fib value for 3', () => {
  expect(fib(3)).toEqual(2);
});

test('calculates correct fib value for 4', () => {
  expect(fib(4)).toEqual(3);
});

test('calculates correct fib value for 15', () => {
  expect(fib(39)).toEqual(63245986);
});

package.json:

{
  "name": "dev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "jest": {
    "testEnvironment": "node"
  },
  "author": "",
  "license": "ISC"
}

I've tried all of these solutions with no success:

  1. Run single test of a specific test suite in Jest
  2. How do I run a single test using Jest?
  3. How do I test a single file using Jest?

But was able to achieve the desired result running jest command with --watch flag and then in regex menu entering the relative path to the fib\test.js. The question is how to do it without entering watch menu?

How to find the duplicate entry in the API response through assertion - SoapUI and Postman

I send a request for a web service and in the response, I will get 1000 recordsID. How can I check all recordsID is unique.

Or how can I find the duplicate entry in the API response

Response Type - XML and JSON(Both)

Tests failing after adding react-remove-properties babel plugin

I am wanting to utilise the react-remove-properties babel plugin, however after introducing it, it seems to make my tests fail...

My simplified component

<div data-testid="my-tag">Hello world</div>

My simplified test

const provider = <Provider store={mockStore(store)}><MyComponent /></Provider>;
const {queryByTestId} = render(provider)

it('should display tag text', () => {
    expect(queryByTestId('my-tag').textContent).toBe('Hello world');
});

Before adding the babel plugin, this test passed!

After adding the plugin to remove the data-testid tags, the test is failing with:

TypeError: Cannot read property 'textContent' of null

      32 |             const {queryByTestId} = render(provider);
      33 | 
    > 34 |             expect(queryByTestId('my-tag').textContent).toBe('Hello world');
         |                    ^
      35 | 
      36 |         });

It seems that the babel plugin is running before my test and removing the data-testid tags first, so they cannot be found during testing.

Can anybody offer any advice on how to rectify this?

Maven - list tests covering one Java class

I have a maven project with tests executed using Surefire and whose code coverage is handled by Jacoco. My test results are then forwarded to SonarQube for analysis for each pull request.

In this context I would like to know the tests that were executed to cover one class, in order to list all tests covering the code changed in my pull request.

Any idea how to do this ? thanks!

How to test simple boolean functions?

Im having some issues to understand testing, since I almost never find it neccessary.

If I have simple functions like

function isMovementOutOfBounds(newPosition) {
  if (newPosition[0] > input[0][0] || newPosition[0] < 0 || newPosition[1] > input[0][1] || newPosition[1] < 0) {
    return true;
  }
  return false;
}

or

function isMovementForbidden(forbiddenMovements, initialPosition, newPosition) {
  function isArrayInArray(arr, item) {
    const item_as_string = JSON.stringify(item);
    const contains = arr.some((ele) => JSON.stringify(ele) === item_as_string);
    return contains;
  }
  const newMovement = [initialPosition, newPosition];

  if (isArrayInArray(forbiddenMovements, newMovement)) {
    return true;
  }
  return false;
}

Should they even be tested? They have always a return, and its always boolean. So I don't understand if its really necessary to test it.

Maybe I should test for the type of input they receive?

It all seems dumb to me, how could I test those functions? Any idea of what should I look for?

Generating test data in R

I am trying to generate this table as one of the inputs to a test.

        id                 diff          d
 1:      1                    2 2020-07-31
 2:      1                    1 2020-08-01
 3:      1                    1 2020-08-02
 4:      1                    1 2020-08-03
 5:      1                    1 2020-08-04
 6:      2                    2 2020-07-31
 7:      2                    1 2020-08-01
 8:      2                    1 2020-08-02
 9:      2                    1 2020-08-03
10:      2                    1 2020-08-04
11:      3                    2 2020-07-31
12:      3                    1 2020-08-01
13:      3                    1 2020-08-02
14:      3                    1 2020-08-03
15:      3                    1 2020-08-04
16:      4                    2 2020-07-31
17:      4                    1 2020-08-01
18:      4                    1 2020-08-02
19:      4                    1 2020-08-03
20:      4                    1 2020-08-04
21:      5                    2 2020-07-31
22:      5                    1 2020-08-01
23:      5                    1 2020-08-02
24:      5                    1 2020-08-03
25:      5                    1 2020-08-04
        id                 diff          d

I have done it like this -

input1 = data.table(id=as.character(1:5), diff=1)
input1 = input1[,.(d=seq(as.Date('2020-07-31'), by='days', length.out = 5)),.(id, diff)]
input1[d == '2020-07-31']$diff = 2

diff is basically the number of days to the next weekday. Eg. 31st Jul 2020 is Friday. Hence diff is 2 which is the diff to the next weekday, Monday. For the others it will be 1.

  • Is there a more R idiomatic way of doing this ?

I personally dont like that I had to generate the date sequence for each of the ids separately or the hardcoding of the diff that I have to do in the input for 31st July. Is there a more generic way of doing this without the hardcoding?

wiremock stub with query params not working

I am trying to match this url path -

/abc-service/abc?param1=value1&param2=VALUE_2

This gets matched with a json file as below

{
  "request": {
    "method": "GET",
    "urlPathPattern": "/abc-service/abc(.*)"
  },
  "response": {
    "headers": {
      "Content-Type": "application/json"
    },
    "jsonBody": [],
    "status": 200
  }
}

But if I remove this and use stubFor() as below, it doesn't work.

WireMock.stubFor(
        WireMock.get(WireMock.urlPathMatching("/abc-service/abc(.*)"))
                .willReturn(okJson("[]")));

I even tried adding query params as below, that doesn't work either.

final Map<String, StringValuePattern> stringStringValuePatternMap = new HashMap<>();
stringStringValuePatternMap.put("param1", matching("value1"));
stringStringValuePatternMap.put("param2", matching("VALUE2"));
WireMock.stubFor(
        WireMock.get(WireMock.urlPathEqualTo("/abc-service/abc"))
                .withQueryParams(stringStringValuePatternMap)
                .willReturn(
                        aResponse()
                                .withStatus(HttpStatus.OK.value())
                                .withHeader(
                                        HttpHeaders.CONTENT_TYPE,
                                        MediaType.APPLICATION_JSON_VALUE)));

What am I doing wrong?

Jest/Enzyme ReactJS Testing Form Control Option

Trying to write unit tests for a form I have in a component. I have this at the moment which works fine for any 'text input' parts of the form however for dropdown selects it doesn't work...

it('should set the gender on change event', () => {
    wrapper.find('#gender').simulate('change', {
        target: {
            value: 'female',
        },
    });
    expect(wrapper.find('#gender').props().value).toEqual(
        'female',
    );
});

It just says that it expected 'Female' but got nothing.

This is what I am trying to test -

<Form.Group as={Row} controlId="gender">
    <Form.Label column sm="2"> Gender </Form.Label>
        <Col sm="10">
            <Form.Control defaultValue="" as="select" value={gender} required onChange={event => setGender(event.currentTarget.value)}>
                <option value="" disabled>Choose...</option>
                {data.gender.map(opt => <option key={opt}>{opt}</option>)}
            </Form.Control>
        </Col>
</Form.Group>

I have been googling and trying a number of things but can't get it to work! Any help would be appreciated

How can a string be both null and not null according to -z and -n tests? [closed]

I am writing a script where I need to check for existence of files with a certain pattern, and I encountered this peculiar, at least to me, behavior. If I test the output of ls command for non-existing files, it turns out to be true whether I use -z or -n test.

# if [ -z $(ls /path/to/file/*nosuchfiles* 2>/dev/null) ]; then echo yes;fi
yes
# if [ -n $(ls /path/to/file/*nosuchfiles* 2>/dev/null) ]; then echo yes;fi
yes

How is that possible? What am I missing here?

jeudi 30 juillet 2020

Use test data instead of fixtures in CakePHP tests

Is there a way to just use actual test data instead of writing all the fixtures for testing CakePHP website?

Configure Chrome options for Cypress

In Selenium projects, I'm used to configure the Chrome options. Is there a way of doing it in Cypress projects?

I need to test a website that is flagged like "unsafe" because of its obsolete certificates, and I need to bypass the "Unprotected connection" window.

What it looks like in Selenium projects:

DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome ()       
handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true)
WebDriver driver = new ChromeDriver (handlSSLErr);

Thanks in advance.

Handling integration and UI tests that are missing their prerequisite

I just have a simple question. For integration tests to the backend and automated UI tests that are missing their prerequisites (eg. the test accounts sign in to the app), do you set the tests as failed or just completely ignore those tests? I am in the process of refactoring my tests and this comes out because when I try checking the backend, my usual test accounts are gone and the tests are all failing. So I can't be sure if this won't happen again in the future.

Thanks.

Appium wdio exited before timeout (exit code: 2) ERROR @wdio/cli:utils: A service failed in the 'onPrepare' hook

When trying to run I'm having the log below as return. @wdio/appium-service: Appium exited before timeout (exit code: 2) [HTTP] Could not start REST http interface listener. The requested port may already be in use. Please make sure there is no other instance of this server running already. ERROR @wdio/cli:utils: A service failed in the 'onPrepare' hook

package.json

wdio.android.conf

wdio.shared.conf

Errors in post Django testing procedure

I'm trying to make a test for incrementig votes in Django polls tutorial application.

I made two identical tests in django shell and in test.py. None of them working and results are different. The app is working well.

In the 1st case response of post request is 200 , no incrementing value. In the 2nd case a '404' ! for same command as the 1st case and error for Choice object.

These are the two situations:

*1) django shell:

Code:

#python manage.py shell < 1.py
#>>> exec(open('1.py').read())

from django.test.utils import setup_test_environment
setup_test_environment()
from django.test import Client
client = Client()

from polls.models import Choice

print("votes before",Choice.objects.get(id=7).votes)

response = client.post('/polls/3/vote/', {'name':'choice','value':'7'} )
print(response.status_code)

response = client.get('/polls/3/results/')
print(response.content)

print("votes after",Choice.objects.get(id=7).votes)

Result:

votes before 5
200
b'<h1>What do you like?</h1>\n\n<ul>\n\n    <li>Coffee -- 5 votes</li>\n\n    <li>Coca Cola -- 4 votes</li>\n\n</ul>\n\n<a href="/polls/3/">Vote again?</a>\n'
votes after 5

*2) django test:

Code:

from .models import Choice

class TestVote(TestCase):

    def test_if_vote_is_incrementing1(self):
        response = self.client.post( '/polls/3/vote/', data = {'name':'choice','value':'7'} )
        self.assertEqual(response.status_code, 200)

    def test_if_vote_is_incrementing2(self):
        votes0 = Choice.objects.get(id=7).votes
        response = self.client.post( '/polls/3/vote/', data = {'name':'choice','value':'7'} )
        votes1 = Choice.objects.get(id=7).votes
        self.assertEqual(votes1, votes0+1)

Result:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
FE
======================================================================
ERROR: test_if_vote_is_incrementing2 (polls.tests.TestVote)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/mihai/all/data/work2020/django/mysite4/polls/tests.py", line 13, in test_if_vote_is_incrementing2
    votes0 = Choice.objects.get(id=7).votes
  File "/home/mihai/env_dj/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/mihai/env_dj/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get
    self.model._meta.object_name
polls.models.Choice.DoesNotExist: Choice matching query does not exist.

======================================================================
FAIL: test_if_vote_is_incrementing1 (polls.tests.TestVote)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/mihai/all/data/work2020/django/mysite4/polls/tests.py", line 10, in test_if_vote_is_incrementing1
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 2 tests in 0.006s

FAILED (failures=1, errors=1)
Destroying test database for alias 'default'...

How to suppress Jest Linter errors from import files?

So I'm trying to do some basic API testing with Jest by importing a function from handler.ts but Jest crawls through the handler ts imports and gives me linter errors for a file that handler importest from my libs folder when all I want to do is check if the result of that function equals what I want it to equal.

Here's my test file test/handler.test.ts:

import { getInbox } from './../handler'
import * as myMongo from '../../../libs/mongo';
import { Db } from 'mongodb';

const productionDbPromise: Promise<Db> = myMongo.getProductionDb();

test("Case page 1, limit 5", async ()=>{
    const page = 1;
    const limit = 5;
    const event = {
        queryStringParameters: {
            page: page,
            limit: limit
        }
    };
    const productionDb = await productionDbPromise;
    const seekerCollection = productionDb.collection('seekers');
    const totalDocs = await seekerCollection.countDocuments({ lastMessageDate: { $ne: null } });
    const code = 200;
    const status = 'OK';
    const res: any = await getInbox(event);
    expect(res.code).toEqual(code);
    expect(res.status).toEqual(status);
    expect(res.json().totalDocs).toEqual(totalDocs);
    expect(res.json().seekers.length).toEqual(limit);
});

And here's the error:

Test suite failed to run

    TypeError: twilio is not a function

      6 | export const client = twilio(accountSid, authToken);
      7 | export const messagingServiceSid = process.env.TWILIO_SERVICE_ID;
    > 8 | 
        | ^

      at Object.<anonymous> (../../libs/twilio.ts:8:18)
      at Object.<anonymous> (../../libs/message.ts:7:18)
      at Object.<anonymous> (handler.ts:14:19)
      at Object.<anonymous> (__test__/handler.test.ts:4:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        12.086 s
npm ERR! Test failed.  See above for more details.

Any idea how to get it to ignore this? (which by the way the function I'm testing does not even use any exports from that libs file, and the twilio object is correctly imported on the first line of that file)

Problem with testing whether a function has been run

I'm new to testing. I've tried to research this, but with no luck.

Problem is, that I'm trying to test my app root file, called couples2.ts, which is the entry for my NodeJS/TypeScript app.

It looks like this:

import App from "./app";

const app = new App();
app.run()

Now I'm trying to test whether the run() function has been called, and so I wrote this couples2.test.ts file with the following code, but it says that tests failed and the reason is that it's been called 0 times.

import App from "./app";

jest.mock('./app');

describe('couples2.ts file', () => {
    it('should run the `run` function', function () {
        const app = new App();
        expect(app.run).toHaveBeenCalled();
    });
})

What am I doing wrong?

REST assured: Wait for a condition before running all tests

I have a service that when it's being loaded, it takes a while (few minutes) until all the information is getting into the database.

If I run the tests prematurely, they will fail for that reason (missing items in DB).

Is there some REST assured feature to deal with it? Or I need to have my own mechanism to do that?

Django Rest Framework get_queryset() does not send full result to TestCase

I am running into a strange issue where my get_queryset() method for my ViewSet is grabbing the correct results but one of the objects in the query gets dropped as it's being returned to my test case. I can't really post any code but I can display parts of the test that fail and some logs.

Has anyone ever encountered this problem?

Here is the print out of my model field names just before the return statement in get_queryset(self):

QUERYSET len: 3
QUERYSET should return: <QuerySet ['Test', 'Test', 'Test']>

The assertion in my TestCase after calling the viewset and storing the response in res

self.assertEqual(len(res.data), 3)
AssertionError: 2 != 3

I don't understand how the ViewSet's get_queryset() clearly shows that the length is 3, yet the response returned from the ViewSet only has 2 objects out of the 3 in it. I've also tested serializing the response.data and testing that length also shows up as 2 but should be 3. So confused. I hope this is enough info for someone to go off of.

Test connected functional component with props - Redux & React Testing Library

I am attempting to test the returned render of my React component via its 2 different routes, depending on the presence of a particular featureToggle that will either be set to true or false.

import React from 'react';
import {connect} from "react-redux";

const mapStateToProps = (state) => ({
    featureToggle: (state.featureToggle && typeof state.featureToggle === 'object') ? state.featureToggle : null,
});

const MyComponent = ({featureToggle}) => {
    if (!featureToggle.myToggle) {
        return (
            <div>
               // One version of the component
            </div>
        );
    }

    return (
        <div>
            // Another version of the component
        </div>
    );
}

export default connect(mapStatesToProps)(MyComponent)

However I am struggling to get to grips with React Testing Library and React Redux. So far I have...

import React from 'react';
import MyComponent from "./MyComponent";
import {Provider} from "react-redux";
import {render} from "@testing-library/react";
import configureStore from 'redux-mock-store';

const mockStore = configureStore();

const getToggle = value => {
    return {myToggle: value};
}

let store;
let provider;
let rendered;

describe('MyComponent', () => {
    describe('Should render route 1 with toggle off', () => {
        store = mockStore(getToggle(false);

        beforeEach(() => {
            provider = <Provider store={store}><MyComponent /></Provider>;
            rendered = render(provider);
        })
   
        it('Should render fallback title', () => {
            expect(rendered.getByTestId('title').textContent).toBe('Toggle Off Title');
        });
    });

    describe('Should render second route with toggle on', () => {
        store = mockStore(getToggle(true);

        beforeEach(() => {
            provider = <Provider store={store}><MyComponent featureToggle={getToggle(true)} /></Provider>;
            rendered = render(provider);
        });

        it('Should render live title', () => {
            expect(rendered.getByTestId('title').textContent).toBe('Toggle On Title');
        });
    });
});

However, running this test file I receive:

TypeError: Cannot read property 'myToggle' of null

      10 | 
      11 | const MyComponent = ({featureToggle}) => {
    > 12 |     if (!featureToggle.myToggle) {
         |                        ^

Whats the best way to write test for testing Routes?

I wanted to write a test for main.tsx. Below is the code for the same. I haven't written any test for routes before. How do I write test for these routes?

const init = async () => {
  const history = createBrowserHistory({ basename: `${HISTORY_BASENAME}` });

  // Catch link clicks and push them to the history object.
  handleNavigation(history);
  const renderCreateOldSliModal = () => <OldSliCreateModal />;
  const renderCreateSRModal = (forceProblemType?: SupportType) => (
    <CreateSRModal forceProblemType={forceProblemType} interPluginContext= 
      {pluginListener.getContext()} />
  );
  
  ReactDOM.render(
    <Configuration value=>
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <NavMenuContextProvider navigation={navTree}>
              <Switch>
                <Route
                  path={`/${ResourceNames.serviceRequest}/${ResourceNames.create}`}
                  render={renderCreateOldSliModal}
                />
                <Route
                  path={`/${ResourceNames.create}`}
                  render={() => renderCreateSRModal()}
                  exact={true}
                />
            </Switch>
         </NavMenuContextProvider>
       </ConnectedRouter>
    </Provider>
    </Configuration>,
    document.getElementById(CONTAINER_ID)
};
init();

I wrote a test like below, but I get an error

TypeError: Cannot read property 'createElement' of undefined

Below is my test

it("check routes", () => {
    const history = createBrowserHistory();
    const { container } = render(
      <ConnectedRouter history={history}>
        <NavMenuContextProvider navigation={undefined}>
          <Switch>
            <Route history={history}>
              path="/support/create"
            </Route>
          </Switch>
        </NavMenuContextProvider>
      </ConnectedRouter>,
    );
    expect(container.innerHTML).toMatch("Open a Support Request");
  });

Using a custom BatchConfigurer in Spring Batch tests with @SpringBatchTest annotation

In an application I am working on, we are using Spring Batch. Until now, we stored Spring Batch metadata in the same Oracle schema as the application data. Due to some requirements, we needed to split this. Piecing together Spring Batch documentation, I've managed to configure Spring Batch to use a custom DataSource for its metadata using this code in my main Configuration class:

@Configuration
@EnableBatchProcessing
@EnableConfigurationProperties
@ImportAutoConfiguration({ BatchAutoConfiguration.class })
public class ArchiverBatchConfiguration {
// ...
    @Bean
    public BatchConfigurer batchConfigurer(BatchDatabaseProperties batchDatabaseProperties) {
        // DataSource gets created and saved into the dataSource variable
        return new DefaultBatchConfigurer(dataSource);
    }
}

This setup worked. The code works well - the Job correctly pulls its data from the main DataSource used by Hibernate and Spring Batch saves the metadata into the DataSource specified in the BatchConfigurer. However, I am unable to run the existing tests for batch steps and other tools we have built on top of Spring Batch. The principal problem seems to be the fact, that in the tests, the JobLauncherTestUtils and JobRepositoryTestUtils that are @Autowired thanks to the @SpringBatchTest annotation, do not respect the DataSource set in my custom BatchConfigurer and instead use the primary DataSource of the application, which is supposed to only be used by Hibernate. The test classes are defined like this:

@RunWith(SpringRunner.class)
@SpringBatchTest
@SpringBootTest(classes = ArchiverBatchConfiguration.class)
public class ArchiveStepAcceptanceTest {
    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Autowired
    private JobRepositoryTestUtils jobRepositoryTestUtils;

    // And the actual tests follow...
}

Any idea on how to persuade the TestUtils beans to use the settings from the custom BatchConfigurer or about any possible workarounds?

Cucumber Jenkins parametrisation

I'm wondering if it's possible to parameterised .feature in cucumber using Jenkins, for example:

Scenario: Test

Then Set login as " " into main field

Using Jenkins I'd like to set in empty space specific login. In the same feature one time I'd like to set login as "Test2", other time when i run my test I'd like to set login as "Test"

Angular 8 | Jasmine | Trying to test method is called in a subscription but it's never triggered

I have a method that is called in an ngOnInit. I want to test that given the ngOnit call then this.anotherService.methodToCall() is triggered and what it is being called with.

It just never seems to be called when I run my tests. I've tried several different ways to try and do this but nothing seems to work. I'm pretty new working with Angular and observables so I might be missing something very obvious.

The functionality of the component does exactly what I want it to do. So i'm basically just asking on advice on what the best method to test this would be. Thanks.

In component.ts

readOnly items: Observable<TemplateItems[]> = this.itemsHandler.itemsState$;
ngOnInit(): void {
  this.checkParams();
}
private checkParams() : void {
  this.observableResult$ = combineLatest(this.items, this.activatedRoute.params]);
  this.subscriptions.add(
    this.observableResult$.subscribe(([items, params]) => {
      this.anotherService.methodToCall(items, params); 
    )
  )
}

in spec.ts - This is an example of the sorta thing I would like to do but once again not sure if this is the best way to approach.

...
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      RouterTestingModule,
      ...,
    ],
    providers: [
      AnotherService,
      {
        provide: ActivatedRoute,
        useValue: {
          params: of({}),
        } 
      }
    ]
  }).compileComponents()
});
...

describe('ngOnInit', () => {
  it('should call anotherservice methodcall with filter items and params', () => {
    activedRoute.params = of ({ value: "TEST_VALUE"});

    fixture.detectChanges();
    ...

    expect(spyOfAnotherServiceMethodCall).toBeCalledWith(someItemsValue, { value: "TEST_VALUE"})
  }
})


Mockito matcher for lambda parameters

I have a method with lambda parameter in Kotlin like this:

interface IQueryBuilder {
    ...
    fun filter(filter: IFilterCondition.() -> Unit): IQueryBuilder
}

I am trying to mock this method with 'anyOrNull()' matcher from mockito-kotlin to return itself instead of null. But it doesn't find my matcher and returns null. How should I mock lambda expressions?

Mocking code:

whenever(queryBuilder.filter(anyOrNull<IFilterCondition.() -> Unit>())).thenReturn(queryBuilder)

Function call in the code:

queryBuilder.filter {
    "Id" eq 1
    "Name" eq "Test"
}

!! Moving lamda inside of parentheses doesn't change anything. Android Studio warns about to use this syntax.

How to find this element using Selenium (python)

How to locate this element?

enter image description here

<div _ngcontent-ysj-c5>
    <div _ngcontent-ysj-c5 class="list-items unselected"> == $0
        <!---->
        " Installation "
    </div>
</div>

i have tried

driver.find_elements_by_xpath("//[contains(text(),' Installation ')]"). 

&

driver.find_element_by_xpath("//*[text()=' Installation ']").click();

but it doesn't work.

mercredi 29 juillet 2020

Postman test - validating value in array

I have a test in postman where I can validate a value in an array. The problem I run into is which the value is returned can be random. This is what the json looks like that I'm validating. [ { "id": "7776", "revision": { "revisionId": "7780", "createdByUserId": "Lakare12", "createdDateTime": "2020-07-29T16:49:34.000+05:30" }, "identifiers": [ { "system": "urn:oid:1.2.752.129.2.1.4.1", "value": "CDE473Child1", "use": "primary", "displayValue": null } ], "name": "AA Child 01", "active": true, "hasChildren": false, "parentUnitId": "7768" }, { "id": "7783", "revision": { "revisionId": "7783", "createdByUserId": "Lakare12", "createdDateTime": "2020-07-30T08:47:40.000+05:30" }, "identifiers": [ { "system": "urn:oid:1.2.752.129.2.1.4.1", "value": "CDE473Child3", "use": "primary", "displayValue": null } ], "name": "BB main Child 03", "active": true, "hasChildren": false, "parentUnitId": "7768" } ] I need to test that name contain "BB main Child 03"

ProgrammingError during TestCase

I am trying to create my first functional TestCase and having an issue with a ProgrammingError occurring. I will first start by showing my TestCase.

Note: I am using TenantTestCase because I am using Django-Tenant-Schemas to separate clients to separate schemas/sub-domains. I am not sure what self.c = TenantClient(self.tenant) does.

class FunctionalTestCase(TenantTestCase):
    def setUp(self):
        self.browser = webdriver.Chrome()
        self.c = TenantClient(self.tenant)

    def test_company_reg_btn_works(self):
        self.browser.get('http://localhost:8000')
        time.sleep(3)
        reg_btn = self.browser.find_element_by_id('register-link')
        reg_btn.click()
        self.c.get('/company-reg/', follow=True)

    def tearDown(self):
        self.browser.quit()

After running this I get the traceback:

  File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/david/PycharmProjects/clearpath_project/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "memos_memo_company" does not exist
LINE 1: ..."memo_id", "memos_memo_company"."company_id" FROM "memos_mem...

The usual way to make migrations and then migrate would be these commands:

python manage.py makemigrations
python manage.py migrate_schemas --shared
python manage.py migrate_schemas --tenant

And then I would create a tenant by:

python manage.py create_tenant

I am guessing this error is occurring as if the migration has not been run, but I am not sure. Can someone help explain what may cause this?

Testing multiple requests in single test method not working

I am trying to test signup form of my application. If same email or phone is used again, the request should be rejected. However, when firing multiple requests in a single method, the second request doesn't seem to get executed. My code

signup code

@user.route('/signup', methods=['GET', 'POST'])
@anonymous_required()
def signup():
    form = SignupForm()
    return_code = 200
    if form.validate_on_submit():
        if not User.find_by_email(form.email.data) and not User.find_by_phone(form.phone.data):
            usr = User()

            form.populate_obj(usr)
            usr.password = request.form.get('password')
            usr.alternate_id = int(time())
            usr.save()

            if login_user(usr):
                usr.update_activity_tracking(request.remote_addr)
                # flash('Thanks for signing up!')
                return redirect(url_for('user.welcome'))
        else:
            flash('The email or phone is already registered')
            return_code = 409
    else:
        return_code = 200 if request.method == 'GET' else 400

    return render_template('user/signup.html', form=form), return_code

Test code

@pytest.mark.usefixtures('empty_db')
def test_multiple_requests_failing(client, user):
    resp_one = client.post(url_for('user.signup'), data=user)

    assert resp_one.status_code == 302 # due to redirection
    assert User.query.count() == 1

    resp_two = client.post(url_for('user.signup'), data=user)
    assert resp_two.status_code == 409 # failing here. status code is still 302

    response_html = resp_two.data.decode('utf-8')
    assert 'The email or phone is already registered' in response_html

Fixture code

I am using pytest with pytest-flask plugin. However, I did try the same thing using naive test_client as well. I will post a case of that as well if required. The client fixture is provided by pytest itself.

@pytest.fixture(scope="session", autouse=True)
def app(tmpdir_factory):
    db_temp_dir = tmpdir_factory.mktemp('db_temp_dir')
    db_temp_path = os.path.abspath(os.path.join(db_temp_dir, 'test-db.sqlite'))
    db_uri = f'sqlite:///{db_temp_path}'

    override_settings = {
        'TESTING': True,
        'WTF_CSRF_ENABLED': False,
        'SQLALCHEMY_DATABASE_URI': db_uri
    }

    _app = create_app(settings_override=override_settings)

    ctx = _app.app_context()
    ctx.push()

    db.drop_all()
    db.create_all()

    yield _app

    ctx.pop()

@pytest.fixture()
def empty_db():
    meta = db.metadata
    for table in reversed(meta.sorted_tables):
        db.session.execute(table.delete())
    db.session.commit()

@pytest.fixture(scope="session")
def user():
    return dict(
        first_name='siddharth',
        last_name='gupta',
        email='check.sid@gmail.com',
        phone='1234123412',
        dob_date='12',
        dob_month='12',
        dob_year='1997',
        password='something',
        confirm_password='something',
        gender='male'
    )

I tried placing debugger on my application code. It turns out that the application code is called only on the first request and not on the second one. That clearly explains why the error is coming. But I don't understand how is resp_two getting the values that are present in resp_one and also the main thing of why the second request is not having any effect and is not getting called. I have a feeling that it might be related to the request context and application context being in scope but I am not sure. Please help. Thanks for taking the time.

Mocha failing to run simple test

I have a project in Node JS 8. These are my current versions :

 $ node --version
v8.17.0
 $ node_modules/.bin/mocha --version
6.2.3

I have a really simple endpoint and a really simple test. However the tests fail with an error in Mocha itself :

.../node_modules/mocha/lib/cli/options.js:108
      const pair = arg.split('=');

TypeError: arg.split is not a function

This is my test :

const app = require('../app.js')
const chai = require('chai')
const request = require('supertest')

var expect = chai.expect

describe('app.js', function() {
    describe('test', function() { 
        it('should reply ok', function(done) { 
          request(app) .post('/hello') .send('test') .end(function(err, res) { 
            expect(res.statusCode).to.equal(200); 
            expect(res.body).to.equal('test'); 
            done(); 
          }); 
        }); 
      }); 
});

What might I be doing wrong?

Note :

This is a snippet to demonstrate how I am running the tests :

"scripts": {
    "test": "NODE_ENV=test node_modules/.bin/mocha — timeout 10000"
  },

This is my packages tree list :

npm list --depth=0
...
├── chai@4.2.0
├── express@4.17.1
├── mocha@6.2.3
└── supertest@4.0.2

And my project structure :

$ find . | grep -v node_modules
.
./tests
./tests/test.js
./README.md
./package-lock.json
./package.json
./middleware.js
./app.js

How to Test a Form with Multiple Submit

I have a form with 2 submit

// src/Form/FooType.php
$builder
    ->add('mainsubmit', SubmitType::class, [])
    ->add('extrasubmit', SubmitType::class, [])

In my controller, I do some different treatment depending of the submit pressed

// src/Controller/FooController.php
if ($form->isSubmitted() && $form->isValid()) {
    if ($form->get('extrasubmit')->isClicked()) {
        // do some extra stuff
    }

When I click on the extra button, I can see it the symfony Profiler in the request POST parameters "extrasubmit" => "".
Everything works fine.

I'm doing functional tests with the crawler. Without trying to submit with the extra submit, it works fine, so we can assume my test doesn't have a typo.

How can I simulate the click on the extra submit ?

First Try:

$form = $crawler->filter('form')->form();
// [...]
$form['my_form_name[extrasubmit]'] = true;
$httpClient->submit($form);
// => InvalidArgumentException: Unreachable field "extrasubmit"

Second Try:

$form->get('my_form_name[extrasubmit]')->setValue("");
// => InvalidArgumentException: Unreachable field "extrasubmit"

How to overwrite cypress experiments?

I'm trying to overwrite the experimentalSourceRewriting option from cypress.json in the test suite file. cypress.json: { "baseUrl": "https://ift.tt/20zml3P", "experimentalSourceRewriting": true } I tried with Cypress.config('experimentalSourceRewriting', false) but it doesn't work

Symfony Panther authentication seems not to be taken into account

I am using Symfony Panther for some testing.

When I want to log an User like this :

    protected function setUpPanther()
    {
        $client = static::createPantherClient(['readinessPath' => '/error']);
        $client->manage()->window()->maximize();
        $this->client = $client;
    }

    protected function loginPantherClient(Client $client, User $user)
    {
        $client->request('GET', '/error');

        $session = self::$container->get('session');

        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $session->set('_security_main', serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());

        $client->getCookieJar()->set($cookie);
    }

    public function testUpdateProductDetails()
    {
        $this->setUpPanther();
        
        $admin = $this->getSuperAdminAccount();

        $this->loginPantherClient($this->client, $admin);
        $this->client->request('GET', '/');
        $this->assertSelectorExists('div.form-group');
    }

A strange phenomenon occurs.

  1. My client goes to the error page to initialize the cookie (required)

  2. And here I have the impression that the authentication of my client is not taken into account, because if you look closely, in my test, I then make a request on

$this->client->request('GET', '/');

But instead of redirecting me to the requested page, it redirects me to / login, as if during the request, the user was not authenticated, and therefore, was redirected to the login page, while in my code, I authenticate the user before

Has someone already had this problem ?

Sorry for my bad english, I'm French, I'm using Google traduction

Rolling/Sliding Window Approach for machine learning models

I want to set up a rolling-window approach to do some backtesting on my ML model. The idea is:

  • Take 9 months of data (e.g., 2019 Jan to Sept) to make forecast on next 3 months (e.g., 2019 Oct to Dec)
  • Then drop earliest 3 months (2019 Jan to March) and add 2019 Oct to Dec
  • Make forecast on next three months (2020 Jan to March)
  • Repeat process until end of data enter image description here

Now, lest say I have 3 years of data and I can easy select each year (or month) with:

dataframe.loc()

Then next step is to actually create a loop that will make the sliding window on my requirements. And here I am stuck and need your help!

If I use a simple loop like the following:

X = dataframe.values
n_train = 500
n_records = len(X)
for i in range(n_train, n_records):
    train, test = X[0:i], X[i:i+1]
    print('train=%d, test=%d' % (len(train), len(test)))

I am able to take the first 500 data points of my data and then make forecast for the next 1 (501st). And then using 501 data points to make forecast for 502nd... etc until I finish my data.

enter image description here

Anyone with an idea on how to use a similar loop (or another technique) to achieve my desired outcome?

Thanks!

Connection error in tests when using MongoDB driver in Rust

I am testing a function that should return entries for a given date. For that, I am calling a function that should populate the database with some entries using the official MongoDB driver.

// Setup DB for tests
async fn setup_db() -> Result<String> {
    let client = Client::with_uri_str("mongodb://root:root@mongodb:27017/").await?;
    let db = client.database("logs");
    let time = build_date();
    let coll = db.collection(&time);
    let mut insertion = coll
        .insert_one(
            doc! {"message": "test message 1", "user": "test_user1", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 2", "user": "test_user2", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 3", "user": "test_user3", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    insertion = coll
        .insert_one(
            doc! {"message": "test message 4", "user": "test_user1", "timestamp" : "01-01-20" },
            None,
        )
        .await?;
    return Ok("Ok".to_owned());
}

When I execute the setup function in main, everything works as expected. When it is run as a test:

#[tokio::test]
async fn reading_db_entries() {
    let res = setup_db().await;
    println!("setup complete, Result was: {:#?}", res);
    assert_ne!(check(res), false)
}

I get the following result:

setup complete, Result was: Err(
    Error {
        kind: ServerSelectionError {
            message: "Server selection timeout: No available servers. Topology: { Type: Unknown, Servers: [ { Address: mongodb:27017, Type: Unknown, Error: failed to lookup address information: Name or service not known }, ] }",
        },
    },
)

MongoDB is running as a Docker container. How can I get this to work?

What should you test in client side code?

the act of testing client side code is easy for me but figuring out what to test is the hard part.

Some sources I read tested every single HTML element in a react component (to make sure it was rendered correctly). this can be tedious in you have a large application or large components. Some sources only tested components that are interactive or changes to the DOM

please can experienced testes please provide a guide as to what to test and what to avoid in a client side application and its individual components.

example would be helpful

thanks in advance :)

integration/ E2E testing with an API test-automation

I have a system that consists two parts:

  • engine: reads input from an external source, transforms it and writes results to the DB
  • web: exposes an API to read the results

both are Spring Boot apps and in production they are running inside a docker container.

I'd like to have an E2E test which:

  • Runs both components
  • Mocks external APIs (that engine uses)
  • Queries web and check expected results
  • Check logs to see if there were any errors

I know about tools like REST Assured and karate but I have two missing parts.

  1. How do you normally run this services in test?
  2. Is there any convenient way to analyze the logs? (i.e. check there weren't any errors)

Flask redirect location has blueprint name. Get route path from redirect location path

I am testing redirects in my flask application. The application has multiple blueprints. The concerned route is in page blueprint while the final route is in user blueprint.

The route in question looks as -

@page.route('/')
def home():
    if current_user.is_authenticated:
        return redirect('user.welcome')
    return render_template('page/home.html')

The test looks as below.

@pytest.mark.usefixtures('empty_db')
def test_home_page_redirects_to_user_welcome_view_for_logged_in_user(client, user):
    # create the user and also logs him in'
    response = client.post(url_for('user.signup'), data=user)

    response = client.get(url_for('page.home'))
    assert response.status_code == 302
    assert urlparse(response.location).path == url_for('user.welcome')

The error I'm facing is that the response.location has the blueprint name in it. That is

response.location = 'http://0.0.0.0:9000/user.welcome'

which is causing the test to fail. The redirection is to the correct page, but the path returned by response.location is what i'm trying to fix. Is there a fix or any workaround? Thanks for taking the time to answer.

Setup add function in Mock DbSet with Moq (Entity Framework)

I'm new to mocking, and I'm trying to create a mock DbContext for testing select, add, update, delete.

The mock for selecting is working, but when I'm trying to add the 'add' function in the setup, I'm getting the following error in my return value .Returns((CalculatieInput t) => t):

Cannot implicitly convert type 'DK.Infrastructure.CalculatieInput' to 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<DK.Infrastructure.CalculatieInput>

Test.cs:

    [Fact]
    public void Add1()
    {
        var context = CreateDbContext();
        _da = new CalculatieInputDA(context.Object);

        CalculatieInput item = new CalculatieInput() { Title = "add test" };

        _da.Add(item);

        List<CalculatieInput> list = _da.getAll();

        Assert.Equal(27, list.Count);
    }

    private Mock<dieKeureWebContext> CreateDbContext()
    {
        var data = GetFakeData().AsQueryable();

        var dbSet = new Mock<DbSet<CalculatieInput>>();
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.Provider).Returns(data.Provider);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.Expression).Returns(data.Expression);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.ElementType).Returns(data.ElementType);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        dbSet.Setup(x => x.Add(It.IsAny<CalculatieInput>())).Returns((CalculatieInput t) => t);

        var context = new Mock<dieKeureWebContext>();
        context.Setup(c => c.CalculatieInput).Returns(dbSet.Object);

        return context;
    }

    private IEnumerable<CalculatieInput> GetFakeData()
    {
        var i = 1;
        var data = A.ListOf<CalculatieInput>(26);
        data.ForEach(x => x.Id = i++);
        return data.Select(_ => _);
    }

CalculatieInputDA.cs:

    public CalculatieInput Add(CalculatieInput item)
    {
        _context.CalculatieInput.Add(item);
        _context.SaveChanges();

        return item;
    }

Can someone point me in the right direction how to fix this?

How to test CSS property value with Jest Enzyme in React

I have a component that changes style depending on window size via media query in the CSS, however I can't seem to test it within React's Jest Enzyme framework.

I am currently doing this:

it('my test', () => {
  const myEl = wrapperEmail.find('a').at(1);
  expect(myEl.style).toHaveProperty('text-decoration', 'none');
});

However I get the error:

expect(received).toHaveProperty(path, value)

Matcher error: received value must not be null nor undefined

Received has value: undefined

I have also tried the old fashioned method:

const myEl = document.getElementsByTagName('a')[1];
expect(myEl.style['text-decoration']).toEqual('none');

with the error:

TypeError: Cannot read property 'style' of undefined

In TestCafe Studio: Is there a way to execute the steps of a previous test?

My test include steps which need to be repeated for every test.

Tests are something like this:

  1. Open Login Dialog (click login button)
  2. Login (enter username and password)
  3. Navigate to private page (click menu point)

Each of the tests depends on the previous tests.

Id like to use a function like "execute previous test code" which when called within test 3, call test 2 and therefore test 1. It is also important that hooks are not executed at this point.

For hand-written tests, this is not an issue: I'd define the tests as seperate functions and call them accordingly, instead of defining then as anonymous function within the test() call.

For TestCafe Studio I felt "hacky" calling internal APIs and created this function:

function executePreviousTestCode(t) {
    const id = t.testRun.test.id;
    const tests = t.testRun.test.testFile.collectedTests;
    const prevTestIndex = tests.findIndex(t => t.id === id) -1;
    if(prevTestIndex < 0) return;
    const prevTest = tests[prevTestIndex];
    return prevTest.fn(t)
}

It works for normal TestCafe but I dont know how to include it in a TestCafe Studio test.

Maybe someone came up with a better solution than copy&paste or one single big test.

How to run a test multiple times with different sets of data in cypress?

While automating a website, I have a requirement to run a test case(it block) multiple times with different set of testdata in cypress.

Please consider the below example :

`it('example test',  () => {
//first run
getOnDefaultForm.typeUserName('Name1');
getOnDefaultForm.typePassword('Pass1');
getOnDefaultForm.clickSubmit();
//second run
getOnDefaultForm.typeUserName('Name2');
getOnDefaultForm.typePassword('Pass2');
getOnDefaultForm.clickSubmit();
//third run
getOnDefaultForm.typeUserName('Name3');
getOnDefaultForm.typePassword('Pass3');
getOnDefaultForm.clickSubmit();
});`

How can I achieve this in Cypress ? Thanks in Advance!

How to mock VueAxios in jest

I want to test my Api functions which are on separate file outside vue component. Inside this methods i call api by Vue.axios, and i can't find the way to mock and test it like in this post:

How do I test axios in jest

example method:

cancelAuction: function (auction_id) {
    if (validateApiInt(auction_id)) {
      return Vue.axios.delete(`/auctions/${auction_id}`);
    }
    return {};
  },

example usage:

const response = await AuctionApi.cancelAuction(id);

Tool or Plugin service to generate Manual test cases automatically for web application?

If someone has a webpage, the usual way of testing the web site for user interaction bugs is to create each manual test case and then use selenium for automaton.

Is there a tool to create these manual testcases automatically? So if I have a webpage that gets altered, new test cases get created automatically?

How to simply unit test function that returns array of li element in Jest/React

I am trying to write a very simply unit test for a function that takes an array of objects like this:

const object = {
  id: 1,
  name: 'testy test
}

and will return an array of li elements like this:

const returnArray =[ <li id='1'>1-testy test</li> ]

my test is very simple

expect(mapFunction(object).toEqual(returnArray)

However I the results never match, the above version shows the return with line breaks in it so they do not match. I have tried using different matchers, like .toContain/.toStrictEqual/.toBe

And have tried to break down expected return array to two variables and test the return array contains them.

using equality matchers results in the returned having line breaks in it that do not match the expected.

Using .toContain results in a console log showing the array matching but the test fails.

I do not want to render the list yet and I know the function works correctly.

What is the correct way to test the return array will match the expected.

The function:

arrayOfObjects.map(object => return <li id={object.id}>{object.id}-{object.name}</li>)

How to verify stringified json in pact

I am trying to build a pact between two services using asynchronous communication.

This is the code I used for generate the pact:

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "provider", providerType = ProviderType.ASYNCH)
public class StringifiedPactTest {

    @Pact(consumer = "consumer", provider = "provider")
    public MessagePact generatePact(MessagePactBuilder builder) {
        return builder.hasPactWith("provider")
                .expectsToReceive("A valid aws sns event")
                .withContent(new PactDslJsonBody().stringType(new String[]{"MessageId", "TopicArn"}).stringValue("Message", new PactDslJsonBody().stringType("Value", "Foo").toString()))
                .toPact();
    }

    @Test
    @PactTestFor(pactMethod = "generatePact")
    public void buildPact(List<Message> messages) {

    }
}

And the generated pact is

{
  "consumer": {
    "name": "consumer"
  },
  "provider": {
    "name": "provider"
  },
  "messages": [
    {
      "description": "A valid aws sns event",
      "metaData": {
        "contentType": "application/json"
      },
      "contents": {
        "TopicArn": "string",
        "Message": "{\"Value\":\"Foo\"}",
        "MessageId": "string"
      },
      "matchingRules": {
        "body": {
          "$.MessageId": {
            "matchers": [
              {
                "match": "type"
              }
            ],
            "combine": "AND"
          },
          "$.TopicArn": {
            "matchers": [
              {
                "match": "type"
              }
            ],
            "combine": "AND"
          }
        }
      }
    }
  ],
  "metadata": {
    "pactSpecification": {
      "version": "3.0.0"
    },
    "pact-jvm": {
      "version": "4.0.10"
    }
  }
}

This means the producer should have a "Message" that matches {"Value" : "Foo"}, any other combination like {"Value" : "Bar" } won't be successful. Is there any way to add matching rules inside a stringified json? Thanks!

call function when all tests are finished running

I want to run some cleanup code like stopping database service. I am currently using std::sync::Once::call_once like this:-

fn init() {
    INIT.call_once(|| {
        //start database
    });
}

I put this function in each test. But now I want to run another function which will be executed when all tests are finished. How can I do that ?

Karate UI Scroll till the end of dynamic page

Can it be possible in karate to scroll till the end of a dynamic page I tried using scroll and wait but it's not working?

mardi 28 juillet 2020

Jasmine spec timed out. Resetting the WebDriver Control Flow. angular 9 testing

I am facing issue while E2E test case (earlier it was working..)

A Jasmine spec timed out. Resetting the WebDriver Control Flow.
    × when login is successful — user object should be set in storage
      - ScriptTimeoutError: script timeout
        (Session info: chrome=84.0.4147.89)
        (Driver info: chromedriver=84.0.4147.30 (48b3e868b4cc0aa7e8149519690b6f6949e110a8-refs/branch-heads/4147@{#310}),platform=Windows NT 6.3.9600 x86_64)

and this is the test case

it("when login is successful — user object should be set in storage", async () => {
    await loginPage.fillCredentials(loginPage.credentials.correct);

    // wait until redirected to new page
    const EC = protractor.ExpectedConditions;
    const elm = await element(by.css(LOGIN_CSS.LOGO_TEXT));
    browser.wait(EC.presenceOf(elm), 40000);

    const _currentUser = await helperService.getLocalStorageObject("currentUser");
    console.log("_currentUser", _currentUser);

    expect(_currentUser).toBeDefined();

    const currentUser = JSON.parse(_currentUser);
    console.log("currentUser", currentUser);
    expect(currentUser.Id).toBeDefined();
    expect(currentUser.Name).toBeDefined();
});

In application, after login it redirects to the page and set user to local storage.

// wait till `LOGIN_CSS.LOGO_TEXT` is available on next page after login
const EC = protractor.ExpectedConditions;
const elm = await element(by.css(LOGIN_CSS.LOGO_TEXT));
browser.wait(EC.presenceOf(elm), 40000);

what can be the issue?

Monitoring and Testing in microservice-based systems

Monitoring and Testing in microservice-based systems.

Hi folks, I want to take the practitioner's perspective about the following two questions for a research study. Please share your experience!

  1. Why monitoring and testing of the microservices-based system are important?
  2. How monitoring and testing of the microservices-based system are different from monolithic and SOA based systems?

Fixture order of execution in pytest

I'm new to using Pytest. I'm a little confused about what's the appropriate use of fixtures and dependency injection for my project. My framework is the following:

conftest.py

@pytest.fixture(scope="session")
def test_env(request):
//some setup here for the entire test module test_suite.py

@pytest.fixture(scope="function")
def setup_test_suite(test_env): 
//some setup that needs to be done for each test function
//eventually parameterize? for different input configuration


test_suite.py
def test_function(setup_test_suite)
//some testing code here
  1. What's the difference between putting the setup function in conftest.py or within the test suite itself?
  2. I want the setup of the testing environment to be done once, for the entire session. If setup_test_suite is dependent on test_env, will test_env execute multiple times?
  3. If I were to parameterize setup_test_suite, what would be the order of calling the fixtures?

Assert one of multiple classes/ids in CasperJS tests

I have an existing CasperJS test script in the following format:

casper.test.begin('SIDEBAR', function (test) {
    var iconExists = casper.exists('#sideNavIcon');
    test.assert(iconExists, 'Icon exists on the sidebar');

    casper
        .waitForSelector('#sidebar-spinner')
        .then(function () {
            test.assertVisible('.sidebar-notifications', 'Notifications are visible on the sidebar');
            test.assert(
                casper.getElementInfo('#sidebar-notifications-unread').text === casper.getElementInfo('.header-alerts-unread').text,
                'The unread counts on the sidebar and header match'
            );
        });
};

I am now trying to modify the tests to include multiple classes or Ids for each of the assert statements, and only one of them can be present. I believe I could do something like the following:

casper.test.begin('SIDEBAR', function (test) {
    var iconExists = casper.exists('#sideNavIcon') || casper.exists('#alertsIcon');
    test.assert(iconExists, 'Icon exists on the sidebar');
    casper
        .waitForSelector('#sidebar-spinner')
        .then(function () {
            test.assertVisible('.sidebar-notifications', 'Notifications are visible on the sidebar') || test.assertVisible('.sidebar-alerts', 'Notifications are visible on the sidebar');
            test.assert(casper.getElementInfo(...).text == ....) || test.assert(casper.getElementInfo(...).text == ....)

The above solution looks very 'dirty' and I am also having trouble to get this to work with the last assert. Is there a better way of achieving this? Any help would be much appreciated.

Jasmine Testing: Spy.and.returnValue() not working

I'm trying to implement tests for my javascript using Jasmine, but I'm running into some problems with .and.returnValue. This is my test:

describe("Test the ResultsPage Function", () => {
let dummyContainer;
let htmlResponse;
let htmlCode;

beforeEach(() => {
    console.log("Before Each is Running");
    htmlResponse = new Response('<div><h id="pick"></h><h1 id="rating"></h1><div id="photo"></div></div>');
    htmlCode = '<div><h id="pick"></h><h1 id="rating"></h1><div id="photo"></div></div>';
    spyOn(window, 'resultsPage').and.callThrough();
    dummyContainer = document.createElement('div');
    spyOn(document, 'getElementById').withArgs('page-container').and.returnValue(dummyContainer);
    console.log("Spy Made");
    console.log(document.getElementById("page-container"));
    spyOn(window, 'loadImage');
    spyOn(window, 'fetch').and.returnValue(Promise.resolve(htmlResponse));
});

it("Test that the function runs correctly", () =>{
    resultsPage("restaurant", "5", "https://www.w3schools.com/images/lamp.jpg");
    expect(fetch).toHaveBeenCalledWith("../results.html");
    expect(resultsPage).toHaveBeenCalled();
});

it("Test that the function alters the DOM correctly", () =>{
    console.log("Test is running")
    resultsPage("restaurant", "5", "https://www.w3schools.com/images/lamp.jpg");
    expect(fetch).toHaveBeenCalledWith("../results.html");
    expect(resultsPage).toHaveBeenCalled();
    expect(dummyContainer.innerHTML).toEqual(htmlCode);
});

});

And this is the function I am trying to test:

function resultsPage(name, rating, photoUrl) {
fetch(`../results.html`)
    .then((html) => html.text())
    .then((html) => {
        let temp = document.getElementById("page-container");
        console.log(temp);
        document.getElementById("page-container").innerHTML = html;
        document.getElementById("pick").innerText = name;
        document.getElementById("rating").innerText = rating;
        loadImage(photoUrl);
    });

}

I added the log statements to verify the behavior of the test as it progresses and I can see that when 'document.getElementById("page-container")' is called in the beforeEach, it correctly returns the spy. However, when it is run in the resultsPage function itself, it only returns null Console Print Statements Any reason that the .and.returnValue() behavior is not working?

MockK - cannot mock same function twice

I am trying to test the getTopicNames function (below) in two scenarios: If it succeeds and if it does not succeed.

fun getTopicNames(): Either<Exception, Set<String>> =
    try {
        adminClient.listTopics()
            .names()
            .get()
            .right()
    } catch (exception: ExecutionException) {
        exception.left()
    }

This is the test class in which I am doing those two scenarios. If I run each test individually, they both suceed. If I run the entire class the second to execute fails because for some reason the previous mock on adminClient.listTopics() is being retained.

These are the versions for everything involved:

  • kotlin: 1.3.72

  • koin: 2.1.6

  • junit: 5.6.1

  • mockk: 1.10.0

class TopicOperationsTest {

    @BeforeEach
    fun start() {
        val testModule = module(createdAtStart = true) {
            single { mockk<AdminClient>() }
        }
        startKoin { modules(testModule) }
    }

    @AfterEach
    fun stop() {
        stopKoin()
    }

    @Test
    fun `getTopicNames() returns a Right with the topics names`() {
        val adminClient = get(AdminClient::class.java)

        val listOfTopicsToReturn = mockk<ListTopicsResult>()
        val expectedTopics = setOf("Topic1", "Topic2", "Topic3")

        every { adminClient.listTopics() } returns listOfTopicsToReturn
        every { listOfTopicsToReturn.names() } returns KafkaFuture.completedFuture(expectedTopics)

        println("listOfTopicsToReturn.names(): " + listOfTopicsToReturn.names())
        println("adminClient.listTopics(): " + adminClient.listTopics())
        println("getTopicNames(): " + getTopicNames())

        assertThat(getTopicNames().getOrElse { emptySet() }, `is`(expectedTopics))
    }

    @Test
    fun `getTopicNames() returns a Left if failing to get topic names`() {
        val adminClient = get(AdminClient::class.java)

        every { adminClient.listTopics() } throws ExecutionException("Some Failure", Exception())

        assertThat(getTopicNames(), IsInstanceOf(Either.Left::class.java))
    }
}

This is the error I get, caused by the fact that the test that verifies the failure is the first to run:

java.lang.AssertionError: 
Expected: is <[Topic1, Topic2, Topic3]>
     but: was <[]>
Expected :is <[Topic1, Topic2, Topic3]>
Actual   :<[]>
<Click to see difference>

Already tried clearAllMocks() on the BeforeEach method but it does not solve my problem as I just start getting:

io.mockk.MockKException: no answer found for: AdminClient(#1).listTopics()

Drag and Drop function is not working in selenium Edge Browser

Following is HTML for source element:

<div title="" class="dragItem row " id="DocSelected-1" draggable="true" type="11" data-content="Salary Slips" data-draggable="item" document-required="1" state="notVerified" accountid="0">
                                    <span class="col-xs-10 dl-no-padding">
                                        <span>Salary Slips</span>
                                    </span>

and following is HTML for target element:

    <div class="recievedDocumentContainer" id="div3" data-draggable="targetRD">
 <p class="col-heading">                    
Received Documents                
</p>                
<div class="recievedDocumentsDivforScroll">                    
<div class="slimScrollDiv" style="width: auto; height: 67px; overflow: hidden; position: relative;">
<div class="recievedDocs" style="width: auto; height: 67px; overflow: hidden;">                    
</div>

Below are the different methods tried to achieve drag and drop function but nothing worked.

All the methods are getting passed in console but drag and drop is not performed.

//method 1 - action class
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            IWebElement to = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            Actions act = new Actions(driver);
            act.DragAndDrop(from, to);
            act.Build().Perform();
            System.Threading.Thread.Sleep(5000);
        Assert.IsTrue(driver.FindElement(By.XPath("//[@id='DocValidatePopup']/div/div/h3/b")).Displayed);


//method 2 -action class with x/y offset
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            Actions act = new Actions(driver);
            act.DragAndDropToOffset(from, 1300, 234).Build().Perform();

 //method 3
            var ele1 = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            var ele2 = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            DragAndDrop(ele1, ele2);
            void DragAndDrop(IWebElement element1, IWebElement element2)
            {
                var builder = new Actions(driver);
                var dragAndDropbuilder.ClickAndHold(element1).MoveToElement(element2).Release(element2).Build();
                dragAndDrop.Perform();
            }

 //method 4
            var ele1 = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            var ele2 = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            DragAndDrop(ele1, ele2);
            void DragAndDrop(IWebElement element1, IWebElement element2)
            {
                var builder = new Actions(driver);
                var dragAndDrop = builder.ClickAndHold(element1).MoveToElement(element2, 1300,234).Release(element1).Build();
                dragAndDrop.Perform();

            }

 //method 5
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            IWebElement to = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            Actions act = new Actions(driver);
            act.ClickAndHold(from).MoveToElement(to).Release().Build();

 //method 6 Javascript
            String java_script = "var src=arguments[0],tgt=arguments[1];var dataTransfer={dropEffe" + "ct:'',effectAllowed:'all',files:[],items:{},types:[],setData:fun" + "ction(format,data){this.items[format]=data;this.types.append(for" + "mat);},getData:function(format){return this.items[format];},clea" + "rData:function(format){}};var emit=function(event,target){var ev" + "t=document.createEvent('Event');evt.initEvent(event,true,false);" + "evt.dataTransfer=dataTransfer;target.dispatchEvent(evt);};emit('" + "dragstart',src);emit('dragenter',tgt);emit('dragover',tgt);emit(" + "'drop',tgt);emit('dragend',src);";
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            IWebElement to = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
            jse.ExecuteScript(java_script, from, to);

  //method 7 Javascript
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            IWebElement to = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
            jse.ExecuteScript("function createEvent(typeOfEvent) {\n" + "var event =document.createEvent(\"CustomEvent\");\n" + "event.initCustomEvent(typeOfEvent,true, true, null);\n" + "event.dataTransfer = {\n" + "data: {},\n" + "setData: function (key, value) {\n" + "this.data[key] = value;\n" + "},\n" + "getData: function (key) {\n" + "return this.data[key];\n" + "}\n" + "};\n" + "return event;\n" + "}\n" + "\n" + "function dispatchEvent(element, event,transferData) {\n" + "if (transferData !== undefined) {\n" + "event.dataTransfer = transferData;\n" + "}\n" + "if (element.dispatchEvent) {\n" + "element.dispatchEvent(event);\n" + "} else if (element.fireEvent) {\n" + "element.fireEvent(\"on\" + event.type, event);\n" + "}\n" + "}\n" + "\n" + "function simulateHTML5DragAndDrop(element, destination) {\n" + "var dragStartEvent =createEvent('dragstart');\n" + "dispatchEvent(element, dragStartEvent);\n" + "var dropEvent = createEvent('drop');\n" + "dispatchEvent(destination, dropEvent,dragStartEvent.dataTransfer);\n" + "var dragEndEvent = createEvent('dragend');\n" + "dispatchEvent(element, dragEndEvent,dropEvent.dataTransfer);\n" + "}\n" + "\n" + "var source = arguments[0];\n" + "var destination = arguments[1];\n" + "simulateHTML5DragAndDrop(source,destination);", from, to);

  //method 8
            IWebElement from = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span"));
            IWebElement to = driver.FindElement(By.XPath("//*[@id='div3']/div[1]/div/div[1]"));
            var builder = new Actions(driver);
            builder.ClickAndHold(from);
            builder.MoveToElement(to, 1300, 234);
            builder.Perform();
            System.Threading.Thread.Sleep(2000);
            builder.Release(to); builder.Perform();

Kindly suggest any other alternative methods to perform drag and drop.

Used:

  • Language - C#
  • Selenium Webdriver
  • Edge Browser

Factory Boy Build JSON String from Another Factory

I am trying to use Factory Boy in order to generate test data for my test suite. My data consists of JSON objects with a body field that contains an escaped JSON String (example below). I also included example python dataclasses and Factory Boy factories for this example data.

Note: For this example, I am skipping the setup of fake data using Faker or the built-in fuzzers to simplify the question. In a more realistic use case, fields like eventtime, deviceid, enqueuedTime would contain rondomized values (using a fixed seed for the randomness)

I am struggling to figure out how to generate the inner JSON object and stringify it using Factory Boy.

An example data point:

{
    "body": "{\"eventdata\":{\"count\":\"1\",\"sourceid\":\"0\",\"updatetime\":\"1579797993879\",\"description\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit\"},\"eventtime\":\"2020-01-23T16:46:35.522Z\",\"eventversion\":\"1.0.0\",\"eventtype\":\"FooEventType\",\"deviceid\":\"000000123ABC\"}",
    "partition": "30",
    "enqueuedTime": "2020-01-23T16:46:35.594Z",
    "event_type": "FooEventType",
    "year": 2020,
    "month": 1,
    "day": 23}

My Python dataclasses and Factory Boy factories:

from dataclasses import dataclass
import factory

@dataclass
class Root:
  body: str
  partition: str
  enqueued_time: str
  event_type: str
  year: int
  month: int
  day: int

@dataclass
class Eventdata:
  count: str
  sourceid: str
  updatetime: str
  description: str

@dataclass
class Body:
  eventdata: Eventdata
  eventtime: str
  eventversion: str
  eventtype: str
  deviceid: str

class EventdataFactory(factory.Factory):
  class Meta:
    model = Eventdata
  count = "1"
  sourceid = "0"
  updatetime = "1579797993879"
  description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"

class BodyFactory(factory.Factory):
  class Meta:
    model = Body
  eventdata = factory.SubFactory(Eventdata)
  eventtime = "2020-01-23T16:46:35.522Z"
  eventversion = "1.0.0"
  eventtype = "FooEventType" # Note: It is the same in Root
  deviceid = "000000123ABC"

class RootFactory(factory.Factory):
  class Meta:
    model = Root
  body = "Escaped JSON String" # Need help here
  partition = "30"
  enqueuedTime = "2020-01-23T16:46:35.594Z"
  event_type = "FooEventType" # Note: It is the same in Body
  year = 2020
  month = 1
  day = 23

How do I create the escaped JSON string build from 'BodyFactory' for the body field in 'RootFactory'?

How do I approach this python test?

I have a function inside a class, that calls other functions and does some stuff until it obtains two variables, A and B:

Class NumberLogic:
    def compare():
    #do stuff_
    A=#do stuff__
    B=#do stuff___
    if A<B:
        return 1
    else:
        return 2

I would like to test this function compare() but give values directly from A and B so only the if condition is tested, I am not sure if this is possible and the rest of the code can be mocked so when I call someting like

assert 1 == NumberLogic.compare()

Gradle: How can I run a specific (architecture) test for each subproject?

I have a Gradle monolith project with around 50 subprojects. I'd like to ensure that the code in each subproject conforms to a specific rule, for example that each class named *Foo is annoted with Bar.

I already wrote a test that successfully scans the classpath and asserts the property I'm interested in.

Where do I put this code so that it is executed for the whole project, either individually for each subproject, or once for the whole codebase?

I know about test fixtures, so I could easily provide the logic in a class that is accessible by all subprojects. However, I'd still need to write a test class that runs the shared code, which I'd have to do for each of my subprojects.

How can I avoid this duplication? I'm looking for something like this:

subprojects {
    additionalTestsFrom project(':architecture-tests')
}

Run maven test in parallel without waiting for sibling module dependencies

I have a multi-module maven project in which the modules have quite a few dependencies between them. I have tried running my tests in parallel, but since the modules are not very well thought off and are highly dependent on each other, I basically have no time gain, since they still end up executing sequentially.

Now, before running the tests altogether I have a phase where I build the project so that I may apply other static analysis tools in parallel to my testing.

My question is: Given that my modules are already compiled, can I not tell maven to run tests in parallel using these precompiled classes and not wait for dependant modules to run their tests first? E.g. currently if I have a module A depending on module B, module B would execute all its tests first before A could start. Since I have A and B already built, I have no need to keep this limitation.

The way I run tests currently is something like: mvn -f project-parent/pom.xml surefire:test where project parent is a module parenting all my other modules. I have ommited profiles and other parameters for brevity.

Thanks!

Edit: I am trying to avoid class/suite level parallelization at this point using junit or surefire and would just like to test modules in a parallel way.

Intellij IDEA skipping closing bracket on test coverage

I'm working on a Grails project. When I run unit tests with test coverage, it skips the enclosing brackets from code coverage. It happens for all methods. I tried varying the coverage runner by using JaCoCo and Emma, but no success.

How can I fix this? Why do those brackets get added to total coverage anyway? It's super annoying.

enter image description here

Can we override 'expect' method of testcafe's TestController

I am looking for a way to override expect method for TestController. My idea is existing tests whoever used t.expect method, I want to perform additional steps in those cases. I came up with below sample code but testcafe runtime fails with below error TypeError: Cannot read property '_expect$' of undefined

sample code attempting to override:

import { Selector } from "testcafe";

fixture`Getting Started`.page`http://devexpress.github.io/testcafe/example`;

test("My first test", async (t) => {
  t = modify(t);
  await t.typeText("#developer-name", "John Smith").click("#submit-button");

  // Use the assertion to check if the actual header text is equal to the expected one
  await t
    .expect(Selector("#article-header").innerText)
    .eql("Thank you, John Smith!");
});

function modify(t) {
  let prevExpect = t.expect;
  t.expect = (param) => {
    console.log("modified expecte has been used");
    return prevExpect(param);
  };
  return t;
}

Also, when using t.click(Selector(...).expect(...), It doesn't use my override expect. How to make it work in the call chain as well?