jeudi 30 avril 2020

C# set foreground window from Console process

This is for a C# xUnit test project that spawns processes such as notepad.exe, winword.exe and winver.exe. I need to switch between these applications for the test (make them the foreground window).

So far, I have tried SetForegroundWindow, SwitchToThisWindow, SetActive, SetFocus etc from user32.dll, which doesn't work. I've tried using the AttachThreadInput trick, but it doesn't seem to work (maybe im doing it wrong? im using it from a console application after all). I've also tried the press alt then switch method, but I do not want to do it this way (notepad eats the alt).

Time out error when executing Jest test with puppeteer

have a small suite of tests based on Puppeteer with Jest, and I can't get rid of the following problem

× test page header logo (5019ms)

  ● test page header logo

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

      at node_modules/jest-jasmine2/build/queue_runner.js:72:21   
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:633:19)

the test code

test("test page header logo", async () => {

  const browser = await puppeteer.launch({ headless: false });

  const page = await browser.newPage();

  await page.goto("localhost:3000"); // our react app;

  const text = await page.$eval("a.brand-logo", (el) => el.innerHTML);

  expect(text).toEqual("Logo");
});


Jest & Enzyme. Find amount of all elements inside wrapper

In jest & enzyme. How to find amount of all elements (children, children's children etc.) inside wrapper. wrapper.children().length outputs only direct children of wrapper

.click() command in Cypress is not performing its function

This is my first time using Cyrpress, and I am trying to run a test for my React app. The test is after a name is entered in the modal, the submit button will be clicked and you'll be taken to the homepage. However, the .click function is not working, at least I think it isn't since the modal is still there with the name on it. Can someone tell me what I am doing wrong and how to fix it?

This is how I wrote the test:

   **fourth.spec.js**
        describe ('UI tests', () => {
            it('should navgitate to landing page after submitting with button', () =>{
                const text = "Christian"
                cy.visit('/')
                cy.get('.new').type (text).should ('have.value', text)
                .click()
            })
        })

This is how I have the button setup for my modal

 <div className="my-modal">
         <h1>Welcome!</h1>
            <p>Please enter your name</p>
               <form>  
                 <input 
                     autoFocus
                     className="new task"
                     placeholder="Name"
                     type="text" 
                     name="firstName" 
                     onChange={this.inputChange}>
                 </input>
               </form>
               <button  
                  className="modal-btn"
                  type="button" 
                   disabled={!this.state.firstName} 
                   onClick={this.displayNameHandler}>
                   Submit
               </button>
    </div>

enter image description here

Generating direct invite link for Beta testing in Testflight

I have an app which I have on testflight but I want to allow people to register and receive a beta invite unique to that registration so I do not have a public link

is there any software or any API's that exist already in the wild that can help me achieve this?

Thanks in advance.

Python: test links, collect the path of broken links

I did a script that collect all the links from my website (internal and external) and give me the broken links.

Here is my code, it is working well:

import requests
# from urllib.parse import urljoin
from urlparse import urlparse, urljoin
from bs4 import BeautifulSoup
import sys

# initialize the set of links (unique links)
internal_urls = set()
external_urls = set()
# number of urls visited so far will be stored here
total_urls_visited = 0
total_broken_link = set()
output = 'output.txt'

def is_valid(url):
    """
    Checks whether `url` is a valid URL.
    """
    parsed = urlparse(url)
    return bool(parsed.netloc) and bool(parsed.scheme) 
    """
    Almost any value is evaluated to True if it has some sort of content.
    Every Url should follow a specific format: <scheme>://<netloc>/<path>;<params>?<query>#<fragment>
    Example: http://www.example.com/index?search=src
    Here, www.example.com is your netloc, while index is the path, 
    search is the query parameter, and src is the value being passed along the parameter search.
    This will make sure that a proper scheme (protocol, e.g http or https) and domain name exists in the URL.
    """

def get_all_website_links(url):
    """
    Returns all URLs that is found on `url` in which it belongs to the same website
    """
    # all URLs of `url`, we use python set() cause we don't redondant links
    urls = set()
    # domain name of the URL without the protocol, to check if the link is internal or external
    domain_name = urlparse(url).netloc
    #Python library for pulling data out of HTML or XML files
    soup = BeautifulSoup(requests.get(url).content, "html.parser")

    # print(soup.prettify()) #test if the html of the page is correctly displaying
    # print(soup.find_all('a')) #collect all the anchor tag

    for a_tag in soup.findAll("a"):
        href = a_tag.get("href")
        if href == "" or href is None:
            # href empty tag
            continue
        href = urljoin(url, href) #internal urls
        #print(internal_urls)
        # print('href:' + href)
        if not is_valid(href):
            # not a valid URL
            continue
        if href in internal_urls:
            # already in the set
            continue
        if domain_name not in href:
            # external link
            if href not in external_urls:
                # print("External link:" + href)
                # print((requests.get(href)).status_code)
                is_broken_link(href)
                external_urls.add(href)
            continue
        # print("Internal link:" + href)
        # print((requests.get(href)).status_code)
        is_broken_link(href)
        urls.add(href) #because it is not an external link
        internal_urls.add(href) #because it is not an external link 
    return urls

def is_broken_link(url):
    if ((requests.get(url)).status_code) != 200:
        #print("This link is broken")
        print(url.encode('utf-8'))
        total_broken_link.add(url)
        return True
    else:
        #print("This link works well")
        return False


def crawl(url, max_urls=80):
    """
    Crawls a web page and extracts all links.
    You'll find all links in `external_urls` and `internal_urls` global set variables.
    params:
        max_urls (int): number of max urls to crawl.
    """
    global total_urls_visited
    total_urls_visited += 1
    links = get_all_website_links(url)
    for link in links:
        if total_urls_visited > max_urls:
            break
        crawl(link, max_urls=max_urls)


if __name__ == "__main__":
    crawl('https://www.example.com/')

    print('Total External links:' + str(len(external_urls)))
    print('Total Internal links:' + str(len(internal_urls)))
    print('Total:' + str(len(external_urls) + len(internal_urls)))
    print('Be careful: ' + str(len(total_broken_link)) + ' broken links found !')

When I am running my script, it returns me all the broken links and also the number of broken links.

But I also want to display the path of each broken link.

For example, if I find this broken link https://www.example.com/brokenlink (internal broken link) or this one https://www.otherwebsite.com/brokenlink (external broken link).

I want to know where those broken links are called in my code, I mean in which page in order to solve the problem. If I know where are these broken links in my code I can easily find them and remove them in order not to have this issue anymore.

So I want this script to allow me to display each broken link with its path and then the number of broken links.

I hope it was clear enough!

GitHub: link to files in GitHub Project

I create a tutorial, where I want to introduce some testing frameworks like Mockito, WireMock and EasyMock. I want to explain it step by step. Additionaly I want to provide examples, where the reader of the tutorial can try to recreate these. Therefore I want to to give them the opportunity to look into my source code and use it when they are not able to recreate the test. And then they can use the actual version to continue and then again, when they are not able to create the next test, I want to to give them the possibility to use my new version with the new test.

My idea is to use different commits and link them to the tutorial. How can I do this or is there any better approach to reach what I just explained?

Can I use `expect.stringContaining()` inside a Jest `.toHaveBeenCalledWith()` block?

Is it possible to use expect.stringContaining() inside a Jest .toHaveBeenCalledWith() block?

I am currently using:

expect(createChatRoomMock).toHaveBeenCalledWith({
  creatorId: expect.stringContaining("user_"),
  chatRoomUuid: expect.stringContaining("chatRoom_"),
});

But this fails with:


    - Expected
    + Received


    Object {
  -   "chatRoomUuid": StringContaining "chatRoom_",
  -   "creatorId": StringContaining "user_",
  +   "chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
  +   "creatorId": "user_nCQsasvYirUwwoEr3j8HsC",
    },

This is odd, as you can see from the error, the recieved strings match what's expected

I've also tried:

expect(createChatRoomMock).toHaveBeenCalledWith({
  creatorId: expect.stringMatching(/user_.*/),
  chatRoomUuid: expect.stringMatching(/chatRoom_.*/),
});

With the same results as shown above.

How can I use expect.stringContaining() inside a Jest .toHaveBeenCalledWith() block?

Test a function called within a *ngFor and a FormGroup in Angular?

I am trying to unit test an Angular application, but I have been facing some problems with the variables within the components.

Here I have a *ngFor and a FormGroup and each one of them is causing an issue when I run the test, the second one gives me these error: Cannot read property '0' of undefined, the first one also gives me the same error, but only if I define component.parentProps.activeStepIndexSkills as 0, if I pass to it any other value over 0 I'll get: Cannot read property 'textContent' of null.

my test script (I am testing 'function onGoToStep':

describe('ListEditComponent', () => {
  let component: ListEditComponent;
  let fixture: ComponentFixture<ListEditComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [ ListEditComponent ]
    })
    .compileComponents();
  });

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

  it('should create list edit', () => {
    expect(component).toBeTruthy();
  });

  it('function onGoToStep', fakeAsync(() => {
    const i = 1
    component.parentProps =  { applicationsData: [''], editMode: 1,  activeStepIndexSkills: i}
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement
    expect(compiled.querySelector('.teste').textContent).toContain('teste');

  }))

});

This is a sample of my template:

