vendredi 30 novembre 2018

Test a real-time software

I want to test an enterprise real-time solution (something like a SIEM). This modular software contains 12 different modules and various libraries which communicate over IPC socket. Actually, I am looking for applicable solutions, tools, and materials that might come handy to test this enterprise software. In addition, some reverse engineering tools to better understand the source code.

How to test C# code on many runtime versions?

Is there a framework or website or something that makes it possible to test C# code on many versions of .NET, specifically different versions of the system runtime library?

I've found System.TimeSpan.Parse("0:00:00.01000000") gives different results on different .NET implementations. Sometimes it throws an OverflowException, sometimes a FormatException, and sometimes it returns a 100ms TimeSpan (it's really 10ms).

I've submitted a patch to Microsoft already. But is there some easy way I can test this across different .NET implementations and different class libraries?

Here's a gist of the complete code I'd like to test, although I'm not sure it reports the .NET version information in a complete or useful way.

How to toggle a Switch in Flutter integration test

How to toggle a Switch in Flutter integration test?

Tapping on the Swtich driver.tap(switch) does not work.

enzyme containsMatchingElement with states

Iam having trouble figuring out why my test won't work. Lets say I have a component like this:

class MyComponent extends Component {
   constructor(props) {
      super(props);
      this.state = { flag: true };
   }
   render() {
      return (
         <div>
          {
            this.state.flag && (
               <div>Hello there!</div>
            )
          }
         </div>
      )
   }
}

Here is my test file:

it ('shows Hello There when the flag is set to true', () => {
  const component = shallow(<MyComponent />);
  component.setState({ flag: true });
  expect(
    component.containsMatchingElement(<div>Hello There</div>)
  ).toBe(true)
});

When I run this, it says that it is expecting true, but getting false. Am I doing something wrong?

Thanks!

Unit Test: How to mock document.getElementsByClassName() in react?

I have this component i did with create-react-app and i want to test following function with jest/enzyme.

(The function triggers when the up/down arrows are pressed in an input)

handleArrow(e) {
  const list = document.getElementsByClassName('search__dropdown')[0];
  const len = document
    .getElementsByClassName('search__dropdown-option').length;
  const arr = Array.from(document
    .getElementsByClassName('search__dropdown-option'));
  let selected = document
    .getElementsByClassName('search__dropdown-option--selected')[0];
  let index = arr.indexOf(selected);
  let next = null;

  if (index === -1 && list) {
    index = 0;
    selected = list.getElementsByClassName('search__dropdown-option')[0];
    selected.classList.add('search__dropdown-option--selected');
  } else if (e === 40 && list) {
    if (selected) {
      index++;
      selected.classList.remove('search__dropdown-option--selected');
      next = list.getElementsByClassName('search__dropdown-option')[index];
      if (next !== undefined && index <= len) {
        selected = next;
      } else {
        index = 0;
        selected = list.getElementsByClassName('search__dropdown-option')[0];
        selected.classList.add('search__dropdown-option--selected');
      }
      selected.classList.add('search__dropdown-option--selected');
    }
  } else if (e === 38 && list) {
    if (selected) {
      index--;
      selected.classList.remove('search__dropdown-option--selected');
      next = list.getElementsByClassName('search__dropdown-option')[index];
      if (next !== undefined && index >= 0) {
        selected = next;
      } else {
        index = len - 1;
        selected = list
          .getElementsByClassName('search__dropdown-option')[index];
        selected.classList.add('search__dropdown-option--selected');
      }
      selected.classList.add('search__dropdown-option--selected');
    }
  }
}

So far, i have tried this:

it('should work', () => {
  const dropdown = global.document.createElement('div');
  const option = global.document.createElement('div');
  const selected = global.document.createElement('div');
  dropdown.classList.add('search__dropdown');
  option.classList.add('search__dropdown-option');
  selected.classList.add('search__dropdown-option--selected');
  global.document.body.appendChild(dropdown);
  dropdown.appendChild(option);
  dropdown.appendChild(selected);

  jest.useFakeTimers();
  const comp = mount(<Search/>);
  comp.setState({
    fetching: true,
    searchInput: 'the',
    onInput: true,
    searchResults: data,
    filteredSearch: filtered,
  });
  comp.setState({searchInput: 'the'});
  comp.find('.search__input').simulate('keydown', {key: 'Enter'});
  comp.find('.search__dropdown-option').at(0).simulate('click');
  jest.runAllTimers();
  comp.unmount();
});

When i run the test the "list" variable is always undefined (thing that i don't understand because the line comp.find('.search__dropdown-option') works, so there's there's gotta be search__dropdown in the DOM ,right?)

Thanks in advance.

Testing React Redux - cannot read properties from store, or wrapper undefined

Im having a bit of a problem setting up a Redux store in my component for my test suite. The problem is that even if I try a unconnected mount then the test throws errors looking for variables in authState. I have the following component:

import React, { Component } from 'react';
import { Link, Redirect } from "react-router-dom";
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as authActions from '../../../actions/auth.actions';

export class PasswordReset extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            emailConfirm: '',
            message: ""
        };
    }

    handleChange = e => {
        e.preventDefault();
        const { value, name } = e.target;

        if (name === 'email') {
            this.setState({...this.state, email: value.trim()});
        } else if (name === 'secondary') {
            this.setState({...this.state, emailConfirm: value.trim()});
        }
    }

    handleSubmit = e => {
        e.preventDefault();
        if (this.state.email.length === 0 && this.state.emailConfirm.length === 0) {
            this.setState({message: "Please Enter and Confirm Email Before Submit"});
            return;
        }

        if (this.state.email !== this.state.emailConfirm) {
            this.setState({message: 'Emails Do Not Match, Please Try Again'});
            return;
        }

        this.props.authActions.resetPassword(this.state.email);
    }

    render() {
        if (this.props.authState.resetStatus === 'reset') {
            return <Redirect to='/login' />
        }
        const error = this.props.authState.resetError === 'TypeError: Failed to fetch' ? 'Agent Id does not exist' : false
        return (
            <div className={'container-login100'}>
                <div className={'wrap-login100 p-t-85 p-b-20'}>
                    <form className={'login100-form validate-form'}>
                        <span className={'login100-form-title p-b-70'}>Reset Password</span>
                        <div className={'wrap-input100 validate-input m-t-85 m-b-35'}>
                        <div style=>
                        {error || this.state.message}
                        </div>
                            <input
                                onChange={e => this.handleChange(e)}
                                className={'input100'}
                                name='email'
                                value={this.state.email}
                                placeholder="Please Enter Your Email"
                                required
                            />
                        </div>
                        <div className={'wrap-input100 validate-input m-t-85 m-b-35'}>
                            <input
                                onChange={e => this.handleChange(e)}
                                className={'input100'}
                                name="secondary"
                                value={this.state.secondary}
                                placeholder="Please Confirm By Re-entering Your Email"
                                required
                            />
                        </div>
                        <div className={'container-login100-form-btn'}>
                            <button className={'login100-form-btn btn-disabled'} onClick={e => this.handleSubmit(e)}>Reset Password</button>
                        </div>
                        <div className={'container-login100-form-btn'}>
                            <Link to='/login'>Back to Login</Link>
                        </div>
                    </form>
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    authState: state.auth,
})

const mapDispatchToProps = dispatch => ({
    authActions: bindActionCreators({resetPassword: authActions.resetPassword}, dispatch),
})

export default connect(mapStateToProps, mapDispatchToProps)(PasswordReset);

And the following test structure:

import React from 'react';
import configureStore from 'redux-mock-store';
import Enzyme, {mount, shallow} from 'enzyme';
import Provider from 'react-redux';
import Adapter from 'enzyme-adapter-react-16';

import ConnectedPasswordReset, {PasswordReset} from '../';

Enzyme.configure({adapter: new Adapter()});

const mockStore = configureStore();
let wrapper, store, mWrapper;
const initialState = {isLoggedIn: false, isInProgress: false, email: null, error: null, resetError: null, resetStatus: null};

describe('PasswordReset component', () => {
    beforeEach(() => {
        store = mockStore(initialState);
        wrapper = shallow(<PasswordReset store={store} />);
        mWrapper = mount(<Provider store={store}><ConnectedPasswordReset /></Provider>);
    })

    it('shallow - should have initial state.email of ""', () => {
        expect(wrapper.state().email).toEqual('');
    });

    it('mount - should have a initial state.email of ""', () => {
        expect(mWrapper.state().email).toEqual('');
    });
});

Im getting the following output:

testing output

self-coded HashTable JUnit Test

I'm working on a self-coded HashTable. And now I stuck in testing the damn thing. This is my test-work so far:

//Put Test
Random r = new Random();
        for (int i = 0; i < 1000; i++) {
            int k = r.nextInt(256);
            dummy[i] = k;
            hash.put(i, k);
        }

        assertEquals(1000, hash.size());

//Key Value Test
for (int i = 0; i < 1000; i++) {
            assertEquals(dummy[i], hash.get(i));
        }
//Key Value Test 2
for (int i = 0; i < 1000; i++) {
            int k = r.nextInt(256);
            if (i % 2 == 0) {
                dummy[i] = k;
                hash.put(i, k);
            }
        }
for (int i = 0; i < 1000; i++) {
            if (i % 2 != 0) {
                assertEquals(null, hash.get(i));
            }
    if (i % 2 == 0) {
                assertEquals(dummy[i], hash.get(i));
            }
        }
//Key Value Test 3
for (int i = 0; i < 1000; i++) {

            if (i % 2 == 0) {
                hash.put(i, null);
            }
            else {
                hash.put(i, 1);
            }
        }