<ng-container *ngIf="parentProps" >
  <div *ngIf="parentProps.editMode === 1" >
    <br />
    <form class="detalhes-container">
      <ng-container *ngFor="let info of parentProps.applicationsData; let i = index; trackBy: trackByFn">
        <!--Test container-->
        <ng-container *ngIf="i === parentProps.activeStepIndexSkills">
          <p id="teste" >teste</p>
        </ng-container>
        <!---->
        <div
          class="detalhes-bloco"
          *ngIf="parentProps.activeStepIndexSkills === i"
          [formGroup]="parentProps.masterFormEdit[i]"
        >
          <div
            class="detalhes-conhecimento-container"
            formGroupName="conhecimento"
          >
          <!-- <p class="teste" >teste</p> -->
          </div>
        </div>
      </ng-container>
    </form>
   </div>
</ng-container>

As it can be seen I have a test container before the FormGroup and a p tag after it, both for testing purposes. I realized that if I replace i for an integer and set component.parentProps.activeStepIndexSkills with the same value in my spec.ts file I can reach the element p inside the test container, what made me think that I have not been able to get the element because i doesn't exist inside the test, but I have not idea how to fix this. I tried to mock the value of i using component, but it doesn't work. So, is it my theory correct? If it is, how could I fix this?

But as I said, I also have a second problem with parentProps.masterFormEdit[i], which returns Cannot read property '0' of undefined, in this case I couldn't tell if the issue is with i or with masterForm, because I was trying to solve a problem at a time, but since I am here I believe it is worth try to get an answer for this as well.

There is one thing that made me even more confused, I have another component very similar to this one of the question and I am not getting none of these errors.

<div *ngIf="parentProps" class="detalhes-container">
  <div *ngFor="let info of parentProps.applicationsData; let i = index; trackBy: trackByFn">
    <ng-container *ngIf="i === parentProps.activeStepIndexSkills">
      <div class="detalhes-bloco">
        <thead class="detalhes-conhecimento-header">
          <th>Tecnologia</th>
          <th>Nível</th>
        </thead>
        <div class="detalhes-icons">
          <p class="modo-edicao-icon" *ngIf="parentProps.editMode === 1">MODO EDIÇÃO</p>
          <i class="material-icons edit-btn" (click)="onEdit()">edit</i>
        </div>
      </div>
    </ng-container>
  </div>
</div>

spec.ts:

it('function onEdit', fakeAsync(() => {
    component.parentProps =  { applicationsData: [''], activeStepIndexSkills: 0 }
    fixture.detectChanges();

    spyOn(component, 'onEdit');

    let button = fixture.debugElement.nativeElement.querySelector('.edit-btn');
    button.click();
    tick();
    expect(component.onEdit).toHaveBeenCalled();

  }))

As you can see I also have a *ngFor and a *ngIf using an i and it works fine.

How to run same set of test for anonymous user and logged in user?

I have a simple MovieDB app written in Django where webpages differ slightly between logged in view and guest user view.

I have a movies list page which doesn't change for logged in user and anonymous user except for sign-in/register links to sign-out. I am currently testing template used, no. of movies listed, movie title, nav-bar links (home, search page, login/register, sign-out, user account). I want to write tests to check these for both type of user only once.

How can I open a React combobox and select one value in testCafe?

I have a combo-box using react:

<div class="Select is-clearable is-searchable Select--single">
    <div class="Select-control">
        <div class="Select-multi-value-wrapper" id="react-select-4--value">
            <div class="Select-placeholder">Select a reseller...</div>
            <div class="Select-input" style="display: inline-block;"><input
                    aria-activedescendant="react-select-4--value" aria-expanded="false" aria-haspopup="false"
                    aria-owns="" role="combobox" value="" style="box-sizing: content-box; width: 5px;">
                <div
                    style="position: absolute; top: 0px; left: 0px; visibility: hidden; height: 0px; overflow: scroll; white-space: pre; font-size: 14px; font-family: Roboto, sans-serif; font-weight: 400; font-style: normal; letter-spacing: normal; text-transform: none;">
                </div>
            </div>
        </div><span class="Select-arrow-zone"><span class="Select-arrow"></span></span>
    </div>
</div>

In my code, I can "open" the combo-box, but I can't select one option:

    test('Create a new Quote...', async t => {

        //open the combo-box
        await t.click(Selector('.Select-arrow-zone')).wait(3000);

        //try to select the second value, that is "Demo"
        await t.click(Selector('input').withAttribute('aria-activedescendant','react-select-4--option-1')).wait(3000);

        await t.expect(Selector('button').withExactText('Add Item').exists).ok();
    });

The second click fail, with the message:

   1) The specified selector does not match any element in the DOM tree.

         | Selector('input')
       > |   .withAttribute('aria-activedescendant', 'react-select-4--option-1')

What should I do?

Thanks!

Cypress code coverage of external custom angular module used in app component

I am using cypress for end to end testing. I wanted to get code coverage of angular component files which are being imported from custom angular packages we have created and deployed in dist folder, this imported package contains all the components, services, akita store and is being used in app component, routing. Currently cypress only covers code for ts files present in src folder which seems to be of no use as it does show coverage of actual components which were imported.

Test functionality Equivalence Post vb.net to c# migration

I have a huge codebase migrated from vb.net to c#. Can you please suggest how can I automate to test functional equivalence between the vb.net and c#

Primarily I am looking for computer vision technique image comparison - For example may be using computer vision technique..compare a specific form screenshot in vb.net against the same form screenshot in c# and check if all the buttons, text boxes, labels are migrated. The screens are not perfectly aligned therefore the image comparison results are not good.

Or there can be other any way

Request for help. Thanks

Scalatest: Combine Assertions

I've just started using WordSpec and I've come across a problem I can't get around.

I'd like to assert on two separate values in one unit test. Suppose I have val result1 and val result2, I need the first to take on a particular value AND the second to take on another particular value.

This would be really easy if it was possible to concatenate/reduce/fold on assertions but I don't think I can. Perhaps something like this:

result1 should be (1) ++ result2 should be (2)

The result would be a new assertion which is only true if both assertions are true.

If I write them as below, it will only take the last value.

result1 should be (1)
result2 should be (2)

Does anyone know a way around this?

In TestCafe, Is there a way to fetch the token set by USER ROLE functionality?

Introduction

I'm using TestCafe and there are some redundant steps I'm using which can be easily replaced by making direct API calls to save a lot of time. Also, in my current tests, I'm using UserRole functionality of TestCafe to avoid login in every tests.

What's the problem?
To make API calls, I would need a token. UserRole already saves it in a cookie but I can't find a way to fetch it.

What I did so far?
I did debug test to look for cookies and I see there are a bunch of cookies in the browser but I can't see relevant which can be used as a token.

There is a way for me to get the cookie using this part of the code:

const getCookie = ClientFunction((name) => {
  const nameEQ = `${name}=`;
  const ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i += 1) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
});

but I need to know the name of the cookie which I'm not aware of how TestCafe had set it.

REQUIREMENT STABILITY INDEX IN SOFTWARE TESTING

Is anyone guide me how to integrate the matrix requirement stability index in a testlink tool, or is there anyway to get the requirement stability index matrix.

Is it possible to test JAR desktop app using cucumber?

I have executable desktop app in JAR file which was written in JAVA. Is it possible to create automated BDD tests using cucumber and gherkin? I can't find any tutorial. I did it by Cucumber in IntelliJ but tested web application using webdriver, so it's very popular.

How to mock axios with jest and enzyme?

How to mock axios requests with jest and enzyme?

Hi. I have simple Rails API and i want to test my axios requests.

How to mock post, delete and e.t.c?

My goal is:

  • 1.Test response code

  • 2.Test response body

  • 3.Test that request sent only once

Here's my test:

 it('should add have ok response', async () => {
    mockAxios.get.mockImplementationOnce(() =>
      Promise.resolve({
        list: {
          board_id: 1,
          title: "Sample list"
        }
      })
    );

    const response = await postList(1);

    expect(response).toEqual({ board_id: 1, title: "Sample list" });
    expect(mockAxios.post).toHaveBeenCalledTimes(1);
    expect(mockAxios.get).toHaveBeenCalledWith(
      "https://localhost:8080/api/v1/lists",
      {
        params: {
          board_id: 1,
          title: "Sample list",
        }
      }
    );
  });

And postList function:

export const postList = async (board_id) => {
  try {
    const result = await FetchHelpers.post(`${API_ROOT}/lists`, {
      list: {
        board_id: board_id,
        title: "Sample list"
      }
    });
    return result;
  } catch (error) {
    console.error(error);
  }
}

But i get this error in test:

  ● CreateListButton › should add have ok response

    expect(received).toEqual(expected) // deep equality

    Expected: {"board_id": 1, "title": "Sample list"}
    Received: undefined

What's wrong here and how to fix that?

How to test an AUTOSAR project?

I am very new to AUTOSAR. Currently I am on a search to find different types of testing used in AUTOSAR projects. My aim is to gain knowledge on AUTOSAR testing area. Following are the questions which I am looking to get answered. 1. What are the different areas of AUTOSAR that can be tested? 2. How to test AUTOSAR projects practically? 3. What are the tools used for AUTOSAR based project's testing? 4. How to start learning testing of AUTOSAR project? 5. Find resources available for learning AUTOSAR testing.

How do I write unit-tests for umbraco 8?

I've been trying to write unit-tests for umbraco v8 with the help of the documentation found here: https://our.umbraco.com/documentation/Implementation/Unit-Testing The tool I am using for the unit-tests is NUnit

But once I set up erverything, the tests don't get run. I don't get any error or success messages. Some help would be appreciated.

Why Angular website (irctc.co.in) require to put Script without WaitForAngularEnabled false.?