for (int i = 0; i < 1000; i++) {
            if (i % 2 != 0) {
                assertEquals(1, hash.get(i));

            }
if (i % 2 == 0) {
                assertEquals(null, hash.get(i));
            }


//Remove Test
for (int i = 0; i < 1000; i++) {
            hash.remove(i);

        }

        assertEquals(0, hash.size());

Any Ideas how I can test my HashTable better ? Or cleverer ? All my test are functional tests. Maybe a big O-Notation test, but how ?

@PostConstruct and bean created with new in configuration class

I have a service in spring boot with a @PostConstruct method. In some integration tests, this method shall not be executed (the service is not used at all in these integratoin tests). So I thought I could just let the bean be created with new inside a configuration class loaded inside this test (@ContextConfiguration).

However, this does not work as I thought. @PostConstruct is called anyway, even twice, as you can see below (yes, this is the whole code):

Application

@SpringBootApplication
public class DemoApplication {

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

Service

@Service
public class MyService {

  @PostConstruct
  public void startup() {
    System.out.println("@PostConstruct - " + this);
  }
}

Test

@RunWith(SpringRunner.class)
@SpringBootTest(
    webEnvironment = WebEnvironment.RANDOM_PORT,
    classes = {DemoApplication.class})
@ContextConfiguration(classes = TestConfiguration.class)
public class DemoApplicationTests {

  @Test
  public void test() {
    System.out.println("Test");
  }

  @Configuration
  static class TestConfiguration {

    @Bean
    public MyService xxx() {
      MyService myService = new MyService();
      System.out.println("@Bean - " + myService);
      return myService;
    }

  }
}

If the test is executed, the following output is printed:

 :: Spring  Boot ::        (v2.1.1.RELEASE)
...
2018-11-30  20:34:28.422  INFO 16916 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-11-30  20:34:28.422  INFO 16916 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1573 ms
@PostConstruct  - com.example.demo.MyService@41c89d2f
@Bean - com.example.demo.MyService@2516fc68
@PostConstruct  - com.example.demo.MyService@2516fc68
2018-11-30  20:34:28.838  INFO 16916 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-30  20:34:29.086  INFO 16916 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 62040 (http) with context path ''
2018-11-30  20:34:29.090  INFO 16916 --- [           main] com.example.demo.DemoApplicationTests    : Started DemoApplicationTests in 2.536 seconds (JVM running for 4.187)
Test
2018-11-30  20:34:29.235  INFO 16916 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Can anybody explain me this?

  • why is first @PostConstruct called
  • why is secondly @PostConstruct called for a bean constructed with new. Why is this bean managed by spring?
  • How can I achieve what I need?

What is a good way to test local sites in different browsers?

I'm trying to test my local site in different browsers, but browser stack and all the other extensions/sites I've been looking at don't seem to work at all. Is there any chrome extension that will help me? Or a site that will work? I'm mainly trying to test my site for Internet Explorer. I'm on a mac, so that makes things more difficult it seems.

JMeter pass JSON response value to next request

I am using JMETER to test a web app.

First I perform a http GET request which returns a JSON array such as:

[
  {
    "key1": 
    {
      "subKey": 
      [
        9.120968,
        39.255417
      ]
    },
    key2 : 1

  },
  {
    "key1": 
    {
      "subKey": 
      [
        9.123852,
        39.243237
      ]
    },
    key2 : 10
  }

]

Basically I want to take randomly one element, take the elements of key1 and create 2 variables in JMeter that will be used for the next query (if randomly it is not possible than just the 1st element).

I tried using JSON Extractor with the following settings:

enter image description here

and in the next query referencing the parameter as ${var1}.

How to set JSON Extractor to extract a value, save into a JMeter variable to be used in the next query?

TestNG priority annotation not working when non-sequential priorities

I'm having some problems with the Priority annotation in TestNG not running test cases. My priority numbers are not sequential, I have intentionally skipped numbers so at a future date I can add some test methods between them so the run in a specific order. Any ideas how I can get TestNG to execute my test methods that follow the number gap? For example, I have priorities in the order of 1 - 3 and then I jump to 200 - 202. The tests with priorities 200 - 202 are not being executed. Thanks for your time.

public class ClassOneTest{
    @Test (enabled=true, priority=1)
    public void methodOneTest() {
        .....
    }

    /**
     * Updates the ServiceNow End Point
     */
    @Test (enabled=true, priority=2)
    public void methodTwoTest() {
        .....
    }

    /**
     * Deletes the ServiceNow End Point
     */
    @Test (enabled=true, priority=3)
    public void methodTwoTest() {
        .....
    }
}

public class ClassTwoTest{
    @Test (enabled=true, priority=200)
    public void methodThreeTest() {
        .....
    }

    /**
     * Updates the ServiceNow End Point
     */
    @Test (enabled=true, priority=201)
    public void methodFourTest() {
        .....
    }

    /**
     * Deletes the ServiceNow End Point
     */
    @Test (enabled=true, priority=202)
    public void methodFiveTest() {
        .....
    }
}

Pass the "Your connection is not private" page in Chromium

I encounter this problem when I try to do the testing with Chromium and Jest, but there is a problem that I cannot make the Chromium instance to pass the "Your connection is not private" page and do what I want.

Look like this: screenshot

I tried the solution that works on Chrome, by setting like this:

Screenshot2

But this setting doesn't make any sense on chromium, for it cannot keep, every time when I try to restart the test, it automatically back to the default setting again.

Appreciate to the help of any kinds.

Cross-Browser-Testing in xUnit with Selenium

I'd like to run my unit tests on different browsers with Selenium and xUnit. I couldn't find a proper solution throughout my research. I have found some variants with nUnit but they don't fit my needs.

The soulution should execute all tests in three different browsers (IE, Chrome, Firefox). Also the amount of browsers should be customizable.

Is there any proper solution?

How to use @WebMvcTest and @WithUserDetails for integration test in Spring Boot

I'm struggling to get a test to run in Spring Boot 2.1.

I'm trying to use @WithUserDetails, as I have a custom UserDetails implementation.

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SearchController.class)
public class SearchControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithUserDetails("testuser")
    public void testPass_OpenAdvancedSearch() throws Exception {

        this.mockMvc.perform(get("/applications/advanced")).andExpect(status().isOk())
                .andExpect(content().string(containsString("</html>")));
    }

This is the UserDetailsService implementation:

@Configuration
public class TestConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        return new TestUserDetails();
    }

}

However, this gives me a

No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available

To try and solve this, I add the below to my test class:

@Import( TestConfig.class)

...however this fails with:

IllegalStateException: The @PropertyMapping annotation @WebMvcTest cannot be used in combination with the @Component annotation @Configuration

I'm not sure what I'm doing wrong; the Boot documentation for @WebMvcTest here does suggest using @Import to add in additional beans as required. https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

If you need to register extra components, such as the Jackson Module, you can import additional configuration classes by using @Import on your test.

I tried removing the @Configuration annotation from the TestConfig class, but it doesn't make any difference.

Jest testing user API