describe('Protractor Alert steps', function () {
   it('Open Angular js website Alerts', function () {
        browser.waitForAngularEnabled(false);
        browser.get("https://www.irctc.co.in/nget/train-search");
        element(by.xpath("//button[contains(text(),'Ok')]")).click();
      })
})

Now it is worked with above code but can u explain me

This is angular website then why below statement is required to be false

browser.waitForAngularEnabled(false); ?

Without above line code is not worked ...

Test system is not shown in HLK controller

I have 2 Windows 2016 server VM,

I have installed HLK Controller in 1 VM as told in the docs Step 1 https://docs.microsoft.com/en-us/windows-hardware/test/hlk/getstarted/step-1-install-controller-and-studio-on-the-test-server

I installed HLK Client on second VM as shown in Step 2 of the same doc above

But when i open HLK Studio in VM 1 I am not able to see VM 2 as test server in Configuration of HLK Studio.

Please help me resolve this , I have tried everything told in troubleshoot doc nothing worked for me

Thanks in advance

Mocked service not called

I have the following code.

SingleLoanDTO singleLoanDto;

@Mock
private SingleLoanService singleLoanService;

@Autowired
@InjectMocks
private LoanFacadeImpl loanFacadeImpl;

@Autowired
private MappingService mappingService;

setSingleLoanDto();
final long fake_id = 43252343;

Then I do some mock.

Mockito.when(
    singleLoanService.createSingleLoan(
        mappingService.mapTo(singleLoanDto, SingleLoan.class)
    )
).thenReturn(fake_id);

And assert, that it works.

Assert.assertEquals(fake_id,
    singleLoanService.createSingleLoan(
        mappingService.mapTo(singleLoanDto, SingleLoan.class)
));

However, instead of calling the mocked version, the code seems to call the real one.

java.lang.AssertionError: 
Expected :43252343
Actual   :0

The mapping by mappingService works. Why is the mocked version not called?

Loop actions until an element is no longer visible

Im trying to loop a set of actions until an element is not longer visible. I have a list of elements on a table and when i delete one (using the actions mentioned) the previous one moves to the top of the table. The element on top always has the same xpath so I am just trying to remove the top element over and over until none remain. Im currently using the following method but it only removes the first element. Ive tried to use .size() but i get an error, any ideas?

public static void rieAllcards() {
    if (firstCard.isDisplayed()) {
        //Allow RIE to Open
        clickToExpandCard();
        clickEditIcon();
        clickRemove();

    } else {

        System.out.println("Element not present");
    }

}

Residuals: ALL 349 residuals are 0: no residual degrees of freedom [closed]

I don't really how to solve this, if I take away the AvgCost/OpRev variable it works but as soon as I use that one, I get the weird output. So the problem lies probably in that column but I don't know where as I checked the column and it only contained numeric values as far as I could see.

click test

How include in jar test class and all dependency?

i use IntelliJ for a project with many modules:

  Root
    |-->Module1
    |-->Module2
    |-->Module3
    pom.xml

Eache Module has a pom.xml. and has also Test Class in src\test\java*.

My parent's pom.xml is this:

<groupId>it.anas.testSuite</groupId>
    <artifactId>TestSuite</artifactId>
    <version>0.0.1</version>
    <packaging>pom</packaging>
    <name>TestSuite</name>
    <properties>
        <maven.test.skip>true</maven.test.skip>   <---this for no run test when i do mvn install
    </properties>
    <modules>
        <module>SimulatorFrontEndTest</module>
        <module>SmartRoadApiTest</module>
        <module>SimulRestTest</module>
        <module>SmartRoadSimulatorTest</module>
    </modules>
<build>
    <pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>8</source>
                <target>8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    </pluginManagement>
</build>

with maven-jar-plugin when ido MVN PACKAGE i obtain 3 jar without test class and so dependencies.. In intelliJ i'm able to create 3 jar include test in CREATE ARTIFACT and INCLUDE TEST WITH DEPENDENCY (in each pom.xml in module). I must put dependency in parent's pom.xml or in each module pom.xml?

Unit testing kafka consumer and producer in node js

So we have a node js api which has both kafka producer and consumer. We are using kafkajs for constructing kafka client. I wanted to know if there is library for unit testing the kafka producer and consumer using which I can bring up an in-memory instance of kafka similar to in-memory DB.

How to write factories for models with has many through association?

I have three models with has many through association User model class User < ActiveRecord::Base has_many :user_projects has_many :projects, through: :user_projects end

Project model

class Project < ActiveRecord::Base has_many :user_projects has_many :users, through: :user_projects end

UserProject model class UserProject < ActiveRecord::Base belongs_to :user belongs_to :project end

How to create factories for these three models

mercredi 29 avril 2020

How to index 2 buttons with same selector in testcafe

I have 2 buttons with the following selector. How can i index them in testcafe automation?

.ng-filter-widget-row > span.ng-filter-widget-column.field-col.form-group.center-block > span > button

Android Benchmark tes - How to test application

I have created a new benchmark module in my application to test out performance of my cide.

My Project Structure is like this

Project_name -app -benchmark

app is Android application (com.android.application) while benchmark module is library (com.android.library).

I want to test my Java/Kotlin code as well as performance of my xml's inside my app module. Now in benchmark samples https://github.com/android/performance-samples the module being benchmarked is a library module.

How can I refer my Java/Kotlin files and my xml's inside my benchmark module to test the performance.

Note: I tried putting benchmark tests in the app module but it does not calculate the speed of the methods/layout inflation if used outside benchmark module.

How do i write a Unit Test for my functions that takes no parameters (Python)

I have a program which using tkinter, allows a user to input his email, and receive updates on the following technology stack (Python, Chrome, Selenium). Nevertheless, i only have one class with a lot of functions, and im trying to write unit tests for each of them, but i don't know how to start as i have not found any help trying to research on it. I'll attach a function from my code and if anyone here can help me write a unit test for it, ill use it as a guide to write my other function. Thanks in advance.

def emailGet(self):
    """
    This function shows all email in the database in an array, to make it easier to send emails to all
    available emails in the database
    :return:
    """
    # Creates the connection from the database.py
    conn = sqlite3.connect("email.db")
    c = conn.cursor()

    c.execute("SELECT *, oid FROM email")
    self.records = c.fetchall()
    logging.info("This is all the emails in the database :" + str(self.records))
    print("This is all the emails in the database : " + str(self.records))
    self.get_records = ""

    for self.i in self.records:
        self.get_records += str(self.i[0] + ",")
        # print(get_records)
        self.new_record = self.get_records[:-1]
        logging.info("New record" + str(self.new_record))
        print(self.new_record)

    conn.commit()
    conn.close()

How can I solve this Mockito MissingMethodInvocationException using when()...?

In Eclipse, using junit and Mockito. I'm trying to test that a method returns a List of certain size, but get the following error:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. 2. inside when() you don't call method on mock but on some other object.

My test:

class ValidateBookResultsTests {

public static ArrayList<Book> searchResults = new ArrayList<Book>();
public static List<Book> topFive;
public static ArrayList<String> authors = new ArrayList<String>();

public static Book book1;
public static Book book2;
public static Book book3;
public static Book book4;
public static Book book5;
public static Book book6;

@BeforeEach
public void setUp() {
    book1 = new Book("title1", authors, "publisher1");
    book2 = new Book("title2", authors, "publisher2");
    book3 = new Book("title3", authors, "publisher3");
    book4 = new Book("title4", authors, "publisher4");
    book5 = new Book("title5", authors, "publisher5");
    book6 = new Book("title6", authors, "publisher6");

    searchResults.add(book1);
    searchResults.add(book2);
    searchResults.add(book3);
    searchResults.add(book4);
    searchResults.add(book5);
    searchResults.add(book6);
}

@Test
public void returnFiveBooksFromSearchResults() {
    authors.add("John Doe");
    authors.add("Bill Gates");

    BookSearch mockBookSearch = Mockito.mock(BookSearch.class);
    Mockito.when(mockBookSearch.returnFiveBooks(searchResults)).thenReturn(topFive);

    System.out.println("return books: " + mockBookSearch.returnFiveBooks(searchResults));
    System.out.println("top: "+ topFive);

    assertEquals(topFive.size(), 5);
 }
}

My relevant code:

public static List<Book> returnFiveBooks(ArrayList<Book> searchResults) {
  Collections.shuffle(searchResults);
  topFive = searchResults.subList(0, 5);

  printFiveResults();

  return topFive; }

I've read other solutions that say to create a mock class/object, which I believe I've done with "BookSearch mockBookSearch = Mockito.mock(BookSearch.class);"

What am I missing?

What is the example for difference between integration test and regression tests?

Integration test checks that when units are combined, the systems fucntions well.

Regression tests also do the same. What is the specific difference between these?

Or does regression test look at the entire application functionality?

Subclassing in a Framework - iOS

I have a few classes in my main project target MyProject. For example: Network.swift

For testing purposes, I want to create a framework (MyMocks) that holds a bunch of Mock objects, that subclass my main project classes. For example: MockNetwork.swift

Is this possible to do, and if so, what are the proper linking steps that I need to take in my Build Phases? When I try to do this now, I have MyProject listed under Dependencies of MyMocks target.

I've then tried to use import MyProject and @testable import MyProject but both give me a ton of Undefined symbol errors.

Thank you!

Issue with Testcafe: withText is not a function

noob coder here, not pretending to be anything else.

I'm trying to write a selector in Testcafe, and according to the documentation (so far as I have understood it) this should work, however it returns an error:

await t.click(Selector('span').withtext('Pending Applications').find(a.field-link.external-link))