I am trying to test the register and login routes for an user API. I am using Jest and supertest. I had some failing attempts but all of them finished with the same error:

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

   9 | describe('Test Users routes - route /register', () => {
  10 |
> 11 |      it('should succesfully register a valid user', async() => {
     |      ^
  12 |              const newUser = new User({
  13 |                      name: 'newuser',
  14 |                      email: 'new@gmail.com',

This is the code:

    it('should succesfully register a valid user', async() => {
        const newUser = new User({
            name: 'newuser',
            email: 'new@gmail.com',
            password: 'new123'

        })
        const expectedName = 'newuser'
        const ExpectedEmail = 'new@gmail.com'
        const newUserStub = 
     sinon.stub(User.prototype,'save').resolves(newUser)
    const fakeResponse = await request(app).post('/api/users/register').expect(200)
    expect(fakeResponse.body.name).toBe(expectedName.trim())
    expect(fakeResponse.body.email).toBe(ExpectedEmail.trim())
    //existingUserStub.restore()
    newUserStub.restore()
})

I am using the same method to tests other API's and it is working just fine.

Alternatives to deprecated jp@gc - JSON Format Post Processor

I am using JMETER to perform http GET requests to a web application. The response is JSON data and I want to format it properly.

I installed with the Plugins Manager the jp@gc - JSON Format Post Processor which works great and does not require any setting. However it is deprecated. I tried to use instead of it the JSON Extractor but it seems it is not made for formatting purposes.

Is there an alternative to the deprecated jp@gc - JSON Format Post Processor JMeter plugin?

Maven run test but "prohibited package name"

I try to test my app, i've insert into src/test/java my test class, maven run test because is its default directory, but throws "prohibited package name: java". How can i solve?

Jasmine/Javascript - why is a DOM element only accessible by reference from within an async then()?

After a loooot of testing... I stumbled upon some interesting behavior that I don't understand.

Code:

function someFunction() {
  ... // whatever this is stubbed
}

// below is called ("mounted") by finalDOM.mountUserActions()     
$("#button").click(function() {
  savedElement = $("#saved_element")
  console.log("BEFPRE THEN in event listener ==========")
  console.log("found saved_element? = " + savedElement.length)
  console.log("found unsaved_element? = " + $("#unsaved_element").length)

  someFunction().then(function(result){
    savedElement.val(result)
    $("#unsaved_element").val(result)
    console.log("INSIDE THEN in event listener ==========")
    console.log("found saved_element? = " + savedElement.length)
    console.log("found unsaved_element?  = " + $("#unsaved_element").length)
  })
})

Test code:

fdescribe("on click of button", function() {
  beforeEach(function(){
    response = Promise.resolve("test")
    spyOn(window, "someFunction").and.returnValue(response)
    savedElement = affix("#saved_element")
    affix("#unsaved_element")
    affix("#button")
    finalDOM.mountUserActions();
    $("#button").click()
  })
  it("should change value of saved_element", function() {
    response.then(function() {
        console.log("INSIDE SPEC EXPECTATION ==========")
        console.log("value of saved_element = " + savedElement.val())
        console.log("value of unsaved_element = " + $("#unsaved_element").val())
      expect(savedElement.val()).toEqual("test") // PASS
      expect($("#unsaved_element").val()).toEqual("test") // FAIL
    })
  })
})

Console output:

BEFPRE THEN in event listener ==========
found saved_element? = 1
found unsaved_element? = 1
INSIDE THEN in event listener ==========
found saved_element? = 1
found unsaved_element?  = 0
INSIDE SPEC EXPECTATION ==========
value of saved_element = test
value of unsaved_element = undefined

The fact that the length of both elements are 1 in BEFORE THEN in event listener proves that the affix worked, both elements are on the page, so then why is only the saved element found once INSIDE THEN in event listener?

I don't think I've ever encountered this... is this a Javascript gotcha or a Jasmine one? Would love to learn more about it to avoid this in the future... have spent a lot of time scratching my head on it.

jeudi 29 novembre 2018

In Nightwatch, how to examine current URL with expect?

If using assert in Nightwatch, I can use tools like urlContains or something to examine the current URL.

But, I just can't find ways to examine URL with expect namespace.

I think it is not a good practice to mix expect and assert together in the test cases.

If anyone knows how to examine URL using expect, please help to give some examples, thanks...

How to use dynamic values for Karate Features

I've a need where I should use dynamic values in the features of my karate tests.

I've came accross with some of the questions and answers like this: How to read input data from an excel spreadsheet and pass it JSON payload in karate framework?

But no mather what how hard I try, I couln't make it happen. I believe I should share the code parts that I am trying to use, so that a discussion can start.

I have a SOAP request for creating new users as below:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xxxxxx>
<soapenv:Header/>
<soapenv:Body>
    <int:createSubscriber soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <custBean xxxxx>
            <accountNumber xsi:type="xsd:string">#(accountNo)</accountNumber>
            <custName xsi:type="xsd:string" xs:type="type:string">Xbox</custName>
        </custBean>
        <addSubscriberBean xxxxx>7
            <subscriberID xsi:type="xsd:string">#(subsID)</subscriberID>
            <password xsi:type="xsd:string" xs:type="type:string">0</password>
            <areaID xsi:type="xsd:string" xs:type="type:string">1</areaID>
            <lineOfCredit xsi:type="xsd:int" xs:type="type:int"></lineOfCredit>
            <creditCycle xsi:type="xsd:int" xs:type="type:int"></creditCycle>
            <points xsi:type="xsd:int" xs:type="type:int"></points>
            <bandwidth xsi:type="xsd:int" xs:type="type:int"></bandwidth>
            <physicalPorts xsi:type="xsd:string" xs:type="type:string">8080</physicalPorts>
            <mobilePhoneNo xsi:type="xsd:string" xs:type="type:string">#(mobile)</mobilePhoneNo>
            <stbCount xsi:type="xsd:int" xs:type="type:int">5</stbCount>
            <oTTCount xsi:type="xsd:int" xs:type="type:int">10</oTTCount>
            <subscriptionType xsi:type="xsd:string" xs:type="type:string">#(subsType)</subscriptionType>
        </addSubscriberBean>
        <sequenceID xxxxx>1234567840123422700</sequenceID>
    </int:createSubscriber>
</soapenv:Body>

As you've seen, I have some variables which is going to be given from outside, and those are: accountNo, subsID, subsType and mobile.

Nw, I have a feature file where I make a call to a SOAP service byusing above file. I am assigning new values to all variables of request, so that I can create new users all the time.

Here is the example:

Feature: Create Subscriber Feature End-To-End Scenario

Background:
* url SOAP_CREATE_SUBSCRIBER_HOST

* def accountNumber = '789'
* def subscriberID = '456'
* def userMsisdn = '123'
* def subscriptionType = 'ASD'

* def createUser = read('create-user-soap.xml') # This is the above one
* replace createUser
  | token              | value               |
  | #(accountNo)       | accountNumber       |
  | #(subsID)          | subscriberID        |
  | #(mobile)          | userMsisdn          |
  | #(subsType)        | subscriptionType    |

Scenario: Create Subscriber
Given request createUser
When soap action SOAP_CREATE_SUBSCRIBER_HOST
Then status 200

And match //returnCode == 0
And match //returnMessage == 'The operation succeeded.'

However, I need to create bunch of users, so I need to use dynamic variables to call my .xml file too many times.

I checked the docs and answer here: How to read input data from an excel spreadsheet and pass it JSON payload in karate framework?

But couldn't locate it in my situation.

Thanks in advance.

How to ignore spec files and mock files in production build in Angular 6

I m trying to compile in production my angular application and I m receiving this error:

Cannot determine the module for class TranslateMockPipe in /src/testing/translate.service.spec.ts! Add TranslateMockPipe to the NgModule to fix it.

this TranslateMockPipe class is a common class that I declared and I m using it in all my test files in order to avoid repeating the same line of code in all the test cases

the code of the class:

@Pipe({ name: "translate" })
class TranslateMockPipe {
    transform = (ss) => ss
}

I m using it in my test like this:

TestBed.configureTestingModule({
            declarations: [
                DemoComponent,
                TranslateMockPipe
            ]
})

If I run the project everything goes well, and my test pass without issues but fail when I try to compile for production

How I can ignore this kind of fake classes for production build?

Testing audio functionalities in Google Actions simulator

I'm writing my first action for the google home, which involves playing an audio file. I was able to get the playback going by returning a MediaObject, however, when I use the simulator to test the action, the "Pause" command is not recognized. I'm aware that I cannot implement a Pause intent and that no callback is issued when the user says "Pause", but I would've expected for the Simulator to respond to it. Any idea where I'm going wrong?

expect(jest.fn()).toHaveBeenCalledWith(expected)

expect(jest.fn()).toHaveBeenCalledWith(expected) is not working with react native 57. Is anyone facing the same issues?

The below test function is failing

[code]

it('message', () => {
    const tt = [
      {data}
    ];

    expect(myfunc).toHaveBeenCalledWith(tt);
  });

[/code]

Should test @RestController or just @Service

I have a application with 3 layers: Controller, Service and Repository.

  • My controller is a Rest (@RestController in spring) that only get a request using a DTO, convert to a Model and pass to a service (@Service in spring).

  • My service have all bussiness logic and my Test classes are based on service classes only.

  • My repository is only a JpaRepository and sometimes use a custom query with @Query.

Well, as i said i just make test classes for Service, because here is my bussiness logic. My doubt is about create test for Controllers classes, is really necessary ? this is a good practice ?

Repeat LAST action from Jubula Testcase

I am using Jubula to test a big softwaretool. Since the UI got updated Jubula has some big problems. The test quit's at a position (let's say after Step A), after I was trying to figure out whats the problem, I didn't find a problem and Jubula quits at a totally different position, some times before and some times after position A. It's seams to be really random if, and if, where it quits.

Now I got known to the eventhandler (before, I never was used to use them). Since there are much testcases and in every Testcase much much actions (at least 50) and Jubula is always "stopping" at different, the problem is not solved to add an eventhandler which always does the same thing (lets say clicks on a button) because some times Jubula shall click on button A and some times on B, in other cases he has to select something from a "dropdown-menu".

NOW my question: Is it possible to force Jubula, to repeat the LAST DONE action? Since I started to watch closely on the reports, I noticed that the buttons are already displayed and jubula just doesn't click on them. (i tried to wait until they appear before i click on 'em)

I would be really really happy if there is a solution (even if it's "difficult" or hard to realize because I need to add much components.)

Unit testing a component which has a promise which contains an Observable

I am having a problem unit testing some functionality in a component were a function is called which returns a promise and that promise itself contains an observable subscription.

I have mocked the Observable response but I am unsure as to how I get this working correctly.

Here is the component functions in question:

public addAncillary(ancillaryCode: AncillaryCode): void {
    this.ancillariesArray.push(ancillaryCode);

    // This code is to be refactored to remove this logic call the ancillary service to calculate quote price
    if (ancillaryCode === AncillaryCode.BuildingsAD || ancillaryCode === AncillaryCode.ContentsAD) {
      this.getRequote(this.selectedTier)
        .then((price: number) => {
          this.adjustedCurrentTierPrice = (price + this.generatePriceWithAncills());
          this.redrawTable();
        });
    } else {
      let ancillary = this.selectedTier.ancillaries.find(ancillary => ancillary.code === ancillaryCode);
      this.adjustedCurrentTierPrice += ancillary.price + ancillary.taxAmount;
    }

    this.rows = this.getRows();
  }

As you can see, the above function contains the call to the function which returns a promise.

public getRequote(tier): Promise<number> {
    return new Promise((resolve, reject) => {
      this.Modal.load('loading', true);
      const quotePayload: Quote = {
        ...this.quoteRequest,
        quoteNumber: this.quoteResponse.quoteResponse.quoteRetrieval.quoteNumber,
        quoteVersion: this.quoteResponse.quoteResponse.quoteRetrieval.quoteVersion,
      };

      this.quoteService.getRequote(quotePayload, [...this.ancillariesArray], this.selectedTier)
        .subscribe((response) => {
          this.Modal.close('loading', true);
          this.quoteResponseStore.change(response);

          // remove this.quoteResponse to use this.quoteResponse.get()
          this.quoteResponse = response;
          const selectedTierQuote = response.quoteResponse.homeInsuranceQuote.home[0].tiers.find((tierIteration) => {
            return tier.name === tierIteration.name;
          });

          resolve(selectedTierQuote.annualPremium.total);
        });
    });
  }

And as you can see here, this function returns the promise which itself resolves after the observable has been subscribed too.

Here is my attempt at testing this:

fit('Should call call the Quote Service Requote method and update premium when AD is given to addAncillary method', fakeAsync(() => {
        const quoteServiceMock = TestBed.get(QuoteService);
        const modalServiceMock = TestBed.get('Modal');

        let quoteServiceSpy, addAncillarySpy, modalLoadingSpy;

        quoteServiceSpy = spyOn(quoteServiceMock, 'getRequote').and.callThrough();
        addAncillarySpy = spyOn(component, "addAncillary").and.callThrough();
        modalLoadingSpy = spyOn(modalServiceMock, 'load').and.callThrough();

        component.addAncillary(AncillaryCode.BuildingsAD);
        flush();

        fixture.whenStable()
            .then(() => {
              expect(addAncillarySpy).toHaveBeenCalledWith(AncillaryCode.BuildingsAD);
              expect(modalLoadingSpy).toHaveBeenCalled();
              expect(quoteServiceSpy).toHaveBeenCalled();

              expect(component.adjustedCurrentTierPrice).toEqual(132.55);

              fixture.detectChanges();
              expect(fixture.nativeElement.querySelector('#total-premium').textContent).toEqual(' £132.55 ');
            });
      }));

Can anyone see what I am going wrong here? The test itself is not working as expected at the price that is tested at the bottom is not being updated from the mocked service. I have mocked the quote service in the test too so real http calls aren't happening.

Thanks

Python mock returns a MagicMock object instead of a specified result value

I want to mock test this function:

def foo():
  client = boto3.client(some_args)
  return client.func_A(other_args)

So I mock boto3 in my test:

def test_foo():
  with patch('boto3') as mock_boto3:
    mock_boto3.return_value.client.return_value.func_A.return_value = 'test_val'
    foo()

The proiblem with this is that func_A returns a MagicMock object instead of the specified return value. What am I doing wrong?

<MagicMock name='boto3.client().func_A()' id='140131668642896'>

Testcafe giving an error when trying to navigate to a new page using an encrypted URL string.

I'm getting an error when trying to navigate to a page using testcafe.

Normally it is fine moving between the pages of the website but when trying to access pages which have encrypted URLs, specifically in this case a contact's details, it duplicates the string query in the URL and then gives the error that is shown in the attached image.

My question is why is testcafe doing this string duplication and how can we either work around it or fix it?

error message that I'm getting when trying to navigate to the URL that is encrypted.

How do you write code that you cannot run?

I am a junior Software developer in a small company.

The thing I am asking is, how are you supposed to write code that you can not actually run yet?

There is a framework which I am supposed to extend. It is a bit documented and the codebase is not too big yet. It is not runnable yet. I just struggle to commit code for a new adapter. My main problem is not knowing if my code is runnable as it is. The project manager said to just commit the code. But how can you start fixing code when you already wrote five adapters afterwards?

I guess this is what software development is about. Adapting and just trying. I feel like I am building a car without the proper knowledge, where I just start the inspection of the different parts once the car is built and the gas tank is filled.

I don't need to test everything. But at least running the whole application once would be nice. The problem is, that there are many dependables which would need to be compiled as well. But for that the project has to many construction sited going on.

Any help on what mindset is needed here or the like?

Thanks in advance!

There is a mobile app having generic search.It Searches Contacts,SMS,Mails and Web and displays results in 4 columns

Above search results are displayed in 4 columns.

Eg. Contacts | SMs | Mails |Web

I was asked to come up with out of the box test scenarios.

Also ,

No new class instance created after calling new class() within a jest test

Issue

Creating new class instance within unit test does not trigger the constructor.


Details

I am trying to test if an error is thrown when the wrong server IP is given, however when I try to create a new instance of the class that should throw the error it does not work.

The class I am trying to test is:

export class ClassA {
    private readonly _redisServerIP = config.redisServerIP;
    private readonly _redisServerPort = config.redisServerPort;

    constructor() {
        console.log(this._redisServerIP);
        this.configure();
    }

    private configure(): void {
        this._redisSub = redis.createClient({host: this._redisServerIP, port: this._redisServerPort});

        this._redisSub.on('error', (error) => {
            if (error.code === "ECONNREFUSED") {
                this._logger.error('Could not create a redisSub, is the redis server running?');
            }
            throw new Error('Something bad happened');
        });
    }
}

This is my test code:

import * as constants from '../src/config/config';

let socket;
let classA;
let httpServerAddr;

beforeAll((done) => {
classA = new ClassA();
    httpServerAddr = classA.getServerIp();
    done();
});

afterAll((done) => {
    done();
});

beforeEach((done) => {

});

afterEach((done) => {
    done();
});

describe('Socket.io redis testing', () => {
    test('should fail due to invalid serverIP', (done) => {
        constants.config.redisServerIP = "0.0.0.0";
        classA = null;

        expect(() => {
            classA = new ClassA();
            done();
        }).toThrow();
    });
});

I only see the server ip once in my node console and the test fails due to the following error:

expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.

Is this because every test runs in it's own promise? And when it's running in that said promise it can't log to the console? Or is it because of me not clearing the existing instance of ClassA before calling new ClassA()?

Selenium or Any other best UI test automation framework with very less maintenance suggestions?

Dear Experts,

Suggest me a best test automation framework with less maintenance work.

Problem Statement:

Currently im using test automation framework built by Selenium Whenever there is a changes in the DOM(Document Object Model) - the element identification fails. here comes the maintenance activity(complex) for failing scripts.

I'm not familiar on latest trends.

Need suggestions \ guidance on the latest or Best UI Automation framework with very little maintenance activity.

Also happy to know your preference and reason too

Appreciate your suggestion and directions

Testing localized strings in Flutter

When I try to test Widget that contains

 hintText: LocalizationResources.of(context).writecomment

I get an Exception saying:

The following NoSuchMethodError was thrown building CommentInput(dirty, state: _CommentInputState#32224): The getter 'writecomment' was called on null.

So, is there something that I'm missing? Widget builds nicely on a device and a simulator.

This is how my test looks like:

....
 final Widget widget =
        MaterialApp(home: CommentWallWidget(channelUid: '123456'), title: 'jelena',);

    await tester.pumpWidget(widget);

And the LocalizationResources is just simple l10n:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import 'l10n/messages_all.dart';

///class containing localization logic and string getters
class LocalizationResources {
  static Future<LocalizationResources> load(Locale locale) {
    final String name =
        locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);

    return initializeMessages(localeName).then((_) {
      Intl.defaultLocale = localeName;
      return LocalizationResources();
    });
  }

  static LocalizationResources of(BuildContext context) {
    return Localizations.of<LocalizationResources>(
        context, LocalizationResources);
  }
....

collect.ImmutableSortedSet.toImmutableSortedSet(Ljava/util/Comparator;)Ljava/util/stream/Collector;

Hi am trying run my test on AWS DeviceFarm I am getting this error every time.can anyone help me to solve this issue

[TestNG] java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet(Ljava/util/Comparator;)Ljava/util/stream/Collector;

Testing Basic Slice / Array

So am new to the whole unit testing landscape. I am using Go 1.11.2 and I have built the below func, its for a wider example project I am hoping to be able to build. But I thought that as some of these functions will be simple, it would be a good place to start some testing.

Function below builds/makes a slice - as I see it this is an array, has I have given it a hard length. Then once built it returns the data, but I am unsure how best to go - :) - about doing the testing for this function?

func makeNumbers() []int {
  numbs := make([]int, 10)

  numbs[0] = 0
  numbs[1] = 1
  numbs[2] = 2
  numbs[3] = 3
  numbs[4] = 4
  numbs[5] = 5
  numbs[6] = 6
  numbs[7] = 7
  numbs[8] = 8
  numbs[9] = 9

  return numbs
}

This is what I have done so far:

func TestMakeNumbers(t *testing.T) {

  t.Run("collection of 5 numbers", func(t *testing.T) {

    got := makeNumbers()
    want := make([]int, 6)

    if reflect.DeepEqual(got, want) {
        t.Errorf("got %d want %d given", got, want)
    }
  })

  t.Run("collection of any size", func(t *testing.T) {
    // numbers := []int{1, 2, 3}

    got := makeNumbers()
    want := make([]int, 10)

    if reflect.DeepEqual(got, want) {
        t.Errorf("got %d want %d given", got, want)
    }
  })

}

The testing function is in main_test.go while the makeNumbers function is in my main.go file.

When I run go test this passes, but I am not sure I am doing it right?

What I wanted, is to build two conditions, one where it would fail, e.g. makeNumbers set to return a bigger array or an array of strings... something like that. Then the next condition would be to make a condition telling it what I need, e.g. an array of int's 0-10.

All help most welcome.

Thanks.

How to test void method in typescript

hey everyone i want to test some code with void method... i have code like this, i very confused with test, i didnt have idea with this test. i make test with jasmine and karma

getMenu(): void {
    this.service.getMenuItems()
    .subscribe(navigation => {
      this.navigationModel = navigation.menu;
    });
  }

this is the code... how i can test this code. everyone who want help me... i hope someone can solve my problem with this test. i have search all with the same problem but i didnt understand. so please help me to solve my testing problem code

Test in Python, you need to choose the correct statement

Question 1 Fork system call

1.used to get the pid of the parent process

2.used to call functions in separate threads

3.ed to create a child process

4.creates an exact copy of the parent process

 Question 2 Fork system call

  1. in the parent process, calling the fork returns the pid of the child
  2. in the child process, calling fork returns 0
  3. in the child process, calling fork returns the pid of the parent process
  4. in the parent process, the call to fork returns 0

     Question 3 What happens to the memory in the child process when working with Python?

  5. Copied from parent process

  6. Shared with parent process

Question 4 File Descriptors in the child process

  1. will be rediscovered by the Python interpreter automatically
  2. will be unavailable, they need to be rediscovered
  3. will be copied and rediscovered
  4. will be copied

     Question 5 Highlight true expressions:

  5. it is preferable to use the context manager to work with locks in Python

  6. locks must be taken in the same order, released in an arbitrary
  7. locks must be taken in the same order, released strictly in the same manner
  8. locks must be taken in the same order, released in reverse

     Question 6 Queues slow down the workflow of Python threads, better use blocking objects

  9. Not

  10. Yes

     Question 7 Highlight true expressions:

  11. GIL slows down the execution of the main control flow in Python3, even if there are no other threads.

  12. GIL does not affect the execution of individual processes in Python3.
  13. GIL prohibits simultaneous execution of bytecode instructions in different streams.
  14. GIL is needed to protect the interpreter's memory from damage

. Question 8 If a Python program performs many I / O operations (IO-bound), then to speed up its work you need

  1. break it into separate functions, execute them in streams
  2. create separate processes

     Question 9 If a Python program performs calculations that require only a CPU (CPU-bound), then to speed up its work,

  3. break it into separate functions, execute them in streams

  4. create separate processes

Question 10 Python generator is

  1. yield instruction
  2. function in which there is a yield statement
  3. special call yield from
  4. object of type concurrent.futures.Future

Question 11 Mark all true statements:

  1. the generator stores the value to generate the next sequence element in local variables
  2. exception StopIteration is used to stop the iterator
  3. the iterator stores the value to generate the next sequence element in self
  4. the iterator interrupts its execution at each iteration, preserving the state of local variables

     Question 12 Mark all true statements:

  5. exceptions cannot be handled in coroutines; this should be done in the main thread

  6. from one coroutine, you can call another with yield from
  7. coroutines are executed in separate threads in parallel
  8. The coroutine can interrupt its work, preserving its state and the values ​​of all local variables

Question 13 Mark all true statements regarding the asyncio event loop:

  1. allows you to perform callable functions and python objects
  2. performs all the corutines in sequence, switching the context between them
  3. responsible for memory allocation in the main process
  4. allows you to perform korutiny registered in it
  5. performs several corutin in parallel in different threads
  6. switch context between python threads

     Question 14 Mark all true statements:

  7. an object of type asyncio.Task stores the associated coruntine and contains the status of its execution

  8. the blocking code in Python will not affect the execution of other korutin in the asyncio event loop
  9. You can create chains from objects of the asyncio.Future type and wait for them to run in the asyncio event loop
  10. an object of type asyncio.Task is executed in a separate control flow, without affecting the execution of other objects of type asyncio.Task

mercredi 28 novembre 2018

How to user json response token in jmeter

I need your help.

I am recording a website then its response token generate in Json Format. I am using Json Extractor then authentication failed. Please help to short out this issue.

My json Response is :

{ "token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBMjIwOSIsInNjb3BlcyI6W3siYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9XSwiaXNzIjoiaHR0cHM6Ly9mcmVzY2hlc29sdXRpb25zLmNvbSIsImlhdCI6MTU0MzQ3NjAxNywiZXhwIjoxNTQzNDk0MDE3fQ.67F7RwjHd4dPteJ77F-QmxSRcv_Wcma_cXh_pnwrfUo", }

I am using this Json Extractor enter image description here

And this is my json response image:

enter image description here

when i am using like this then authentication failed , Please help me guy so i can fixed this issue.

Thanks,

Jest - Mocking a function call within the handleSubmit of a form

I am trying to write a test that mocks the calling of a function within the handleSubmit of a form, however, I am unable to show that the function has been called.

The form is as follows:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import signUp from '../../actions/users/sign_up';
import PropTypes from 'prop-types';

class Signup extends Component {
  constructor (props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.showError = this.showError.bind(this);
  }

  handleChange(event) {
    const target = event.target;

    this.setState({ [ target.name ]: target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    this.props.signUp(this.state);
  }

  showError(type) {
    if (this.state && this.state.error && this.state.error.data.errors[ type ]) {
      return this.state.error.data.errors[ type ][ 0 ];
    }
  }

  componentDidUpdate (prevProps, prevState) {
    const props = this.props;

    if (prevProps === props) {
      return;
    }

    this.setState({
      ...props,
    });
  }

  render () {
    return (
        <div className='container-fluid'>
            <div className='row'>
                <div className='col col-md-6 offset-md-3 col-sm-12 col-12'>
                    <div className='card'>
                        <div className='card-header'>
                            <h4>Sign Up</h4>
                        </div>
                        <div className='card-body'>
                            <form onSubmit={ this.handleSubmit } >
                                <div className="form-row">
                                    <div className="form-group col-md-12">
                                        <label htmlFor="email">Email</label>
                                        <input
                        type="email"
                        name="email"
                        className={ `form-control ${ this.showError('email') ? 'is-invalid' : '' }` }
                        id="email"
                        placeholder="Email"
                        onChange={ this.handleChange }
                      />
                                        <div className="invalid-feedback">
                                            { this.showError('email') }
                                        </div>
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group col-md-12">
                                        <label htmlFor="username">Username</label>
                                        <input
                        type="text"
                        name="username"
                        className={ `form-control ${ this.showError('username') ? 'is-invalid' : '' }` }
                        id="username"
                        placeholder="Username"
                        onChange={ this.handleChange }
                      />
                                        <div className="invalid-feedback">
                                            { this.showError('username') }
                                        </div>
                                    </div>
                                </div>
                                <div className="form-row">
                                    <div className="form-group col-md-12">
                                        <label htmlFor="password">Password</label>
                                        <input
                          type="password"
                          name="password"
                          className={ `form-control ${ this.showError('password') ? 'is-invalid' : '' }` }
                          id="password"
                          placeholder="Password"
                          onChange={ this.handleChange }
                        />
                                        <div className="invalid-feedback">
                                            { this.showError('password') }
                                        </div>
                                    </div>
                                    <button type="submit" className="btn btn-primary">Sign Up</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
  }
}

function mapStateToProps (state) {
  return {
    email: state.UsersReducer.email,
    username: state.UsersReducer.username,
    password: state.UsersReducer.password,
    error: state.UsersReducer.error,
  }
}

function mapDispatchToProps (dispatch) {
  return bindActionCreators({
    signUp: signUp,
  }, dispatch);
}

Signup.propTypes = {
  email: PropTypes.string,
  username: PropTypes.string,
  password: PropTypes.string,
  signUp: PropTypes.func.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(Signup);

I am trying to simulate the fact that the form will be submitted with the values obtained from the form inputs, which are in the form's state (email, username and password).

The test I currently have is:

import React from 'react';
import { shallow, mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import { bindActionCreators } from 'redux';
import thunk from 'redux-thunk';

import Signup from '../../../components/users/signup';
import UsersReducer from '../../../reducers/reducer_users';

describe('<Signup />', () => {
  describe('render()', () => {
    test('submits the form data',  async () => {
      const mockStore = configureStore([thunk]);

      const initialState = {
        UsersReducer: {
          email: '',
          username: '',
          password: '',
        },
      };

      const store = mockStore(initialState);

      const signUp = jest.fn();

      const wrapper = shallow(<Signup store={store} signUp={signUp} />);
      const component = wrapper.dive();

      component.find('#email').simulate(
        'change', {
          target: {
            name: 'email', value: 'foo@gmail.com'
          }
        }
      );

      component.find('#email').simulate(
        'change', {
          target: {
            name: 'username', value: 'foo'
          }
        }
      );

      component.find('#password').simulate(
        'change', {
          target: {
            name: 'password',
            value: '1234567',
          }
        }
      )

      component.find('form').simulate(
        'submit', {
          preventDefault() {}
        }
      )

      expect(signUp).toHaveBeenCalledWith({
        email: 'foo@gmail.com',
        username: 'foo',
        password: '12345678'
      });
    });
  });
});

But I keep getting the following error no matter what I try.

Expected mock function to have been called with:
  [{"email": "foo@gmail.com", "password": "12345678", "username": "foo"}]
But it was not called.

Any assistance would be greatly appreciated.

How to test the cuda program

I have written a cuda program for vector addition and vector multiplication but I don't know how to test the outputs for the program, whether the answer/output is correct or not.Is there any way to test the correctness of the program and aslo is there any online dataset to use for cuda vector/matrix addition/multiplication ?

For loop prints log to console prior to the action actually occurred

i am automating a spec which create sales quotation

for(var j=0;j<1000;j++)
{    
  element(by.cssContainingText('option','Sales Quotation')).click();
  element(by.id('Vendor_Customer_Name')).sendKeys("Abc enterprise");
  browser.driver.sleep(2000); // wait for rendring data
  element.all(by.css(".ui-corner-all")).first().click();
  for(var i=0; i<data.length;)
  {
    element(by.id('ItemCode_1')).sendKeys(data[i].Value);
    i++;
    browser.actions().sendKeys(protractor.Key.ENTER).perform();
    element(by.id('ItemQty_1')).sendKeys(data[i].Value); //Qty for quote
    i++;           
    browser.actions().sendKeys(protractor.Key.TAB).perform();
    browser.actions().sendKeys(protractor.Key.TAB).perform();
    element(by.id('ItemRate_1')).sendKeys(data[i].Value);
    i++;
    browser.actions().sendKeys(protractor.Key.TAB).perform();
    browser.actions().sendKeys(protractor.Key.TAB).perform();
    browser.actions().sendKeys(protractor.Key.TAB).perform();
    browser.actions().sendKeys(protractor.Key.ENTER).perform();
  }
  element(by.id('lnkSubmit')).click();
  element(by.xpath('//*[@id="lblSuccessMessage"]/button')).click();
  console.log("Sales Quotation No... ->"+j);
}

What it does is it prints sales quotation no. from 1 to 1000 prior to any single Sales Quote is really created how can i make it to print 1 by after Sales quotation is created

Upload and Download File over Remote Node without Input Tag as File type

I am Automating a Scenario for Web Application Over Windows which includes the File And Images to be Uploaded to a website, and on my local it is working fine through robot class **

  • but when i execute my tests over Jenkins my jobs get failed. I need to Upload my file to a web site executing over Remote machine.

**

  • For File Upload :- I cannot simply upload the file using send keys method since The Input tag doesn't have File Type i.e. input[type!='file']. Are there any other solutions to achieve this without using Robot Classes and Auto-It.

**

  • For File Download:-

** And I also need to download the File from a web Application over remote and verify that it has been downloaded successfully provided there is no API for this. When the file gets downloaded over the remote, I am not able to verify that whether it has been downloaded or not since Remote Machine execution is not visible. Is there any way to achieve this, kindly please suggest.

Django testing in creating a user with email address which is from session input, assertRedirects is not working

The user creation is using an email address as USERNAME_FIELD and it is extracted from session and save in the form save(). It seems it is not going further down to the redirection. How can I test the redirection in this case?

tests.py:

class RegistraionViewTest(TestCase):

    valid_data = {
        'email': 'good@day.com',
        'password1': 'test1234', 
    }

    kwargs = {
        'email': 'good@day.com'
    }

    def test_registration(self):
        response = self.client.post(reverse('registration'), data=self.valid_data, follow=True)
        self.assertTrue(response.context['form'].is_valid())

        # mocking the session input
        response.context['form'].save(email=self.kwargs['email'])
        self.assertTrue(account.check_password(self.valid_data['password1']))

        # working so far, but it seems there is no redirect url in response
        self.assertRedirects(response, reverse('next_url'))

In views.py:

   if request.method == 'POST':
    form = RegistraionForm(request.POST)

    if form.is_valid():   
        email = request.session.get('email') 
        try: 
            account = form.save(email=email)
            return HttpResponseRedirect('next_url'))

In forms.py:

def save(self, **kwargs):
    user = super(RegistrationForm, self).save(commit=False)
    user.email = kwargs.pop('email')
    user.save()
    return user

It seems there is no url in the response in tests.py. What went wrong here?

Getting the position of a widget in a Flutter test?

How do you get the position of a Widget in a Flutter test? Ideally the center of the widget, but the top left coordinate would be fine too.

This is my test and attempt at a function that finds the location of a Widget on screen.

  testWidgets('Pin is in center of screen', (WidgetTester tester) async {
    await _setUp(tester); // Does setup
    final findPin = find.byKey('pin');
    final pinLocation = _getLocation(findPin.evaluate().first);
    print(ui.window.physicalSize);
    expect(pinLocation.dx, 1200.0);
    expect(pinLocation.dy, 900.0);
  });

Offset _getLocation(Element element) {
  return (element.findRenderObject() as RenderBox).localToGlobal(Offset.zero);
}

The printing for ui.window.physicalSize (where ui is the dart:ui package) tells me the size is Size(2400.0, 1800.0). However, when I set those midpoints in my test, my test fails, saying that the Size is actually 395.0 and 305.0. My widget is only 30.0 x 30.0 in size, and even 395 +/- 30 doesn't equate anything in the 1200 range.

In my test, I then wrapped my widget inside a Container of predefined width (400) and height (300), which is not how it looks in the real app, but for the purposes of testing it's much closer - giving a "center" of 195 and 155, when it should be 200 and 150.

The widget I'm testing (in the code, not with the extra Container in my testWidgets) is approximately:

return Center(
    child: Container(
      key: Key('pin'),
      height: 30.0, 
      width: 30.0, 
      color: Colors.pink,
   ),
);

Testing code with a universal catch with Jest - race condition

I just realized all of my test code has a race condition.

My style pattern follows something like this:

const myFunc = (callback) => {
    return somePromise().then((result) => {
        return someOtherPromise();
    }).then((result) => {
        db.end(() => {
            callback();
        });
    }).catch((err) => {
        db.end(() => {
            callback(err);
        });
    });
};

I'm testing with Jest. Test code looks something like this.

it('should work', (done) => {
    // mock stuff
    let callback = () => {
        expect(...);
        done();
    };

    myFunc(callback);
});

I have dozens of functions and tests following this pattern. The last test I wrote was giving me a Jest matcher error in my callback. After much confusion, I realized that the first callback execution is throwing the Jest failure, and the callback with the err parameter is being executed and failing before done() is called by the first callback execution.

I'm realizing this pattern might be absolutely terrible. I've managed to beat the race condition by having certain expect() calls in certain order, but that's no way to do this.

How can I remove the potential for the race condition here?

I'm open to completely changing the style I do this. I know my Javascript isn't particularly amazing, and the system is still pretty early in its development.

JAVA - can't imort src/test/java to src/main/java

I have created an E2E testing project, initially, all the java classes were in 'src/test/java", but now I want to move all the files that do not contain tests to the "src/main/java" folder, the problem is after I do it:
I can't import packages from "src/test/java" to "src/main/java" (but can do the opposite). like the packages do not exist at all for import.

Cleaned the project and tried to run via IDE and via maven and it does not change the result.

enter image description here

What am I doing wrong?

Factory for iOS Models on iOS

I'm starting a new project and the I have a really hight testing requirements. The app is very "data intensive" lots of models and models nested.

I'm trying to think a good way to be able to organize and create fake models I'm going to be using to test ViewModels.

I'm looking for something similar to FactoryGirl on ruby but I can't find anything similar for iOS.

Any advise?

Jest - Testing functions based in other functions

I'm testing my new module:
- It has multiple basic functions, e.g.: addItem(item), rmItem(item), etc.
- But also I have bulk functions which basically receive an array of items and iterate over it calling the basic functions:

addItems = (items) => {
  items.forEach(item => addItem(item))
}

rmItems = (items) => {
  items.forEach(item => rmItem(item))
}

I have, already, tested my basic functions and I'm trying to test my bulk functions.

BUT my problem is: How can I test my bulk function mocking the basic function for this specific case?

I'm trying something like:

import List from '/src/list.js';

it('test basic functions', () => {...}) <- It works cool
it('test bulk function', () => {
  const list = new List();
  list.addItems([1, 2, 3, 4]);

  expect(list.addItem).toHaveBeenCalledTimes(4);
})

My main problem is, I should be mocking addItem for the addItems test. But I can't find a way to do it.

Program Testing Coverage with JaCoCo

I am testing a short program using JaCoCo, and I have almost achieved 100% coverage, except this is the only statement I can't seem to test, what test suite can I write to be able to cover the whole program? Attached below is the code. Here is a screenshot of my JaCoCo report

Pt. 2

no such table: ken_users when executing testing method setUp() with Laravel / PHPUnit

I work with Laravel 5.6, PHPUnit 7.1.1

Right now, all my tests work, I use in memory sqlite db, and everything is fine.

Now, I just execute

composer update

and now all my tests fail when executing first method of test, setUp():

    Caused by
PDOException: SQLSTATE[HY000]: General error: 1 no such table: ken_users

/Users/julien/Documents/Projets/kendozone/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:77
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Connection.php:452
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Connection.php:657
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Connection.php:459
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php:88
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:264
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Schema/Builder.php:149
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:223
/Users/julien/Documents/Projets/kendozone/database/migrations/2014_10_12_000000_create_users_table.php:58
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:359
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:366
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:177
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:146
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:95
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:70
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:87
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:31
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Container/Container.php:564
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Console/Command.php:179
/Users/julien/Documents/Projets/kendozone/vendor/symfony/console/Command/Command.php:255
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Console/Command.php:166
/Users/julien/Documents/Projets/kendozone/vendor/symfony/console/Application.php:893
/Users/julien/Documents/Projets/kendozone/vendor/symfony/console/Application.php:262
/Users/julien/Documents/Projets/kendozone/vendor/symfony/console/Application.php:145
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Console/Application.php:89
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Console/Application.php:188
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:250
/Users/julien/Documents/Projets/kendozone/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:223
/Users/julien/Documents/Projets/kendozone/vendor/laravel/browser-kit-testing/src/TestCase.php:75
/Users/julien/Documents/Projets/kendozone/tests/functional/UserTest.php:25

I use BrowserKitTesting package, and did not redefined setUp() method.

I also tried to set all the plugin to version that make my test pass, but it doesn't work. In particular, I also tried not to update phpunit and setting it to the 'working' version, but with no success.

Any idea ?

.then() vs aysnc and await protractor

I am new to protractor and have been reading up on promise chaining using the .then() function.

For example

 this.getContent = function(content) {
    return element.all(by.repeater('item in list')).filter(function(elem) {
        return elem.getText().then(function(text) {
            return text;
        });
    }).first();
};

Which works fine to get the text i'm looking for. However, how can i restructure this to use async and await instead of the the .then() function?

Every time I try i just get a element explorer and no text.

Thanks in Advance

Preventing the Android Monkey from starting Activities

I have an app that I want to Monkey Test with the Android ADB Monkey Exerciser. I want the "monkey" to mess around in a list view of Items, but prevent it from going to the payment/order activity. I thought it would be enough adding the Monkey Category in the activity intent-filter to all activities except the payment/order activity. But the Monkey still manages to click it's way in to the Payment/Order Activity.

The package parameter works as expected, but not the Category param.

-c main-category

If you specify one or more categories this way, the Monkey will only allow the system to visit activities that are listed with one of the specified categories. If you don't specify any categories, the Monkey will select activities listed with the category Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY. To specify multiple categories, use the -c option multiple times — one -c option per category.

https://developer.android.com/studio/test/monkey

This is how my Activities with the Monkey category typically looks like. My problem is that the Monkey Allows start of Activities without the Monkey Category.

<activity
    android:name=".activity.SomeActivity"
    android:parentActivityName=".activity.drawer.ParentActivity">
  <intent-filter>
    <category android:name="android.intent.category.MONKEY"/>
  </intent-filter>
</activity>

This is how my ADB command typically looks like.

monkey -p <my.package.name> -c android.intent.category.MONKEY -v -v 200

After reading the Monkey source code my understanding is that the category Monkey only works when the Monkey tries to start an Main Activity with an Implicit Intent, and that the categories is ignored when the app is starting Explicit Intents within the app. https://android.googlesource.com/platform/development/+/master/cmds/monkey/src/com/android/commands/monkey/Monkey.java

Cucumber test cases fail when run together, but they pass when I run them individually

I am using Spring with Cucumber (and IntelliJ and Gradle). My test case fails when run together and passes when run individually. (The fails 2 out of 3 times, sometimes it works...)

I also tried to quarantine the problematic Scenario or Senario combinations, but no luck... I tried introducing @After and @Before hooks to reset the value of of the account value... I even tried switching the position of senarios, nothing helps...

I really hope someone can help me with this problem

The features:

Feature: Cash Withdrawal
  Scenario: Successful withdrawal from an account in credit
    Given my account has been credited with $100.00
    When I withdraw $20
    Then $20 should be dispensed
    And the balance of my account should be $80.00
  Scenario: Unsuccessful withdrawal due to technical fault
    Given my account is in credit
    But the cash slot has developed a fault
    When I request some of my money
    Then I should see an out-of-order message
    And $0 should be dispensed
    And the balance of my account should be unchanged
  Scenario: Unsuccessful withdrawal due to insufficient ATM funds
    Given my account is in credit
    And the ATM contains $10
    When I withdraw $20
    Then I should see an ask-for-less-money message
    And $0 should be dispensed
    And the balance of my account should be unchanged

And my stepdefinitions:

public class AccountSteps {

    @Autowired
    Account account;

    private Money originalBalance;

    @Given("^my account has been credited with (\\$\\d+\\.\\d+)$")
    public void myAccountHasBeenCreditedWith$(
            @Transform(MoneyConverter.class) Money amount)
            throws Throwable {
        account.credit(amount);
    }

    @Given("^my account is in credit$")
    public void myAccountIsInCredit$() throws Throwable {
        originalBalance = new Money(30, 00);
        account.credit(originalBalance);
    }

    @Then("^the balance of my account should be unchanged$")
    public void theBalanceOfMyAccountShouldBeUnchanged() throws Throwable {

        checkBalanceIs(originalBalance);
    }

    @Then("^the balance of my account should be (\\$\\d+\\.\\d+)$")
    public void theBalanceOfMyAccountShouldBe$(
            @Transform(MoneyConverter.class) Money amount) throws Throwable {

        checkBalanceIs(amount);
    }

    private void checkBalanceIs(Money amount) throws Throwable {
        int timeoutMilliSecs = 3000;
        int pollIntervalMilliSecs = 100;

        while (!account.getBalance().equals(amount) && timeoutMilliSecs > 0) {
            Thread.sleep(pollIntervalMilliSecs);
            timeoutMilliSecs -= pollIntervalMilliSecs;
        }

        Assert.assertEquals(
                "Incorrect account balance -",
                amount,
                account.getBalance());
    }
}

public class CashSlotSteps {

    @Autowired
    TestCashSlot cashSlot;

    @Given("^\\$(\\d+) should be dispensed$")
    public void $ShouldBeDispensed(int dollars) throws Throwable {
        Assert.assertEquals("Incorrect amount dispensed -", dollars,
                cashSlot.getContents());
    }

    @Given("^the cash slot has developed a fault$")
    public void theCashSlotHasDevelopedAFault() throws Throwable {
        cashSlot.injectFault();
    }

    @Given("^the ATM contains \\$(\\d+)$")
    public void theATMContains$(int dollars) throws Throwable {
        cashSlot.load(dollars);
    }
}

public class TellerSteps {

    @Autowired
    private Account account;

    @Autowired
    private AtmUserInterface teller;

    @When("^I withdraw \\$(\\d+)$")
    public void iWithdraw$(int amount) throws Throwable {
        teller.withdrawFrom(account, amount);
    }

    @Given("^I request some of my money$")
    public void iRequestSomeOfMyMoney() {
        int dollarsRequested = 10;
        teller.withdrawFrom(account, dollarsRequested);
    }

    @Then("^I should see an out-of-order message$")
    public void iShouldSeeAnOutOfOrderMessage() throws Throwable {
        Assert.assertTrue(
                "Expected error message not displayed",
                teller.isDisplaying("Out of order"));
    }

    @Then("^I should see an ask-for-less-money message$")
    public void iShouldSeeAnAskForLessMoneyMessage() throws Throwable {
        Assert.assertTrue(
                "Expected error message not displayed",
                teller.isDisplaying("Insufficient ATM funds"));
    }
}

Unable to intercept request [Puppeteer JS]

In app both when testing manually and in puppeteer the request is being done and the data is being used,so i know the problem isnt there.I tryed multiple ways to accees and intercept the requests ot atlest try to replace the data that is coming from the api as start but didnt manage to do anything.I copied the code below from answer from github issues page that seems the fix the other person's problem.

import puppeteer from 'puppeteer';
describe('index', () => {
  let page;
  beforeAll(async () => {
    jest.setTimeout(30000);
    const browser = await puppeteer.launch({
      headless: false,
      slowMo: 250,
      args: ['--windows-size=1920,1080']
    });
    page = await browser.newPage();
    await page.goto('http://localhost:1234/');
  });
  afterAll(() => {
    browser.close();
  });
  it('should have title "Fonoapi app"', async () => {
    const title = await page.title();
    expect(title).toMatch('Fonoapi app');
  });
  describe('searching for device', () => {
    const device = {
      brand: 'lenovo',
      model: 'p70'
    };
    const constants = {
      url:
        'https://fonoapi.freshpixl.com/v1/getdevice?brand=lenovo&device=p70&token=d1191e0a0b1cb4cdc6b573126ca98b321b703f1ebe49fe7b',
      array: [
        {
          Brand: 'Lenovo',
          DeviceName: 'Lenovo P700i',
          alert_types: 'Vibration; MP3, WAV ringtones'
        }
      ]
    };

    beforeAll(async () => {
      await page.waitForSelector('.search-form');
      await page.type('input[name=brand]', device.brand);
      await page.type('input[name=model]', device.model);
      await page.$eval('.search-btn', btn => btn.click());
      await page.setRequestInterception(true);
      await page.on('request', interceptedRequest => {
        if (interceptedRequest.url() === constants.url) {
          interceptedRequest.respond({
            status: 200,
            contentType: 'application/javascript; charset=utf-8',
            body: JSON.parse(constants.array)
          });
        } else interceptedRequest.continue();
      });

      await page.waitForSelector('.device-card');
    });
    
  });
});

How do you mock or set device width/height in Flutter Widget test?

I'm writing Widget tests in Flutter and need to be able to test my layouts on different device sizes.

The headless device size is always 600 height and 800 width. I want to be able to specify the size in my test. Some of the UI logic is dependant on device size and can't be tested unless I can set this size.

How do I run the same scenario simultaneously on the same browser?

How do I run the same scenario simultaneously on the same browser (if on chrome on new windows), the purpose is test if anything goes wrong when multiple users are using the same functions.

Django tests display traceback of expected exception in assertRaises

I'm testing a django view with APIClient. One of the test cases checks whether an exception is raised:

    self.assertRaises(
        IntegrityError,
        self.client.post,
        path='/some/url/to/view/',
        data={
            'test': 'data'
        },
        format='json'
    )

Although the test passes, the client call raises the expected exception with printing the full traceback. Can I somehow change this behaviour? I don't want to see numbers of tracebacks in my test run as this is a common test case.

Stress, spike, destroy tests in a Production

Have you ever heard about stress, spike, destroy tests in a Production? (We talk about clusters. It isn't a simple web server) What is company do this tests? What type of methods usually use?

Thanks a lot

How to run a simple botium test against watson

I am attempting to test botium against watson assistant following the wiki.

Running:

  • MacOS High Sierra 10.13.06
  • Node 8.10
  • Npm 6.4.1

Step by step what I did:

  • I installed botium-cli: npm i botium-cli -g
  • Setup the following folder structure

enter image description here

Where this is my package.json:

{
  "name": "botium",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "emulator": "botium-cli emulator console --convos ./spec/convos --config ./botium.json",
    "emulatorBrowser": "botium-cli emulator browser --convos ./spec/convos --config ./botium.json"
  },
  "author": "",
  "license": "ISC"
}

And this is my botium.json:

{
    "botium": {
      "Capabilities": {
        "PROJECTNAME": "botium-sample1",
        "CONTAINERMODE": "watsonconversation",
        "WATSON_URL": "https://gateway-fra.watsonplatform.net/assistant/api",
        "WATSON_USER": "<WATSON_USER_ID>",
        "WATSON_PASSWORD": "<WATSON_PASSWORD",
        "WATSON_WORKSPACE_ID": "<WATSON_WORKSPACE_ID>"
      },
      "Sources": {},
      "Envs": {
        "NODE_TLS_REJECT_UNAUTHORIZED": 0
      }
    }
}

Expected behavior:

As I execute npm run emulator I would expect botium to send the utterances specified in spec/convos/captain.convo.txt to watson and compare this against the specified test.

Actual behavior:

Error: Loading Botium plugin failed
    at Validate.Validate.then (/Users/user/workspace/testing/botium/node_modules/botium-cli/node_modules/botium-core/src/containers/PluginConnectorContainer.js:56:15)
    at <anonymous>

Issue with PublishSubject and TestScheduler, item isn't emitted

I have been facing an issue with subjects and TestSchedulers. My tests work if I use a trampoline scheduler but for some reason they fail if I use the TestScheduler. Also If I do not supply any subscribeOn or observeOn scheduling tests still pass.

Here's my sample test and relevant classes.

@RunWith(MockitoJUnitRunner::class)
class DemoViewModelTest  {


    //Error Mocks
    private val actionsStream: PublishSubject<DemoContract.ViewEvent> = PublishSubject.create()

    private lateinit var viewModel: DemoViewModel

    private val handler = mock(DemoContract.Handler::class.java)

    @Before
    fun setup() {
        viewModel = DemoViewModel(schedulersProvider, handler)
        viewModel.viewEventsStream = actionsStream
    }

    @Test
    fun testUpdateCounter() {
        actionsStream.onNext(DemoContract.ViewEvent.UpdateClick)
        testScheduler.triggerActions()
        verify(handler).onUpdate()

    }


    protected var testScheduler = TestScheduler()

    protected var schedulersProvider: SchedulersProvider = object : SchedulersProvider() {
        override fun mainThread(): Scheduler {
            return testScheduler
        }

        override fun io(): Scheduler {
            return testScheduler
        }

        override fun computation(): Scheduler {
            return testScheduler
        }

        override fun newThread(): Scheduler {
            return testScheduler
        }

        override fun trampoline(): Scheduler {
            return testScheduler
        }

        override fun single(): Scheduler {
            return testScheduler
        }
    }
}

And my ViewModel class

class DemoViewModel (val schedulersProvider: SchedulersProvider, val handler:DemoContract.Handler) : DemoContract.ViewModel() {

    var viewEventsStream: Observable<DemoContract.ViewEvent>? = null
        set(value) {
            field = value
            subscribeToViewEvents()
        }

    private fun subscribeToViewEvents() {
        viewEventsStream?.let {
            it.subscribeOn(schedulersProvider.io())
                .observeOn(schedulersProvider.mainThread())
                .subscribe(object:Observer<DemoContract.ViewEvent>{
                    override fun onComplete() {

                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: DemoContract.ViewEvent) {
                        onViewEvent(t)
                    }

                    override fun onError(e: Throwable) {
                    }

                })

        }
    }
     fun onViewEvent(event: DemoContract.ViewEvent) {
        when (event) {
            is DemoContract.ViewEvent.UpdateClick -> {
               handler.onUpdate()
            }
        }
    }

}

and My Contract class is

interface DemoContract {
        abstract class ViewModel

        sealed class ViewEvent {
            object UpdateClick : ViewEvent()
        }

        interface Handler{
            fun onUpdate()
        }
    }

A few things about this, If I replace

viewModel.viewEventsStream = actionsStream

with

viewModel.viewEventsStream = Observable.just(DemoContract.ViewEvent.Update)

this test passes.

Can someone throw some light on this, thanks in advance.

sbt test fails my spark testing suite while intellij test works

I am trying to test the behaviour of a class which eats and process DataFrames.

Following this previous questions: How to write unit tests in Spark 2.0+? I tried to use the loan pattern to run my tests in the following way: I have a SparkSession trait:

/**
  * This trait allows to use spark in Unit tests
  * https://stackoverflow.com/questions/43729262/how-to-write-unit-tests-in-spark-2-0
 */
trait SparkSetup {

  def withSparkSession(testMethod: SparkSession => Any) {
    val conf = new SparkConf()
      .setMaster("local")
      .setAppName("Spark test")
    val sparkSession = SparkSession
      .builder()
      .config(conf)
      .enableHiveSupport()
      .getOrCreate()
    try {
      testMethod(sparkSession)
    }
    // finally sparkSession.stop()
  }
}

Which I use in my test class:

class InnerNormalizationStrategySpec
  extends WordSpec
  with Matchers
  with BeforeAndAfterAll
  with SparkSetup {
 ...
 "A correct contact message" should {
    "be normalized without errors" in withSparkSession{ ss => {

      import ss.implicits._

      val df = ss.createDataFrame(
        ss.sparkContext.parallelize(Seq[Row](Row(validContact))),
        StructType(List(StructField("value", StringType, nullable = false))))

      val result = target.innerTransform(df)

      val collectedResult: Array[NormalizedContactHistoryMessage] = result
        .where(result.col("contact").isNotNull)
        .as[NormalizedContactHistoryMessage]
        .collect()

      collectedResult.isEmpty should be(false) // There should be something
      collectedResult.length should be(1) // There should be exactly 1 message...
      collectedResult.head.contact.isDefined should be(true) // ... of type contact.
    }}
  }
 ...
}

When attempting to run my tests using IntelliJ facility, all tests written in this manner works (running the Spec class at once), however, the sbt test command from terminal makes all the tests fail. I thought also it was because of parallelism, so i added concurrentRestrictions in Global += Tags.limit(Tags.Test, 1)

in my settings, but didn't work. Any help?

How to design a rest api using akka-http so that it is easy to test?

I have a simple REST-API. Each api sub-path has its own service implementation.

The questuion is: how to correctly test it?

Example:

class RestAPI(implicit dispatcher: ExecutionContext)  // some services need its own dispatcher
extends FirstService with SecondService with etc... { 
  val api: Route = pathPrefix("api") {
    get {
      firstService()
    } ~ post {
      secondService()
    } ~ ...
  }

  def start(implicit system: ActorSystem, materializer: ActorMaterializer): Unit = {
    Http().bindAndHandle(api, "host", 8080)
  }
}

object RestAPI {
  def apply(implicit dispatcher: ExecutionContext): RestAPI = new RestAPI
}

In this case i cannot test my endpoint because of dependency of execution context and service implementation which i should mock. I can create my own implementation of RestApi in test case, but i have to update it each time a change something inside real RestApi

I tried another way:

class RestAPI(implicit dispatcher: ExecutionContext)  { // some services need its own dispatcher
  this: FirstService with SecondService with etc... =>
  val api: Route = pathPrefix("api") {
    get {
      firstService()
    } ~ post {
      secondService()
    } ~ ...
  }

  def start(implicit system: ActorSystem, materializer: ActorMaterializer): Unit = {
    Http().bindAndHandle(api, "host", 8080)
  }
}

object RestAPI {
  def apply(implicit dispatcher: ExecutionContext): RestAPI = new RestAPI extends DefaultFirstService with DefaultSecondService with etc...
}


Test {
  val api = (new RestApi(dispatcher) extends StubOne with StubTwo with ...).api
}

In this case, at least, i can test all endpoints but i have to pass execution context and build RestApi object before i can get my routes. Also, this is not the best solution because of now i need to write this new RestApi(dispatcher) extends StubOne with StubTwo with ... and if there is 1 or 2 services - this is ok, but if there is more than 3, than it looks a bit awkward (in my opion).

Than i tried this approach:

class RestAPI(serviceOne: FirstService, serviceTwo: SecondService, ...)(implicit dispatcher: ExecutionContext)  { // some services need its own dispatcher
  val api: Route = pathPrefix("api") {
    get {
      serviceOne.firstService()
    } ~ post {
      serviceTwo.secondService()
    } ~ ...
  }

  def start(implicit system: ActorSystem, materializer: ActorMaterializer): Unit = {
    Http().bindAndHandle(api, "host", 8080)
  }
}

object RestAPI {
  def apply(serviceOne: FirstService, serviceTwo: SecondService, ...)(implicit dispatcher: ExecutionContext): RestAPI = new RestAPI(serviceOne, serviceTwo, ...)
}


Test {
  val api = (new RestApi(...)(dispatcher)).api
}

Probably, it is the most common approach, but i still have to pass execution context.

So, the main question is how to test my endpoints which depend on service implementation but without real implementation of those services? I suspect that there is a problem in implementation design but i can still change it. The question it: which approach i should to choose?

How to Undock Chrome Developer Tools using Selenium

Please any one Let me Know how to undock the chrome Developer Tools using Selenium .

I tried With pressing CLRT+SHIFT+D and CLRT+SHIFT+I, its not Working Just its dock-to-right and Bottom.

Thank you.

Test fails if an Exception is thrown in another part of the SUT

I have a system like this

class Sut
{
    IRepository _repo;

    public Sut(IRepository repo) { _repo = repo; }

    async Task Handle(Request request)
    {
         var entity  = new Entity(request.Id); //=> if Id is not ok the Entity throws Exception

         _repo.Save(entity);
    }
}

This is the test

        [Fact]
        public async Task Test_Save()
        {
            Mock<IRepository> repositoryMock = new Mock<IRepository>();

            repositoryMock
                .Setup(repo => repo.Save(It.IsAny<Entity>()))
                .Returns(Task.CompletedTask);

            var sut = new Sut(repositoryMock.Object);

            /// Act
            Action action = async () => await sut.Handle(new Request { Id = default(Guid)});

            /// Assert 
            Assert.Throws<Exception>(action);
            repositoryMock.Verify(repo => repo.Save(It.IsAny<Entity>(), Times.Never);
        }

So what it does is, the Entity has a check for default Guid being passed to it. If default value is passed it will throw an Exception.

The exception is thrown but the test fails with this message.

Message: Assert.Throws()

Failure Expected: typeof(System.Exception)

Actual: (No exception was thrown)

The test never calls

 repositoryMock.Verify(repo => repo.Save(It.IsAny<Entity>(), Times.Never);

it will break at this line

Why is that and how to solve this situation ?

Assert.Throws<Exception>(action);