The error it returns is

TypeError: (0 , _exportableLib.Selector)(...).withtext is not a function

Am I doing something wrong?

React tests are not working after building it by Webpack

I have an issue that I'm spending a lot of time to seek a solution. Previously my project was build by CRA and used react-scripts. Test script was working. For test I used react-testing-library (now implemented to react by default). Actually it has changed and now app is built by webpack. I tried to implement jest and test, but I cannot configure it in proper way.

I tried:

  • install jest and babel-jest
  • add jest.config.js / jest.config.json

But still jest is sending me this information:


    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.     

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

Error shows whenever it meets React syntax

it("renders without crashing", () => {
       6 |   const div = document.createElement("div")
    >  7 |   ReactDOM.render(<App/>, div)
         |                   ^
       8 | })

My webpack config:

let path = require("path")

module.exports = {
  entry: {
    app: "./src/index.js",
  },
  output: {
    filename: "[name].js",
    path: path.resolve(process.cwd(), "name/static/js"),
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
          },
        },
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
}

package.json

{
  "name": "app-name",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "formik": "^2.1.4",
    "json-server": "^0.16.1",
    "lodash": "^4.17.15",
    "react": "^16.13.0",
    "react-input-mask": "^2.0.4",
    "react-simple-timefield": "^3.0.0",
    "reactstrap": "^8.4.1",
    "yup": "^0.28.3"
  },
  "scripts": {
    "test": "jest",
    "start-dev": "webpack --progress --colors --watch --config webpack.dev.js",
    "build": "webpack --progress --colors --config webpack.prod.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "last 1 edge version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-transform-react-jsx": "^7.9.4",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "@testing-library/dom": "^7.1.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "babel-jest": "^25.5.0",
    "babel-loader": "^8.1.0",
    "css-loader": "^3.4.2",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "jest": "^25.5.0",
    "react-dom": "^16.13.1",
    "react-snapshot": "^1.3.0",
    "react-test-renderer": "^16.13.1",
    "style-loader": "^1.1.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-merge": "^4.2.2"
  }
}

},

My purpose is to be available to run tests with this configuration.

Run Tensorflow unit tests for a single file, but output nothing

I want to run unit test for a single file in TensorFlow. I use this command:

bazel run -c opt //tensorflow/core/kernels:unique_op_test

But the result is:

INFO: Found 1 target...
Target //tensorflow/core/kernels:unique_op_test up-to-date:
  bazel-bin/tensorflow/core/kernels/unique_op_test
INFO: Elapsed time: 0.528s, Critical Path: 0.01s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action
exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //tensorflow/core/kernels:unique_op_test
-----------------------------------------------------------------------------
Running main() from test_main.cc
[==========] Running 0 tests from 0 test suites.
[==========] 0 tests from 0 test suites ran. (0 ms total)
[  PASSED  ] 0 tests.

It seems that no test is run. Is there any option missing ?

I don't edit the source code file. The version of TensorFlow I use is 1.15 and the Bazel is 0.26.1

Read Violation at address xxxxxxxx in "projectFolder.dll" Alert Box occurs suddenly?

Hai I am doing selenium auto testing.In this I have two forms.When I click on the button in form1 ,It naviagtes to form2.When I click the "ok" button in form2,Form2 should be closed and it again naviagtes to form1 and form1 operations should be continued.But When I click on "ok" button in form2 Read violation address 00000000B in porojectFolder.dll module alertbox occurs.Why I am having this alertbox?How to fix this?Anyone please help me.Thanks in advance.

Get inputType from Android editText widget using Appium (Python)

I couldn't find a way to get the inputType attribute from Android editText widgets using Appium. There is no "inputType" in the available attributes when I use the inspector. I also tried get_attribute("inputType") just to be sure but no result as expected.. Is there any way to get this attribute? Thanks!

When and how do you use Laravel Factory and Seeding

I'm confused about using them, so want to make sure I'm using them correctly and get to know if there is any other use case". Here are my use cases:

1- In unit tests

public function test_index_returns_view()
{
    ...
    $streets = factory(Street::class, 10)->make();
    ...
}

2- when I'm developing a new app, run the seeders like this to puplate DB

php artisan migrate:fresh --seed

3- for inserting some records in production, put something like this in a migration

Artisan::call('db:seed', array('--class' => 'YourSeederClass'));

Laravel Dusk getting: "stale element reference: element is not attached to the page document"

Yesterday, I run my Laravel Dusk tests and they worked fine, today I run them and 8 out of the 13 fail, most of them with "stale element reference". I've made some modifications to the app but nothing that should require me to modify the tests.

I've updated the chrome driver using (thanks to staudenmeir/dusk-updater):

php artisan dusk:update 81

but that got me even more errors. Before doing that I got only 3 of my tests to fail now I've got 8.

I've tried googling the issue but nothing seems like a solution.

here are the first 3 errors I get:

1) Tests\Browser\ApartmentsTest::testApartments
Facebook\WebDriver\Exception\StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: headless chrome=81.0.4044.122)
  (Driver info: chromedriver=81.0.4044.69 (6813546031a4bc83f717a2ef7cd4ac6ec1199132-refs/branch-heads/4044@{#776}),platform=Linux 4.15.0-96-generic x86_64)

/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:108
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:331
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:565
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteExecuteMethod.php:40
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebElement.php:332
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:142
/var/www/domovakniga.local/tests/Browser/ApartmentsTest.php:25
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:67
/var/www/domovakniga.local/tests/Browser/ApartmentsTest.php:67

2) Tests\Browser\BoardMembersTest::testExample
Facebook\WebDriver\Exception\StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: headless chrome=81.0.4044.122)
  (Driver info: chromedriver=81.0.4044.69 (6813546031a4bc83f717a2ef7cd4ac6ec1199132-refs/branch-heads/4044@{#776}),platform=Linux 4.15.0-96-generic x86_64)

/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:108
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:331
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:565
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteExecuteMethod.php:40
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebElement.php:332
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:142
/var/www/domovakniga.local/tests/Browser/BoardMembersTest.php:25
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:67
/var/www/domovakniga.local/tests/Browser/BoardMembersTest.php:54

3) Tests\Browser\CashbookSettingsTest::testExample
Facebook\WebDriver\Exception\UnrecognizedExceptionException: element not interactable
  (Session info: headless chrome=81.0.4044.122)
  (Driver info: chromedriver=81.0.4044.69 (6813546031a4bc83f717a2ef7cd4ac6ec1199132-refs/branch-heads/4044@{#776}),platform=Linux 4.15.0-96-generic x86_64)

/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Exception/WebDriverException.php:158
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:331
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:565
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteExecuteMethod.php:40
/var/www/domovakniga.local/vendor/facebook/webdriver/lib/Remote/RemoteWebElement.php:332
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/InteractsWithElements.php:142
/var/www/domovakniga.local/tests/Browser/CashbookSettingsTest.php:25
/var/www/domovakniga.local/vendor/laravel/dusk/src/Concerns/ProvidesBrowser.php:67
/var/www/domovakniga.local/tests/Browser/CashbookSettingsTest.php:32 

the other errors are of the same type as "stale element reference".

Here is also my ApartmentsTest:

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ApartmentsTest extends DuskTestCase
{
    /**
     * Test if user can create and edit apartments
     *
     * @return void
     */
    public function testApartments()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/login');

            sleep(1);

            $browser->click('#ok')
                ->waitForLocation('/login')
                ->type('email', 'peter.v.vasilev@gmail.com')
                ->type('password', 'password')
                ->press('Вход')
                ->visit('/apartments/create')
                ->waitForLocation('/apartments/create')
                ->assertSee('Нов апартамент')

                // select obekt
                ->click('.form-group:nth-child(2) .selectize-input')
                ->click('.form-group:nth-child(2) .selectize-dropdown .option:nth-child(2)')
                ->click('.panel-heading');

            sleep(1.5);

            // select entrance
            $browser->click('.form-group:nth-child(3) .selectize-input')
                ->click('.form-group:nth-child(3) .selectize-dropdown .option:nth-child(1)')
                ->click('.panel-heading')

                ->select('type', 1)
                ->type('floor', 10)
                ->type('apt_number', 1)
                ->type('percent_ideal_parts', 10.00)
                ->type('taksa_fro', 2.50)
                ->type('taksa_domoupravitel', 5.00)
                ->type('starting_balance', 14.00)
                ->press('Запиши')
                ->assertSee('Апартамента беше запазен успешно.')
                ->assertPathIs('/entrances/2/apartments')
                ->visit('/apartments/21/edit')
                ->type('percent_ideal_parts', 12.50)
                ->press('Запиши')
                ->assertSee('Успешно актуализирахте апартамента.')
                ->visit('/apartments')
                ->type('.form-control-sm', '#2020221101');

            sleep(1);

            $browser->press('Изтрий')
                ->acceptDialog()
                ->waitForLocation('/apartments')
                ->assertSee('Апартамента бе успешно изтрит.');
        });
    }
}

Any ideas appreciated.

Mock method failure - Java

I have the following piece of code:

void startLogin() {
        if (userNotLoggedIn) {
            view.showLoginScreen(loginInterface);
        } else {
            refreshToken();
        }
    }

void refreshToken() {
            authController.refreshToken( new ResultListener() {
                @Override
                public void onSuccess() {
                    Log.d(TAG, "Token refreshed successfully");
                    view.showApp();
                }

                @Override
                public void onError(AuthControllerException exception) {
                    Log.w(TAG, "Token refresh failed", exception);
                    view.showLoginScreen(loginInterface);
                }
            });
    }

I wanna test the method above with the three following tests, of which the first one is already working:

@Test
    public void startLogin_RefreshToken_WhenLoggedIn() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalled();
    }

---------------------------------------------------------------------------------------
    @Test
    public void startLogin_RefreshToken_Successful_WhenLoggedIn_ShowsApp() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalledAndSucceeds();
        thenAppIsShown();
    }

    @Test
    public void startLogin_RefreshToken_Failed_WhenLoggedIn_ShowsLoginScreen() {
        givenUserIsLoggedIn();
        whenStartingLoginScreen();
        thenRefreshTokenIsCalledButFails();
        thenLoginScreenIsCalled();
    }

I am not sure how to mock the thenRefreshTokenIsCalledButFails() and thenRefreshTokenIsCalledAndSucceeds()

For thenRefreshTokenIsCalled what I do is I have an instance of the class the method is in, same class the startLogin is in, lets call it AuthViewer

so I do authViewer.refreshToken(); or authViewer.startLogin();

For LogInScreenIsShown and thenAppIsShown I do:

private void thenLogInScreenIsShown() {
        Mockito.verify(mockView, Mockito.only()).showLoginScreen(Mockito.any());
    }

    private void thenAppIsShown() {
        Mockito.verify(mockView, Mockito.only()).showApp();
    }

mockView is the instance of the class View I am using which contains showApp and showLoginScreen:

mockView = Mockito.mock(View.class);

I tried something like:

private void givenTokenCanBeRefreshed() {
        mockAuthController.errorReturnedByRefresh = null;
    }

But I keep getting wanted but not invoked errors.

Any guidance would be helpful.

Testcafe and cloudflare

Cloudflare Access expects both values as headers in the request sent to the application. Name them as follows:

CF-Access-Client-Id: &lt;Client ID&gt;
CF-Access-Client-Secret: &lt;Client Secret&gt;
https://developers.cloudflare.com/access/service-auth/service-token/

I am new to TestCafe and i have done several tests on our production website and it worked well. However now when i try to access our application on Test environment which is behind cloudfare, i am failing to get through. i read that i should send in headers the above two values. Does anyone know how i can do this in TestCafe? Do let me know if I am missing out any information. Thank you in advance :)

Virtualbox reset IP-address of vboxnet0 on linux

When trying to connect to a service in a virtualbox-guest-machine throu a java-backend I noticed that the IP-Address of the vboxnet0 interface becomes a reset (bug reported but closed 2012).

Guest-Machine in virtualbox is:

  • WinXP (IP: 10.0.2.15, Subnetmask: 255.255.255.0)

Host system running virtualbox is:

  • Ubuntu, vboxnet0 (IP: 192.168.56.1, Subnetmask: 255.255.255.0)

Theese are the commands I used to force to set the vboxnet0 interface to ip 10.0.2.2:

[root@rm-2  rm2.sxixus.de ~]# ifconfig vboxnet0 && date
vboxnet0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.1  netmask 255.255.255.0  broadcast 192.168.56.255               <-- WRONG at 12:04:26
        inet6 fe80::800:27ff:fe00:0  prefixlen 64  scopeid 0x20<link>
        ether 0a:00:27:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 669  bytes 86020 (86.0 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Wed Apr 29 12:04:26 CEST 2020
[root@rm-2  rm2.sxixus.de ~]# ifconfig vboxnet0 10.0.2.2                              <-- set 10....
[root@rm-2  rm2.sxixus.de ~]# ifconfig vboxnet0 && date                               <-- OK at 12:05.01
vboxnet0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 10.0.2.2  netmask 255.0.0.0  broadcast 10.255.255.255
        inet6 fe80::800:27ff:fe00:0  prefixlen 64  scopeid 0x20<link>
        ether 0a:00:27:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 669  bytes 86020 (86.0 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Wed Apr 29 12:05:01 CEST 2020
[root@rm-2  rm2.sxixus.de ~]# ifconfig vboxnet0 && date                                <-- WRONG at 12:05:03
vboxnet0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.1  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::800:27ff:fe00:0  prefixlen 64  scopeid 0x20<link>
        ether 0a:00:27:00:00:00  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 671  bytes 86200 (86.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Wed Apr 29 12:05:03 CEST 2020
[root@rm-2  rm2.sxixus.de ~]#

This is my application log:

29-Apr-2020 12:03:51.954 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Trigger snapshot creation.
29-Apr-2020 12:03:51.954 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Try to start the VM in headless mode.
29-Apr-2020 12:03:52.499 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Successfully started VM.
29-Apr-2020 12:03:53.015 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Time left to create snapshot: 59500
        (... snip)
29-Apr-2020 12:04:30.075 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check if route from vboxnet0 to guest-machine is possible.
29-Apr-2020 12:04:30.076 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check if route from vboxnet0 to guest-machine (0) is possible.
29-Apr-2020 12:04:30.076 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check ipv4 connection between guest  10.0.2.15(255.255.255.0) and host 192.168.56.1(255.255.255.0)
29-Apr-2020 12:04:30.076 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check ipv4 dec notation connection between guest  452984832(-50331648) and host -1593835520(-50331648)
29-Apr-2020 12:04:30.076 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Can guest reach host? false
29-Apr-2020 12:04:30.076 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Can host reach guest? false
29-Apr-2020 12:04:30.092 WARNING [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations No bidirectional route between host-system and guest-system.
29-Apr-2020 12:04:30.093 WARNING [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Could not connect to puppeteer.
29-Apr-2020 12:04:30.100 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Shutdown vm using poweroff.
29-Apr-2020 12:04:40.767 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:04:51.113 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:05:01.483 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:05:01.487 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Trigger snapshot creation.
29-Apr-2020 12:05:01.487 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Try to start the VM in headless mode.
29-Apr-2020 12:05:01.973 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Successfully started VM.
29-Apr-2020 12:05:02.499 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Time left to create snapshot: 59500
        (... snip)
29-Apr-2020 12:05:39.684 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Time left to create snapshot: 26500
29-Apr-2020 12:05:39.937 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check if route from vboxnet0 to guest-machine is possible.
29-Apr-2020 12:05:39.937 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check if route from vboxnet0 to guest-machine (0) is possible.
29-Apr-2020 12:05:39.937 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check ipv4 connection between guest  10.0.2.15(255.255.255.0) and host 192.168.56.1(255.255.255.0)
29-Apr-2020 12:05:39.938 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Check ipv4 dec notation connection between guest  452984832(-50331648) and host -1593835520(-50331648)
29-Apr-2020 12:05:39.938 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Can guest reach host? false
29-Apr-2020 12:05:39.938 FINE [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.findRoute Can host reach guest? false
29-Apr-2020 12:05:39.948 WARNING [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations No bidirectional route between host-system and guest-system.
29-Apr-2020 12:05:39.949 WARNING [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Could not connect to puppeteer.
29-Apr-2020 12:05:39.955 INFO [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Shutdown vm using poweroff.
29-Apr-2020 12:05:50.590 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:06:00.936 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:06:11.346 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:06:21.705 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.
29-Apr-2020 12:06:32.102 FINER [RM - Virtualbox Snapshot creation request] de.e_sxixus.test.vb.sync.VirtualboxPersistenceService.executeSnapshotCreations Create snapshot for machine using id #102.

Since I have about 20 different guest-machines and 400 different snapshots on the server the IP-Address of the vboxnet0 interface should not change.

Question

How to modify the ip-address of inet-interface vboxnet0?

How to avoid the change of the virtualbox IP address?

Best practices for benchmarking across multiple environments?

We have a benchmark tool to test the performance of some DB population tasks inside a service (the services are in Go and the DB is Postgresql but I don't think that is helpful to the context of my question). This to get a sense of the scalability of both.

Currently we do not have a single environment where this benchmark tool is run, therefore the results could slightly change depending on it.

Does it make sense to store the results of the benchmark tests and compare them with further runs or the fact of having multiple environments completely defeats this? What are some best practices for utilising the benchmark results? Thanks in advance for your help!

Why classes methods are not maintaining execution sequence when running through jenkins job

how two run two different class sequentially through jenkins under single job. Please help.

Testing EFCore using XUnit and Moq in ASP.NET Core

I am a newbie in testing and i am writing my first lines of code to test the GetById in EFCore layer, i wrote this code to instanciate the service :

public class GroupTest
    {
        private readonly GroupService<GroupDTO, Group, GroupUser, AuthContext> _service;
        private readonly Mock<IUserRoleRepository<UserRole>> _userRoleRepo = new Mock<IUserRoleRepository<UserRole>>();
        private readonly Mock<IGroupUserRepository<GroupUser>> _groupUserRepo = new Mock<IGroupUserRepository<GroupUser>>();
        private readonly Mock<IGroupRepository<Group>> _groupRepo = new Mock<IGroupRepository<Group>>();
        private readonly Mock<ICurrentContextProvider> _contextProvider = new Mock<ICurrentContextProvider>();
        private readonly Mock<AuthContext> dbContext = new Mock<AuthContext>();


        public GroupTest()
        {
            _service = new GroupService<GroupDTO, Group, GroupUser, AuthContext>
                (_contextProvider.Object,_groupRepo.Object, _userRoleRepo.Object, _groupUserRepo.Object,dbContext.Object);

        }

Then i wrote my first testcase :

[Fact]
public async Task GetByIdAsync_ShouldReturnGroup_WhenGroupExists()
{
  const int id = 1;
  var resultGroup = await _service.GetById(id);
  Assert.Equal(id, resultGroup.Id);
}

When i excuted the test an exception is thrown : enter image description here

Any suggestion please?

How to pass vouch coockie in request headers using python

In my case i want to pass access token cookie and vouch cookie in headers. While i am trying using postman i am passing access token cookie as a cookie in headers and vouch cookie as authorization token. It is working fine. In the same way i tried using python script , It's not working.

cookie='fhfeuii..34hnsn'
vouchcookie = 'hdjkfnv89'
headers = {'Authorization': vouchcookie, 'Cookie': cookie}

Unable to perform any actions in modal window

I am trying to automate my application and i am unable to perform any actions on the modal window.

Below is the HTML code of that modal window.

<div class="modal fade bs-modal-lg in" id="homeModal" tabindex="-1" style="display: block; padding-left: 16px;" aria-hidden="false"><div class="modal-backdrop fade in" style="height: 958px;"></div>
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header modal-header-dl " id="homeModalHeader">
                <a href="javascript:void(0)" onclick="ClosepopupModal()" class="pull-right dl-padding-top-10 dl-padding-right-20" role="button" title="Close">
                    <i class="zbox-button close"></i>
                </a>
            <h4 class="modal-title">XDS Authentication</h4></div>
            <div class="modal-body " id="homeModalBody"><div class="form-group dl-padding-bottom-20 dl-mg-left-right-5px">
    <input type="text" class="form-control" id="id-number" name="IDNumber" placeholder="SA ID number" value="" maxlength="13" onpaste="return onPaste(event)" onkeydown="return onKeyPress(event)" onkeyup="return onKeyUp(event)" onkeypress="return checkNumberAndClearTextBox('account-number')" onblur="checkLength(this, 13)">
    <small><span id="id-number-error" class="error-msg">&nbsp;</span></small>
    <div>
        <button type="button" id="register-btn" class="btn pull-right dl-button-primary dl-margin-right-0" onclick="GetClientDetails(event)">Retrieve Authentication Questions</button>
    </div>
</div>

I have to enter value on text box and click on a button in that modal window but unable to do it.

Window handles method doesn't worked.Getting unable to locate element error.

driver.SwitchTo().Window(driver.WindowHandles[1]);
            IWebElement IDnumber = driver.FindElement(By.Id("id-number"));
            IDnumber.SendKeys("123456");
            IWebElement Authenticate = driver.FindElement(By.CssSelector(".btn.pull-right.dl-button-primary.dl-margin-right-0"));
            Authenticate.Click();
            IWebElement Skipbutton = driver.FindElement(By.CssSelector(".btn.pull-right.dl-button-secondary"));
            Skipbutton.Click();

What is the right way to do it?

mardi 28 avril 2020

Public read only Splunk data for testing

Is there a public instance of Splunk that can be used to test queries?

I Googled "public splunk test instance" and didn't see anything there.

HTML image gets rendered on top of Karma

How come a logo which I have in my navbar component is rendered in Karma when I run "ng test"?

When running "ng test" it appears like in the image below:

enter image description here The following code is from my app.component.spec.ts file.

describe("AppComponent", () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let de: DebugElement

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule, 
        AngularFireDatabaseModule,
        AngularFireAuthModule,
        AngularFirestoreModule,
        AngularFireStorageModule,
        AngularFireModule.initializeApp( environment.firebase)],
      declarations: [
        AppComponent, 
        NavbarComponent],
      providers: 
        [ 
          DatabaseService, 
        ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthy();
  });
}); 



how to test two json file with pytest in python3.6

what would be the best way to test the case below with pytest with python3(3.6}+)?

json_data_one = {
   "id": 1,
   "status": True,
   "name": "Jhon"
}

json_data_two = {
   "id": 2,
   "status": False,
   "name": "Dave"
}
def foo(json_data_one, json_data_one):
    # not the best way to show this
    # but i want to loop through each json data then
    # show the result based on `status` is either `True` or `False`
    if json_data_one["status"] == True:
        return json_data_one
    elif json_data_one["status"] == False:
        return json_data_two

I am a bit lost on how to implement it but what i want to accomplish is check each json data, then if status == True return "name" == "John" but if status == False return "name" == "dave"

I believe parametrize could be used but i am having a hard time figuring it out.

Thank you.

In React, How to mock action creator(thunk) with an api endpoint ? (react-testing-library)

I'm using react-testing-library as a testing tool.

// Actions
import Api from '../Api';

const getA = () => {
  return (dispatch) => {
    dispatch(...);
    Api.requestA(..) <-- SDK function that calls an api endpoint
    dispatch(...);
  }  
}
class A extends React.Component {
  componentDidMount() {
    this.props.getA();
  }

  render() {
    ...
  }
}

if i call api directly not through SDK, i think i could mock the endpoint doing like

fetchMock.getOnce('/something', {
}

However, since what i am actually calling is a SDK function, I am not really sure how to mock this async action creator. Thank you in advance!

Scala test error: The @Rule must be public

I'm familiar with the necessity of Java unit tests making their @Rule properties public, however new to doing this in Scala. I understand that Scala classes have properties public by default, so expect this to be acceptable:

class MyTest {

  @Rule
  var failure: ExpectedException = ExpectedException.none()

}

What am I missing?

Puppeteer & Cucumber Selecting one class (from 48 with same class) and clicking on it

I have this problem since yesterday and can't figuered out how to solve it. The problem is that I have 48 buttons with same class (the childs are the same too). Tried using xpath, other classes inside but nothing work.

It work creating an array with all buttons and then pressing on it with "button[number]" but I don't know exactly which number is every button. The last thing that I did was create this loop to check the page by clicking on every single button (may be redirected to the correct one) but didn't work. Maybe I wrote something wrong.

When('I press the Users tab', async function () {
const tabToPress = await scope.page.$$('.ng-star-inserted');
var numberToPress;
for (var index = 0; index < tabToPress.length; index++) {
    await tabToPress[index].click();
    const desiredPage = `https://3.0.testing.azavista.com/users/users`;
    const currentPage = await scope.page.url();
    if (currentPage === desiredPage) {
        numberToPress = index
    }
};
await tabToPress[numberToPress].click();
await scope.page.waitFor(1000);

Parameterized Test with two Arguments in JUnit 5 jupiter

How can I write a parameterized test with two arguments in JUnit 5 jupiter? The following does not work (compile error):

@ParameterizedTest
@ValueSource(strings = { "a", "b", "foo" })
@ValueSource(ints = { 1, 2, 3 })
public void test(String arg1, int arg2) {...}

Test datasource connection in tomcat 9

In the past i worked with WebSphere application Server and to test data source connection there was a simple button test connection. I searched the same function in Tomcat 9 but i could not find it. Do you know a way to test a data source in tomcat 9? Many thanks bye

Loop before launching function

I would like to run a function with different parameters each time. But instead of looping on each fruit and launch the function it will just loop all fruits AND run the function without parameters.

export async function runTestForAll() {
  var fruits = require('./fruits.json');
  var fruitsArray = Object.keys(fruits);
  var arrayLength = fruitsArray.length;    

  for (var i = 0; i < arrayLength; i++) {
    console.log(fruitsArray[i])
    fruits = fruitArray[i]
    runTest(fruits)
  }
};

Images generated from the same array are different during array comparision

In this code sample, the assertion in the function fails.

from pathlib import Path

import numpy as np
import PIL.Image


def make_images(tmp_path):
    np.random.seed(0)
    shape = (4, 6, 3)
    rgb = np.random.randint(0, 256, shape, dtype=np.uint8)
    test_image = PIL.Image.fromarray(rgb)
    image_path = tmp_path / 'test_image.jpg'
    test_image.save(image_path)
    return image_path, rgb


def test_Image_load_rgb(tmp_path):
    image_path, original_rgb = make_images(tmp_path)
    rgb2 = np.array(PIL.Image.open(image_path))
    assert np.array_equal(rgb2, original_rgb)


if __name__ == '__main__':
    test_Image_load_rgb(tmp_path)

When I look at the two arrays, original_rgb and rgb2, they have different values, so of course it is failing, but I don't understand why their arrays have different values.

Opening them both as images using PIL.Image.fromarray(), visually they look similar but not the same, the brightness values are slightly altered, visually.

I don't understand why this is.

The two images are:
test_image.jpg test_image2.jpg

Note: This is fails the same way for both pytest and when run as a script.

Testing @Deprecated classes

Is it a good practice to not write test-cases (Unit tests) for @Deprecated classes?

If so, how can I ignore it for my test coverage?

Note that I am using JUnit.

How to convert my cucumber project to run in parallell?

Hi I currently have a large project where i run my cucumber tests, I am running these at night but im finding the jenkins build keeps breaking after an hour or so, so I want to now run my tests in parallel.

Is this possible to do with an existing project, my project is set up with the feature files, steps,runner etc in the src/test/java directory and my test runner looks like this

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
import org.testng.annotations.DataProvider;

@RunWith(Cucumber.class)
@CucumberOptions(
    features = {"src/test/java/noting/feature_files/"},
    glue = {"noting.steps", "noting.hooks"},
    tags = {"@regression"},
    monochrome = true,
    plugin = {"pretty", "json:target/cucumber-report/cucumber.json", "rerun:target/rerun.txt"}
)

public class MainRunner {



}

Is there a way to convert this to run in parallel, maybe by annotation or feature package?

KarateDSL UI Testing - Friendly Locators not working

Following the other question that I raised recently, could you guys help spot what is wrong with the way how I wrote the "below" friendly locator? Thank you in advance!

Scenario: Get UI - Download
   Given url 'https://test01/v1/doc/env/
   And headers headers1
   When method get
   Then status 200
   * def env = response.url

   Given driver env
   And click('{button}Proceed')
   And click('{span}Start')
   And click('{span}Required - GSA)
   And click('{span}Required - GSB')
   And click('{span}Required - GSC')
   And click('{span}Required - GSD')
   And click('{span}Required - GSE')
   And click('{span}Required - GSF')
   And click('{span}Required - GSG')
   And click('{span}Required - GSH')
   * below('{}Required - GSH').input('karate dsl')

I have a textarea that I would like values to be entered, but the friendly locator "below" is not working for me.

javascript evaluation failed: below('{}Required - GSH').input('karate dsl'), unable to find: {}Required - GSH, BELOW, INPUT

gradle publishing with kotlin dsl with artifactId != project.name for spring-cloud-contract 3.0.0.M1 Milestone

I have a gradle kotlin dsl multi-project setup where the archivesBaseName and therefore artifactId is not equal to the subproject.name.

I struggle with publishing (here publishToMavenLocal) as artifact(verifierStubsJar) is complaining with

Cannot convert the provided notation to an object of type MavenArtifact: task ':microservice:verifierStubsJar'.
The following types/formats are supported:
  - Instances of MavenArtifact.
  - Instances of AbstractArchiveTask, for example jar.
  - Instances of PublishArtifact
  - Maps containing a 'source' entry, for example [source: '/path/to/file', extension: 'zip'].
  - Anything that can be converted to a file, as per Project.file()

also the configurations { ... provider.get().outgoing.artifact(bootJar) ... }

is complaining with:

   > Artifact minimal_microservice-0.1.0.NIGHTLY.jar wasn't produced by this build.

the publishing for my gradle kotlin dsl looks like this:

// Starting from Gradle 6.2, Gradle performs a sanity check before uploading, to make sure you don’t
// upload stale files (files produced by another build). This introduces a problem with Spring Boot
// applications which are uploaded using the components.java component:
// Artifact my-application-0.0.1-SNAPSHOT.jar wasn't produced by this build.
// This is caused by the fact that the main jar task is disabled by the Spring Boot application, and the
// component expects it to be present. Because the bootJar task uses the same file as the main jar task by default,
configurations {
    val jar by tasks.existing
    val bootJar by tasks.existing
    listOf(apiElements, runtimeElements).forEach { provider ->
        provider.get().outgoing.artifacts.removeIf {
            it.buildDependencies.getDependencies(null).contains(jar)
        }
//        provider.get().outgoing.artifact(bootJar)        // <-- why does this not work???
        println(String.format("%s/libs/%s-%s.jar", project.buildDir, archivesBaseName, version))
        provider.get().outgoing.artifact(File(String.format("%s/libs/%s-%s.jar", project.buildDir, archivesBaseName, version)))
    }
}
configure<org.gradle.api.publish.PublishingExtension> {
    publications {
        val archivesBaseName: String by project.extra
        val theVersion = version as String
        create<MavenPublication>("maven") {
            groupId = project.rootProject.group as String?
//            artifactId = archivesBaseName
            version = theVersion
            from(components["java"])
            afterEvaluate {
                artifactId = tasks.bootJar.get().archiveBaseName.get()
            }
        }
        create<MavenPublication>("stubs") {
            groupId = project.rootProject.group as String?
//            artifactId = archivesBaseName // + "-stubs"
            version = theVersion
            val verifierStubsJar by tasks.existing
            artifact(verifierStubsJar)               // <-- this line gives me the above error
            afterEvaluate {
                artifactId = tasks.bootJar.get().archiveBaseName.get()
            }
        }
    }
}

any idea how to (with gradle kotlin dsl)?

a) adjust the configurations { ... } part for a customarchivesBaseName`

b) get the MavenPublication "stubs" artifact from generatedverifierStubsJar`

Mockery mock and spy called 0 times on custom class in controller

I'm having difficulty with the spy and mock in Laravel 7 test when I test for MyCustomClass.

I have tried both mock before running $this->get and spy after $this->get. Both with the same error message (*below).

When running debug in the controller the $myCustomClass is still the MyCustomClass and not the mocked object.

MyCustomClass

class MyCustomClass
{
 public function execute()
 {
   return 'hello';
 }

MyController

class MyController
{
 public function show()
 {
   $myCustomClass = new MyCustomClass();

   $data = $myCustomClass->execute();

   return $data;
 }


private $mySpy;

public function testGetATreeNoCache()
    {
        $spy = $this->spy(MyCustomClass::class); 

        $response = $this->get('/my/path');

        $spy->shouldHaveReceived('execute');

        $response->assertStatus(200);
    }

Error

Method execute(<Any Arguments>) from Mockery_2_App_MyCustomClass should be called
 at least 1 times but called 0 times.

Junit test cases for a nested do while loop

Here is the skeletal for the code:

    flag1=True
    flag2=True
    do {

        try {

            if (){
                throw new IllegalArgumentException();
            }
            .
            .
            .
           do {

                if () {


                } 
               else {

                }
                .
                . 
                .
                if () {
                }

            } while (flag2);

            flag1 = false;

        } catch (RuntimeException ex) {

            retry = true;
        } catch (Exception ex) {

            flag1 = true;


        } catch (Error ex) {

            flag1= true;
        }
        }

    } while (flag1);
}

I am using junit4 for testing. I need to cover all the try catch blocks for testing as well. I wrote a test case satisfying the first if condition and hence throwing illegal argument exception, but after throwing the exception the code moves to the do loop with flag1 always staying true.

TypeError with vue-testing-library and Vuex

I want to test a Vue application using the vue-testing-library. My application uses Vuex. I get a TypeError when trying to render the App component.

TS2322: Type 'StoreOptions<State>' is not assignable to type 'StoreOptions<{}>'.
Types of property 'getters' are incompatible.     
Type 'GetterTree<State, State> | undefined' is not assignable to type 'GetterTree<{}, {}> | undefined'.
Type 'GetterTree<State, State>' is not assignable to type 'GetterTree<{}, {}>'.         
Type '{}' is not assignable to type 'State'.

I render the App component this way.

const finder = render(App, {
    store: options,
    router,
    i18n,
});

Where options is:

const options: StoreOptions<State> = {
    state: {
        username: '',
        token: '',
        refresh: '',
    },
    mutations: {
        storeToken: function (state, token: string) {
            state.token = token;
        },
        storeRefresh: function (state, refresh: string) {
            state.refresh = refresh;
        },
        storeUsername: function (state, username: string) {
            state.username = username;
        },
        deleteTokens: function (state) {
            state.refresh = '';
            state.token = '';
        }
    },
    actions: {
        rescindRefreshToken: async function (context) {
            // ...
        },
        refreshAccessToken: async function (context) {
            // ...
        }
    },
    modules: {}
}

How to validate a text for the webelement which is under Div/small/d tags C#

Below is the HTML code of the footer information of my webpage.

<div class="footer navbar-fixed-bottom">
    <div class="container">
        <small>
            © 2020 <b>CT Bank Limited</b>&nbsp;- <b>Version:</b> 2.1.7418
            - <b>Release Date:</b><span id="releaseDate"> 23/04/2020</span>
            - <b>Web Host:</b><span id="webHost"> CBWFDEV01</span>
            - <b>Client Name:</b><span id="clientName"> cn8c04ba119a80</span>
            - <b>Request Time:</b><span id="requestTime"> 28/04/2020 9:23 AM</span>
        </small>
    </div>
</div>

I need to validate each text field in the footer information like CT Bank Limited/Version/Release Date/Web Host/Client Name/Request Time are present in the web page.

What is the right way to validate the above text in footer information.

How to use Class initialize and Class Cleanup only once in the framework passing test context

I have integrated log4net and extent reports together for logging. I wanted to pass Test Method name as the name of the log file so in order to do that I used to pass Test context in Class Initialize method before every test case run.

the script looks like this:

    [TestClass]
    public class ToverifySequenceProperty : BaseSetup
    {
        BaseSetup baseobj = new BaseSetup();
        BaseDeveloper_CF devobj = new BaseDeveloper_CF();
       // public TestContext TestContext { get; set; }
       // public static string logfilename;


        [TestMethod]
        public void VerifySequenceProperty()
        {
            try
            {

                baseobj.LocateParentWindowbyName("SystemModeler17 - Microsoft Visual Studio  (Administrator)");
                htmlLogging.HTMLReportLogging("Info", "Prent Window Located Successfully");
                var projectnode = "SystemModeler17 [(OS 2200) Standard mode] on SystemModeler17";
                devobj.AddElement(projectnode, "Folder", "fol1");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.AddElement("fol1", "Segment", "seg1");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.AddElement("seg1", "Ispec", "ispec1");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.AddElement("ispec1", "Attribute", "Attribute1");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.AddElement("ispec1", "Attribute", "Attribute2");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.AddElement("ispec1", "Attribute", "Attribute3");
                htmlLogging.HTMLReportLogging("Info", "Element Added Successfully");
                devobj.DeleteElement("Attribute1");
                htmlLogging.HTMLReportLogging("Info", "Element Deleted Successfully");
                devobj.CheckSequenceError();
                htmlLogging.HTMLReportLogging("Info", "Sequence error checked Successfully");
                devobj.ResolveSequenceError("ispec1");
                htmlLogging.HTMLReportLogging("Info", "Sequence Error Resolved Successfully");
            }
            catch (Exception ex)
            {
                htmlLogging.HTMLReportLogging("Error", ex.ToString());
            }

        }

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {
            test = extent.CreateTest($"{context.TestName}");
            logfilename = $"{context.TestName}";
            Setup();
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            TearDown();
            Directory.CreateDirectory(@"C:\LogFiles");
            File.Move(@"C:\temp\default.log", @"C:\LogFiles\" + logfilename + ".log");

        }
    }

Now I am adding this Class initialize and Class Cleanup method in all the Test Class Files. Is there a way I can use this only once and it automatically gets run for every test class. I tried making a constructor in BaseSetup class but then context is null there. How to pass the test context of the test classes i am not getting that part.

KarateDSL UI Testing - Browser is closing automatically

I have recently implemented UI automation along with my API test automation (both in Karate). It is working now with minor issue - the browser is getting closed automatically after the script is executed completely. Is there a way in Karate to either close or retain the browser opened? Thank you!

Scenario: Get UI - Download
   Given url 'https://test01/v1/doc/env/
   And headers headers1
   When method get
   Then status 200
   * def env = response.url

   Given driver env
   And click('{button}Proceed')
   And click('{span}Start')
   And click('{span}Required - GSA)
   And click('{span}Required - GSB')
   And click('{span}Required - GSC')
   And click('{span}Required - GSD')
   And click('{span}Required - GSE')
   And click('{span}Required - GSF')
   And click('{span}Required - GSG')
   And click('{span}Required - GSH')

lundi 27 avril 2020

How to test if error thrown in error handling function in Jasmine

In my Angular application I have a component that subscribes to an observable and in the subscribe method assigns the returning value to a property. Should the request fail, I want to reset the value in the component and pass the error to the global error handler (which we implemented ourselves and takes care of notifying the user).

someFunction(): void {
   const myObservable = this.service.someFunction(); //simplified; in the actual code there are some ifs and elses that determine which function is actually called
   myObservable.subscribe(
        (response) => {
            this.result= response;
        },
        (error => {
            this.result = null;
            throw error;
            }
        ));
}

This piece of code works just fine in the actual application. The only proplem is that I don't understand how to test it properly. I wrote a spy that throws an error so that the error handling function can rethrow it. It looks like this:

spyOn(serviceMock, 'someFunction').and.returnValue(throwError('Error!!'));

Since the error is not thrown in the function directly but rather in the asynchronously executed error handling function, it won't work if I use

expect(component.myFunction()).toThrowError() //test fails because apparently no error is thrown, although I get an 'unhandled exception: Error!!' in the console

Neither can I use a try catch in the test, because then the error will be thrown, but not caught. Yet the test will fail, because the error occured.

I would like to test that the error is rethrown or at least like my test not to fail, because this error is thrown.

Can you please tell me if that is possible in Jasmine or if this idea of throwing errors and using the global error handler isn't such a good idea after all?

Any help would be appreciated :)

How to set limit on Aeron subscriber and publisher count while Running Aeron Samples

I'm running the Aeron samples as given here.

Steps to run the test:

git clone --branch 1.27.0 https://github.com/real-logic/aeron.git
gradle --console='plain' --stacktrace assemble
$JAVA_HOME/bin/java -cp /src/aeron-all/build/libs/aeron-all-1.27.0.jar -Daeron.dir=/dev/shm/aeron-root io.aeron.driver.MediaDriver &
$JAVA_HOME/bin/java -cp /src/aeron-all/build/libs/aeron-all-1.27.0.jar io.aeron.samples.BasicSubscriber &
$JAVA_HOME/bin/java -cp /src/aeron-all/build/libs/aeron-all-1.27.0.jar io.aeron.samples.BasicPublisher &

Output of test

Offering 53747/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3439776) <<Hello World! 53747>>
Offering 53748/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3439840) <<Hello World! 53748>>
Offering 53749/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3439904) <<Hello World! 53749>>
Offering 53750/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3439968) <<Hello World! 53750>>
Offering 53751/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3440032) <<Hello World! 53751>>
Offering 53752/10000000 - yay!
Message to stream 1001 from session -1579104823 (18@3440096) <<Hello World! 53752>>

As shown in the output, there are 1000000 Subscribe and Publish events that are going to take place.

So my question is how can I limit the number of interactions. Doing so using some flags would be great.

How can I apply some generic fluent validation to check all API response?

I have some came across the fluent validation, and I am really liking it. I want to know how can create some generic rules so I can apply to all the API response I get. Instead of validating for the models I want to validate for the response the server gives back. How can I create some generic method to apply these rules.

I have also looked at this Generic Validator for Model T Using Fluent Validation? I am trying to achieve something similar.

public class Validator : AbstractValidator<> {

  public Validator()
    {
        //Get the response here from the server and validate against in the Test
        //Then use that method to apply to the API calls

        RuleFor(x => x.response).NotEmpty().
        RuleFor(x => x.response).NotNull();
}        RuleFor(x => x.response).Must<BeAValidGuid>();
   }

How to change the value new Date() in java

In my application, the date and time need to be changed frequently when the tester tests the application. Currently, we have to use the system command date-s to change the system time,But this will cause other applications on the server to be affected as well。I want to change the Date() only this application, and I don't want to change the application itself, because there are so many places where new Date is used

Writing unit tests which may access private/protectedstate

I use Boost Test for unit tests. I typically have a fixture struct:

class ClassBeingTested
{
protected:
    int _x;             // Want to access this directly in my unit tests
};

struct TestFixture : public ClassBeingTested
{
    // I can access ClassBeingTested::_x here but it means i have to add getters for each test to call
    ClassBeingTested _bla;
};

However, even if my fixture inherits from ClassBeingTested or uses a friend relationship I cannot access private/protected methods/state from each individual test:

BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
    _bla.doSomething();
    BOOST_REQUIRE_EQUAL(_bla.x, 10);    // Compiler error. I cannot access ClassBeingTested::_x here
}

only the fixture, which means I have to add a new getter (or test) for each access I wish to make.

Is there any way to achieve this? I have to add public getter methods to ClassBeingTested which are only used by tests, which isn't ideal.

(Please no replies of 'test using the public interface', that's not always possible).

How to Verify all values from DropDown List in selenium c#

I have the below values inside the dropdown and i need to very each values in the dropdown.

{ "Service Consultant", "DLBO Developer", "Admin Agent", "Team Leader", "Manager", "CV Mandator", "CV Agent", "Forensics Agent" };

Kindly suggest the way to do the same.

InvalidDataAccessApiUsageException: first-result value cannot be negative

I have got a problem with spring data. I have two repositories, with each method on one repository:

Repository1

Page<Model> findAllByIdAndLibraryTypeAndIsActive(Long Id, LibraryType libraryType,
      boolean isActive, Pageable pageable);

Repository2

Page<Model2> findAllByIdAndBookTypeAndIsActive(Long id, BookType bookType,
      boolean isActive, Pageable pageable);

Then I have a common method in my service to get out data from one of repository, it depends of parametres:

  private Page<?> findAll(Long id, String type, boolean isActive, Pageable pageable) {
   if (EnumUtils.isValidEnum(LibraryType.class, type)) {
      return repository1
          .findAllByIdAndLibraryTypeAndIsActive(id, LibraryType.valueOf(type), isActive, pageable);
    } else if (EnumUtils.isValidEnum(BookType.class, type)) {
      return repository2
          .findAllByIdAndBookTypeAndIsActive(id, BookType.valueOf(type), isActive, pageable);
    } 
  }

The call seems so:

Pageable pageRequest = PageRequest.of(0, 10000);
Page<?> all = findAll(id, type, true, pageRequest);

So, when I try to test this in my test method, I'm getting the error:

org.springframework.dao.InvalidDataAccessApiUsageException: first-result value cannot be negative : -2147477296; nested exception is java.lang.IllegalArgumentException: first-result value cannot be negative : -2147477296
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:367)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy208.findAllByInsurerIdAndDocumentTypeAndIsActive(Unknown Source)
    ***at findAll(Service.java:93) - Page<?> all = findAll(id, type, true, pageRequest);
    at method(Service.java:69) - repository1
      .findAllByIdAndLibraryTypeAndIsActive(id, LibraryType.valueOf(type), isActive, pageable);***
    at $$FastClassBySpringCGLIB$$9205311a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
    at org.springframework.cloud.sleuth.instrument.async.TraceAsyncAspect.traceBackgroundThread(TraceAsyncAspect.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at $$EnhancerBySpringCGLIB$$c6a8ab2f.extract(<generated>)
    at 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
Caused by: java.lang.IllegalArgumentException: first-result value cannot be negative : -2147477296
    at org.hibernate.query.internal.AbstractProducedQuery.setFirstResult(AbstractProducedQuery.java:925)
    at org.hibernate.query.internal.AbstractProducedQuery.setFirstResult(AbstractProducedQuery.java:106)
    at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.setFirstResult(CriteriaQueryTypeQueryAdapter.java:136)
    at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.setFirstResult(CriteriaQueryTypeQueryAdapter.java:59)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:102)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.invokeBinding(PartTreeJpaQuery.java:244)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:171)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.doCreateQuery(PartTreeJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:210)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:192)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 69 more

I found one thing, the value "-2147477296" is setting on the method

public QueryImplementor setFirstResult(int startPosition) {
        getProducer().checkOpen();
        if ( startPosition < 0 ) {
            throw new IllegalArgumentException( "first-result value cannot be negative : " + startPosition );
        }
        queryOptions.setFirstRow( startPosition );
        return this;
    }

then I'm getting thrown exception. However I cant understand how is coming this number. Maybe, someone can help me how I can fix this problem on my side. I was googling too much and even can't find any useful information.