samedi 30 juin 2018

How should I test a convenience method who's sole purpose is to call another method?

Disclaimer

This question is subjective. I know we're supposed avoid subjective questions on Stack, but it's something that a) I've been struggling with for a while and don't know where else to ask and b) I think would be considered a constructive subjective question and therefore permitted on Stack.


The Problem

I don't know how to go about testing a convenience method who's only purpose is to call another method on a different object.

As far as I can tell their are two ways to go about this, both with downsides:

  1. Retest all of the exact same logic for both the convenience method and the method it calls.

  2. Test that the convenience method calls and returns the original method with the expected arguments.

Option 1 makes less sense to me, in particular it doesn't make sense when the origin method (the one that the convenience method wraps) performs slightly complex logic and requires multiple unit tests. Why would I want the exact same logic tested in multiple places? What if that logic changes? Wouldn't it be better to just test that in one place rather than several?

I tend to lean towards option 2, but obviously the glaring red flag their is your testing implementation, not behavior. Which as I've heard time and time again (and tend to agree with for the most part,) you should not do.


An Example Of The Problem

Ok, now on to an example to help clarify what I'm talking about.

I'm currently working on an API of sorts that helps programmers interact with Alexa. The fundamental way to set responses to Alexa in my API is through a response object on an instance of a class called Alexa. For example, to set the output speech to 'hello world' you would use the following:

@alexa = Alexa.new
@alexa.response.set_speech("hello world")

In addition to this, I provide a convenience method on the Alexa class called #say that has the exact same result:

@alexa.say("hello world")

Here's what's going on behind the scenes:

# Alexa class
class Alexa
  attr_reader :response

  def initialize
    @response = Response.new
  end

  def say(speech)
    @response.set_speech(speech)
  end
end

# Response class
class Response
  attr_reader :response_hash

  def initialize
    @response_hash = {}
  end

  def set_speech(speech)
    @response_hash[:speech] = speech
  end
end

Notice how the Alexa#say method is a wrapper method who's only responsibility is to call response#set_output_speech with the passed in arguments.

Ok, now on to the tests.

For the set_speech method, the testing is easy:

RSpec.describe Response do
  describe '#set_speech' do
    it 'adds the passed in argument to the response hash under key :speech' do
      subject = Response.new
      subject.set_speech("hello world")
      expect(subject.response_hash[:speech]).to eq("hello world")
    end
  end
end

For the say method, I'm torn.

I could either retest the behavior of the method, which is not DRY and leads to unit tests that are dependent on other methods and objects:

RSpec.describe Alexa do
  describe '#say' do
    it 'adds the passed in argument to the response hash of @response under key :speech' do
      subject = Alexa.new
      subject.say("hello world")
      expect(subject.response.response_hash[:speech]).to eq("hello world")
    end
  end
end

Or I could test that say calls response#set_speech with the provided options, which as far as I can tell is testing implementation, and not behavior:

RSpec.describe Alexa do
  describe '#say' do
    it 'calls #set_speech on @response' do
      subject = Alexa.new
      expect(subject.response).to receive(:set_speech).with("hello world")
      subject.say("hello world")
    end
  end
end


My Question

TL;DR - How should I go about testing a convenience method whose sole purpose is to call a different method?

Is it better to retest the behavior and have repetitive and dependent unit tests, or to test that the convenience method calls the original method, and thus test implementation instead of behavior?

Or perhaps there is a third option I haven't come across yet?

Since this is a subjective question I would love more than just a 'use option 1' or 'use option 2' answer, try to explain why you think one technique is better than the other. Maybe even add in a story or two from your experience where you've seen the benefits of one approach over the other. Thanks!

Running selenium test with DrJava IDE

It is possible to run the selenium libraries on DrJava, if so how can I make the test case to run the respective libraries. I'm tying to run some test cases in Junit

Automated Test of Sorting by Column Feature

I am a new QA, and just started work last week. My senior left because of the working changes. Therefore, I have nobody to ask around me... and I took over his job. Hope you guys can help me here!

I am trying to write a automated test script to test the "sort by end date" feature. But sadly, I can not use selenium to test this feature from UI. Any thoughts of how to do this?

What I am thinking now, is that the sort on the front-end should be an "front-end" only feature? I do not know how to test it on back-end only. But my idea is that, I can call the API to create elements with different "end-date" then use LINQ to sort them. Then use the data from front-end and to make an assert statement to tell if the test is passed. But I am not sure how can I get the front-end data without testing from front-end....

If my description is confusing, please let me know. I will try to state it better.

Thanks!

Getting error : org.openqa.selenium.WebDriverException: unknown error: keys should be a string

I am getting the error to access the data from the properties file in my selenium UI : How can this be solved ?

org.openqa.selenium.WebDriverException: unknown error: keys should be a string.

I have the following framework. I made it for my self for ease, looks like complicating myself. If any good ideas to better it, please suggest. Appreciate all suggestions.

Framework contains the following : 1. config properties file 2. utilities class 3. Page elements definition class file 4. reusable functions class file 5. test classes

config.properties file has the following content :

url=http://some.com
username=someuser
password=somepassword

utilities class (BrowserCalls) the following code :

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class BrowserCalls {

    public WebDriver driver;
    public Properties configs = new Properties();
    public String pathToProperties = "path to config.properties file";

    public void invokeChromeBrowser() throws IOException {

        FileInputStream input = new FileInputStream(pathToProperties);
        pmsConfigs.load(input);
        System.setProperty("webdriver.chrome.driver", configs.getProperty("chromepath"));
        driver = new ChromeDriver();
        getAndMazimize();

    }

    private void getAndMazimize(){

        driver.get(configs.getProperty("url"));
        driver.manage().window().maximize();

    }


    public void closeChromeBrowser(){

        if(driver != null){

            driver.close();
        }

    }


}

Page elements definition class file has the following code :

import org.openqa.selenium.By;

public class LoginPageElements {


    //Login page elements
    public static By element1 = By.xpath("/html/head/link[1]");
    public static By username = By.xpath("//*[@id=\"login\"]/input/tr1/td1");
    public static By password = By.xpath("//*[@id=\"login\"]/input/tr2/td1");
    public static By submitButton = By.xpath("//*[@id=\"login\"]/input/tr3/td2/button");
    public static By title = By.xpath("/html/head/title");

}

Functionality definition classes to be called by test case classes :

import com.automation.PageElements.LoginPageElements;
import com.automation.ReusableFunctions.BrowserCalls;

public class LoginFeature extends BrowserCalls {

    public void userLogin(){

        driver.findElement(LoginPageElements.element1);
        driver.findElement(LoginPageElements.username).sendKeys(configs.getProperty(Email));
        driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty(Password));
        driver.findElement(LoginPageElements.submitButton).click();

    }

}

Test Case class is as below :

import com.automation.ReusableFunctions.BrowserCalls;
import com.automation.Components.LoginFeature;
import org.testng.annotations.Test;

import java.io.IOException;

public class LoginTestCase1 extends BrowserCalls {

    @Test (description = "Verify application login")
    public void LoginTest() throws IOException {

        LoginFeature login = new LoginFeature();
        login.invokeChromeBrowser();
        login.userLogin();
        login.closeChromeBrowser();

    }

}

How to tackle configuration file in Jenkins?

There are some configurations in my code (to connect DB). I wrote them in .env. Users need to create their own .env file to run the application. This is the copy code in Dockerfile: COPY .env server COPY .env test

When I use Jenkins to build a pipline, I have to commit this file, but I should not do that(aws information included there).

What is the best practice to save configuration file?

Thanks

Why isn't Xcode recording these user interface tests?

Xcode has the cool ability to live record UI tests, as demonstrated by this youTube video - the user clicks buttons on the simulartor and the code appears in test.

However, when I do the same action on this freshly pushed to github xcode project nothing code appears. What is my missing ingredient?

This is the screen I see. enter image description here

and this is a recording of what it looks like live. What am I missing?

Should I create an interface for every class to make my code testable (unit testing)

I'm trying to learn how to create valuable unit tests. In each tutorial I saw people create interfaces for every dependency to create a mock.

Is it mean that I should always create an interface for every class I have in my project? I don't know is it a good or a bad idea but every time I see a rule with "always" I get suspicious.

vendredi 29 juin 2018

Restito and RestAssured - compare REQUEST body to xml file

I have a file request.xml and an application that is sending request to another API. I would like to compare the XML that is generated to request.xml to make sure the request body is correct.

So far I have mocked API:

server = new StubServer(7071).run();
RestAssured.port = server.getPort();

whenHttp(server).match(post("/endpoint"), withPostBodyContaining("100"))
                .then(ok(), resourceContent("response.xml"), contentType("text/xml"));

This rule just sends a response depending on request body containing 100 but I would like to actually compare request body to request.xml file.

What is the best way to do this using RestAssured or not using RestAssured? Thank you.

Can't get Mjacksons Expect module to work in Codepen

I'm trying to follow along learning Redux, and Dan Abramov uses Michael Jacksons expect module, but I can't get it to work in Codepen. I'm under "Pen Settings" > "Javascript" > "Add External Scripts/Pens" and I tried https://npmcdn.com/expect/umd/expect.min.js, https://cdnjs.cloudflare.com/ajax/libs/expect/1.20.2/expect.js, https://unpkg.com/expect@%3C21/umd/expect.min.js and https://wzrd.in/standalone/expect@latest but no matter which I pick, I run the following code which I would expect to throw an exception, and nothing happens in the CodePen console.

function counter(state, action) {
  return state;
}

expect(
counter(0, { type: 'INCREMENT' })
  ).toEqual(1);

expect(
counter(1, { type: 'INCREMENT' })
  ).toEqual(2);

expect(
counter(2, { type: 'DECREMENT' })
  ).toEqual(1);

expect(
counter(1, { type: 'DECREMENT' })
  ).toEqual(0);

console.log('Tests Passed!');

If I use the cloudflare link, I get the following exception in the browser console, but it never loads into the CodePen console.

expect.js:2654 Uncaught Error: Expected 0 to equal 1
    at assert (VM287 expect.js:2654)
    at Expectation.toEqual (VM287 expect.js:172)
    at VM292 pen.js:5

Any idea which is the best to use and why the CodePen console isn't showing the exceptions?

Node Chai and Mocha tests end up red and dont show assertion errors

So I have been trying to mess around with mocha, chai and chai-http for integration testing and I have a very weird problem. Sometimes when I run my tests my assertion errors show up and sometimes they dont. They end up getting logged by my application though. When I run these tests in my terminal I get an output like this:

failure output image

As you can see, the failed test just shows up in red and the assertion error gets logged. This is the code (starting from first describe) of my test. I added the done callback to every "it" as described in the mocha documentation. Im running different setups before each test to set up proper conditions with before and each.

describe('Customer', () => {
before(async () => {
    testTokens = await testUtils.mockTestRequirements(testUserId, testPlatform);
});

after(async () => {
    await testUtils.removeTestRequirements(testUserId, testPlatform);
});

describe('GET /has-premium', () => {
    describe('No subscription case', () => {
        before(async () => {
            await testUtils.mockPaymentTestRequirements(testUserId);
        });

        after(async () => {
            await testUtils.removePaymentTestRequirements(testUserId);
        });

        it('should respond false if the customer does not have a subscription', (done) => {
            chai.request(app)
                .get('/customer/has-premium')
                .set('x-access-token', 'QueueFeed ' + testTokens.accessToken)
                .set('x-refresh-token', testTokens.refreshToken)
                .query({unique_id: testUserId})
                .end((err, res) => {
                    expect(res).to.be.json;
                    expect(res).to.have.status(200);
                    expect(res.body.success).to.equal(true);
                    expect(res.body.premium).t.equal(false);
                    done();
                })
        });
    });
});

I have no idea why this keeps failing and I tried debugging but I cant figure out the error.

Thanks in advance!

how to test a function which calls 2 other functions with jest and enzyme

I'm using react-dates component in my react project and 'onDatesChange' is a function which is dispatching actions to redux store two times, can someone help me in testing this function with jest and enzyme..

This is DateRangeComponent imported from react-dates.

<DateRangePicker
   startDate={this.props.filters.startDate}
   startDateId={this.state.startDateId}
   endDate={this.props.filters.endDate}
   endDateId={this.state.endDateId}
   onDatesChange={this.onDatesChange}
   focusedInput={this.state.calenderFocused}
   onFocusChange={this.onFocusChange}
   showClearDates={true}
   numberOfMonths={1}
   isOutsideRange={() => false}
/>

And this is my function which is dispatching two actions to the redux store.

onDatesChange = ({ startDate, endDate }) => {
  this.props.dispatch(setStartDate(startDate));
  this.props.dispatch(setEndDate(endDate));
};

How can I test this function in this form. I know, I can test it easily if I refactor it to mapDispatchToProps, which I don't wanna do. thanks

how to compare data from tableau to a big query table automatically?

Please help me in telling me a way to compare data which is being shown in the tableau with the value present in the table automatically? this needs to be automated with the python or any possible technique.

How to measure performance test on java method?

I have a method in java Public Object someMethod (String param) ( //some calculations Return Object )

I want to test the performance of this method ( how much time would it take to reach to db and return an object ) How can I do this? I don't have a main method because its a library. I use unit tests to check if it works. Help.

Testing High-Order component with enzyme and jasmine

I'm new to testing with Jasmine and Enzyme and I've been trying to test a HOC which is connected to redux. Take for instance the following HOC:

import React, { Component } from 'react';
import { connect } from 'react-redux';

const WithAreas = (WrappedComponent) => {
  class WithAreasComponent extends Component {
    constructor(props) {
      super(props);    
    }    

    shouldRenderWrappedComponent(userObj) {
      return !!userObj.areas;
    }

    render() {
      const { userObj } = this.props;

      return shouldRenderWrappedComponent(userObj)
        ? <WrappedComponent {...this.props} />
        : null;
    }
  }

  function mapStateToProps(state) {
    const { info } = state;
    const { userObj } = info.userObj;

    return { userObj };
  }

  return connect(mapStateToProps)(WithAreasComponent);
};

export default WithAreas;

Let's say I want to test this HOC in order to check if the wrapped component is being render according to the userObj. I thought about doing a mock component and pass it to the HOC, but this is not working.

Test.js File:

import React from 'react';
import { shallow } from 'enzyme';
import jasmineEnzyme from 'jasmine-enzyme';

import { WithAreas } from './';

class MockComponent extends React.Component {
  render() {
    return(
      <div> MOCK </div>
    );
  }
}

function setup(extraProps) {
  const props = {
   info: {
    userObj: {
     id: 'example1'
    }
   },
  };

  Object.assign(props, extraProps);

  const WithAreasInstance = WithAreas(MockComponent);
  const wrapper = shallow(<WithAreasInstance {...props} />);

  return {
    props,
    wrapper
  };
}

fdescribe('<WithAreas />', () => {
  beforeEach(() => {
    jasmineEnzyme();
  });
  it('should render the Mock Component', () => {
    const { wrapper } = setup();
    expect(wrapper.find(MockComponent).exists()).toBe(true);
  });
});

But it gives me this error:

TypeError: (0 , _.WithAreas) is not a function at setup (webpack:///src/user/containers/WithAreas/test.js:20:47 <- src/test_index.js:9:18060087) at UserContext.<anonymous> (webpack:///src/user/containers//WithAreas/test.js:34:24 <- src/test_index.js:9:18060822) What am I doing wrong? Or what approach might you recommend?

Thanks for any given help.

In app purchase live url show sandbox popup and allow subscription for sandbox user

I have added in-app purchase in my application it is working well in sandbox environment but when I change it's URL from sandbox to live and run the application it is behaving unexpectedly.

Here is my code:

Below are the method in which we are requesting to apple for getting in app purchase detail of user.

-(BOOL) getSubscriptionStatusFromAppleWithReceipt:(NSData *) receiptData

{

NSError *error;
NSMutableDictionary *requestContents = [NSMutableDictionary dictionaryWithObject:
                                        [receiptData base64EncodedStringWithOptions:0] forKey:@"receipt-data"];
NSString *sharedSecret = @“*********************”;
if (sharedSecret) requestContents[@"password"] = sharedSecret;
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];

NSString *strUrl = @"";


// Live server
strUrl = @"https://buy.itunes.apple.com/verifyReceipt";

// Devlopment server

// strUrl = @"https://sandbox.itunes.apple.com/verifyReceipt";

NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
[storeRequest setHTTPMethod:@"POST"];
[storeRequest setHTTPBody:requestData];

queue = [NSOperationQueue mainQueue];

//    NSError *error = nil; 
NSHTTPURLResponse *response = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:storeRequest returningResponse:&response error:&error];

if (!error)
{
    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    if ([jsonResponse[@"latest_receipt_info"] isKindOfClass:[NSArray class]])
    {
        NSArray *receiptInfo = (NSArray *) jsonResponse[@"latest_receipt_info"];
        return [self parseJsonFromAppleServer:receiptInfo];
    }
}
else
{        NSLog(@"%@", error.localizedDescription);
}

return false;   

}

And next method in this I m retrieving the last index of receipt array and try to get user's subscription details.

Should I upload it on test flight or any other way in it's differentiation from live to development? How to test it in live environment.

Thanks

Codeception as PHAR with monolog

I am using Codeception downloaded as PHAR and installed into /usr/local/bin. After a while I just tried to use the Logger extension but was unable to use it with the error being

[Codeception\Exception\ConfigurationException] Logger extension requires Monolog library to be installed

I tried installing Monolog via composer locally or globally and it does not seem that it would be available to be installed via PHAR.

After testing through all the available installation methods (hehe) it seems that it's possible to use the logger extension with codeception only if both are installed via composer locally.

Is there any way to use them as PHAR packages? I assume monolog needs to be packages into the codeception PHAR package to make this work somehow.

I would like to NOT put these libraries into the projects local composer packages - mainly to keep myself from remembering to use paths like vendor/codeception/bin/codecept run to run tests.

How to detect that I'm in test mode angularjs

I need to know when I run protractor, how can I do this? I need something like this:

if(mode==test) {
    do something
}

How can I have access to variable from protractor.conf.js in my angularjs application?

Eclipse Photon deos not resolve imports in test sources

I have moved to Eclipse Photon with an existing workspace. I have some Maven projects in this workspace. All projects did not have any errors in Eclipse Oxygen. After opening my workspace in Eclipse Photon all test-classes which import org.mockito.Mockito, org.springframework.mock and org.springframework.test have errors. These imports cannot be resolved though Eclipse is aware of them as I can jump into the classes.

Why can Eclipse Photon not resolve these imports? And how can I fix this?

spying on bunyan log - NodeJS

Is there any way in which I can spy on the bunyan log to ensure I print out what I expect?

MyFile.js

const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'FailureAuditService'});

class someClass {
   someFunct() {
     if(x) {
        log.warn('something happened');
     }
   }
}

Test

const service = require(../MyFile);

describe('test something', () => {
    it('Will test the bunyan log', res => {
       let consoleLog = sinon.spy(log, 'createLogger');
       let x = true;

       service.someClass(x).then(res => {
          let expected = 'something happened';
          consoleLog.should.equal(expected);
       });
    });
})

Is there a way to test the size (height and width) of the view using espresso for android Instrumentation test?

I want to check if the visibility and size of the adFrame changes after clicking the buttonShow

onView(withId(buttonShow)).perform(click());
onView(withId(adFrame)).check(matches(isDisplayed()));
onView(withId(adFrame)).check(?);

I am looking for a solution of this ?.

Do we have an assertion that can test the size of the adFrame using the espresso for this Android Instrumentation test?

How can I check mode test?

I must do something like this:

'If test run, hide something.'

So I need something like this:

if(mode=test) {
    do something
}

How can I find out when I'm in test mode and when I'm not?

How to handle the image captcha in selenium web driver-java

After check the robots checkbox, its display the various image selection as captcha.so how can we handle this in the automation script?

Testing dom in angular

I have this form in an tect.html file and I want to test if the button is disabled or not:

//an ID INPUT
 <label class="form-control-label" jhiTranslate="oncosupApp.protocolo.identificador" for="field_identificador">Identificador</label>
        <input type="text" class="form-control" name="identificador" id="field_identificador"
            [(ngModel)]="protocolo.identificador" required/>


//and the button
<button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">

I am using protractor, cucumber, and dom methods to test if this button is disabled when the form data are invalid, so I check its attribute disabled like this:

const { Given, When, Then } = require('cucumber');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const chai = require('chai');
const expect  = chai.expect;
const should = chai.should();
chai.use(require('chai-dom'));

Given('I go to the project', {timeout: 90 * 1000},function(callback) {
  browser.driver.manage().window().maximize();
        browser.get('http://localhost:8080/#/').then(callback);   

  });
  
   When('I put a blank id',{timeout: 90 * 1000},  function( callback) {
        
        element(by.css("*[id='field_identificador']")).click();
        element(by.css("*[id='field_identificador']")).sendKeys('4').then(callback);
       
    });
    
    
    Then('Disabled should be true',{timeout: 90 * 1000}, function() {
  JSDOM.fromFile("src/main/webapp/app/entities/protocolo/protocolo-dialog.component.html").then(dom => {
   dom.window.document.getElementById("ref_button").hasAttribute('disabled').should.be.true;
     
    });
  });
Now the test always fails, cause it doesnt find disabled. But when I use jasmine and protractor though, like below, it works perfectly, fails when it is enabled and passes when disabled.
//describe.....

it('When the id is blank form is invalid so disabled should be true', function () {
        
        element(by.css("*[id='field_identificador']")).click();
      element(by.css("*[id='field_identificador']")).sendKeys('');
        
        expect(button.getAttribute('disabled')).toEqual('true');

    });
What am I missing in the first cobination with cucmber? Maybe jsdom? Maybe teh callbacks? Maybe there is another way to test dom using cucmber and protrcator???

Thanks!

MethodNotAllowedHttpException when testing on Lumen 5.6

I am testing a Lumen 5.6 API .

Here is my route:

$router->delete('/tournaments/{slug}', 'TournamentController@destroy');

When consuming with Angular 6, I have no problem, route is working, but when I try to test with PHPUnit with:

$this->call('DELETE', '/tournaments/' . $tournament->slug);

I get a MethodNotAllowedHttpException

Why ?

Separate/pull capabilities from another JS file

Ok so I'm trying to put the capabilities declaration for my Appium tests into another file and just reference it but I'm having no luck so far with using classes, functions, arrays and even global variables. I have also tried pulling it from a csv file but since JS is asynchronous that didn't work either.

I am not very familiar with JS and honestly stumped so if anyone could point me in the right direction that would be greatly appeciated!

Here's the code that I'm trying to seperate/make a reference for:

const opts = {
  port: 4723,
  desiredCapabilities: {
    platformName: "Android",
    platformVersion: "8.1.0",
    deviceName: "Nexus 6P", 
    app: "C:/Users/reina.reinhart/KonyWorkspace/temp/dcpApp/build/luaandroid/dist/luavmandroid.apk",
    automationName: "UiAutomator2",
    noReset: true
  }
}

jeudi 28 juin 2018

Unable to assert css width to be 100%

I'm trying to assert the CSS width of an element in NightwatchJS to be 100%, but it fails saying that the width is 196px. I have tried using the following syntaxes for the same:

page.assert.cssProperty(`@button-element`, 'width', '100%');
page.expect.element(`@${element}`).to.have.css("width").which.equals("100%");

I don't want to use hard-coded values, as they can change depending on the container width. What is the right way to do it?

I am using Page Object Model here but can do without it.

Ruby on Rails - How can I run automated tests on a user-uploaded Ruby file?

I'm currently working on a Rails application (React frontend) that deals with students submitting zipped directories of Ruby projects. The files are stored through Paperclip and S3 on an Assessment model. Currently, in order to grade student submissions, I must download every student file and test with RSpec individually from the command line.

I've improved the workflow through writing a script (in Ruby) that will take a directory of Zips, grade them all at once, and store each individual RSpec output in a scores.txt file.

The goal is to allow students to upload their .zips through a portal, and have them be immediately and automatically tested with RSpec. Is there a way to do this?

I've done a lot of searching, and so far can only find advice on how to test live user input (similar to codecademy, or other sites with integrated IDEs).

Angular - set private Input() in test

Here is my component

class Component {
  @Input() private somePrivateInput: string;

}

Next, I want to test it. According to docs, I have:

 it('Should do something basing on input', (done: DoneFn) => {
    component.somePrivateInput ='something';

    fixture.detectChanges();

    expect(component.something()).toBeTruthy;
});

However I got ERROR in my-component(43,19): error TS2341: Property 'somePrivateInput' is private and only accessible within class 'SomeComponent'.

rails test output carry return do not work

I run rails test and the output is:

Started with run options --seed 41744

Run options: --seed 41744--=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=---=] 0% Time: 00:00:00, ETA: ??:??:??

Running:

. 831/2: [ ] 0% Time: 00:00:00, ETA: 00:04:2

. 831/3: [ ] 0% Time: 00:00:00, ETA: 00:02:5

. 831/4: [ ] 0% Time: 00:00:01, ETA: 00:03:3

. 831/5: [ ] 0% Time: 00:00:01, ETA: 00:03:0

. 831/6: [ ] 0% Time: 00:00:01, ETA: 00:02:3

. 831/7: [ ] 0% Time: 00:00:01, ETA: 00:02:2

. 831/8: [ ] 0% Time: 00:00:01, ETA: 00:02:2

. 831/9: [= ] 1% Time: 00:00:01, ETA: 00:02:1

. 831/10: [= ] 1% Time: 00:00:01, ETA: 00:02:0

...

...

Every test is a new line, but the correct behavor is same line always

Mocking the requests for testing in Scrapy Spider

My objective is to test the spider written using scrapy (Python). I tried using contracts but it is really limited in the sense that I can not test things like pagination or whether some attributes are extracted correctly or not.

def parse(self, response):
    """ This function parses a sample response. Some contracts are mingled
    with this docstring.

    @url http://someurl.com
    @returns items 1 16
    @returns requests 0 0
    @scrapes Title Author Year Price
    """

So the second idea is to mock all the requests that the spider makes in one run, and use that in the testing phase to check against expected results. However, I am unsure and how can I mock every request that is made via the spider. I looked into various libraries and one of them is betamax. However, it only supports http requests made by requests client of Python. (As mentioned here). There is another library vcrpy, but it also supports limited clients only.

Are you using Requests? If you’re not using Requests, Betamax is not for you. You should checkout VCRpy. Are you using Sessions or are you using the functional API (e.g., requests.get)?

Last option is to manually record all the requests and somehow store them, but that's not really feasible at the scale which the spider make requests.

Does scrapy.Requests use some underline python client which can be used to mock those requests? Or is there any other way I can mock all the http requests made by the spider in one run and use that for testing the spider for expected behavior?

Do I need a database cleaner in Python?

I come from a Rails background, and am new to Python. Unfortunately, my googling and searching SO has been unsuccessful.

We are building a Python app with no framework. We're using pytest for testing, and factory-boy for factories.

I'm wondering if we need a database cleaner for our app. I have found the pytest_sessionstart and pytest_sessionfinish hooks, which would seem like a good place to do the cleaning. But I can't figure out if we even need such a thing as a database cleaner like we use in Rails testing.

Any information or assistance is greatly appreciated! If I do need some sort of cleaner, explicit instructions or links to docs would be very useful.

Jmeter questions

Im jmeter noobie. I got my junior project, with my own library. Could anyone tell me, can I easily export all the jars (project, my library, and POMs stuff) too jmeter folder and it will work? I read somewhere that I need double constructors in my classes, one empty one with string parameter. In all the classes, or just test classes?

Please Reply ASAP

Write test cases and the complexity for each code. Given an array of integers, find the closest value to the given number. The array may contain duplicate values and negative numbers. (Example : Array : 2,5,8,8,9,6,7,3 Target number : 5 Output : 5)(Target number : 11 Output : 9)(Target Number : 4 Output : 5)

handle different responses using mocha in nodejs unit testing

my test is getting passed(200 status code), when i passing correct header information. but when i try with wrong info(400 status code), it can't able to handle that error,

this is my code,(here im passing wrong headers info, so response will be status 400 code)

const chai = require('chai');
const expect = require('chai').expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const main  = require('../server');
let token;
describe('GET USER', function()  {
  this.timeout(50000);
  it('Display info about user and returns a 200 response', (done) => {
    chai.request(main)
    .get('/users')
    .set("Authorization"," ")
    .then(function(response) {
      // Now let's check our response
      expect(response).to.have.status(200);
      done();
    })
    .catch((err)=>{
      expect(err.status).to.be.equal(400)
      done();
    })
  });
});

im getting error like this,

GET USER
(node:28390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected undefined to equal 400
    1) Display info about user and returns a 200 response

  1 failing

  1) GET USER
       Display info about user and returns a 200 response:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/test/users.test.js)

How do I always run a "clean up" command in bash propagating the previous error code?

I'm setting up tests for a Node.js project. The tests include interacting with static content (images) that is supposed to be served from a local http-server.

When the tests have completed - either successfully or failing - I want to end the server process and exit with a correct code. What I came up with in my npm scripts is the following:

"server": "http-server testdata -p 9876 -s",
"testcmd": "...",
"test": "npm run server & npm run testcmd && kill $(lsof -t -i:9876) || (kill $(lsof -t -i:9876) && exit 1)",

which "works", but has two problems:

  • it repeats code as I do not know how to run things in any case instead of defining || and && cases
  • any non-zero exit code of testcmd will always be transformed into an 1 exit code - ideally I would like to propagate the exact exit code

I tried reading up on this and found people talking about traps, but could not get it to work.

What would be a good way to simplify this control flow scenario?

Unable to login to a website using powershell

I am trying to login to a site using the below code,

$IE = New-Object -ComObject InternetExplorer.Application

$Url = "https://example.com"

$IE.Navigate($Url)

$IE.Visible = $true

 while ($IE.busy) {
 start-sleep -milliseconds 1000 
 } 



$elements = $IE.Document.getElementById("userID")

Foreach($element in $elements)
    {
        $element.value = "user"
    } 


$elements = $IE.Document.getElementById("pswd")

Foreach($element in $elements)
    {
        $element.value = "password"
    } 


$elements = $IE.Document.getElementByName("configCombo")

Foreach($element in $elements)
    {
        $element.value = "config"
    } 

But except navigating to the url, nothing else seems to happen.The values in the username,password and config fields are not being filled up by the code.Looked for such cases in stack overflow but couldn't find any. So posted this as a new question.

I have unchecked the the enable protected mode in IE.

Any ideas/solutions will be greatly appreciated.

Angular 2 Unit Testing Services with HTTP requests

I am new to testing services with Angular 2 and I am trying to test a service with Http basic requests (Get and GetBYId). - How works my service? : I have a getAllMyProducts method which consumes a REST Api exposed in a Spring boot Backend application .this web api query the products and return products for the current user.(The http request is sent with headers ). - What I want to do? : Now I have to test this GetAll method with Jasmine and I am not sure how to do that especially regarding the current user…

  1. My GetAllMethod in my Service:
getAll(): Observable<Product[]> {
    return this.baseapiService.getAll('/product/userProducts');
    }
  1. my baseapiService that attachs header to the request:
getAll(link){
    this.header = this.createHeader();
    return this.http.get(this.apiurl+link, this.header)
      .map(this.extractData);
  }

Any examlpes or suggestions would be great. Thanks in advance

Gradle refuse to start process command 'cmd'

I'm encountering issue with a custom gradle task. Seems like gradle refuse to start a command line process.

Here is the custom task:

task generateAllure(type: Exec) {
    workingDir "$projectDir/allure/bin"
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine 'cmd', '/c', 'allure.bat', 'generate', '-c', '../../integration/build/allure-results'
    } else {
        commandLine 'bash', '-c', 'allure', 'generate', '-c',"$projectDir/integration/build/allure-results"
    }
}

tasks.withType(Test)*.finalizedBy generateAllure

With the appropriate dependency:

compile group: 'ru.yandex.qatools.allure', name: 'allure-commandline', version: '1.4.18'

After using gradle clean test execution fails on:

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':generateAllure'.
> A problem occurred starting process 'command 'cmd''

Any thoughts about that? Thanks!

have.attr() in chai-dom not working properly

I have this button to test in a file test.html :

<button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">

I am using protractor, cucumber, and chai dom to test if this button is disabled when the form data are invalid, so I check its attribute disabled like this:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const chai = require('chai');
const expect = chai.expect;
const should = chai.should();
chai.use(require('chai-dom'));

//In given when then step definitions I run teh app, login, go to the form and fill the form with valid data
....
When('I put a valid name',{timeout: 90 * 1000}, function(callback) {

  element(by.css("*[id='field_nombre']")).click();
  element(by.css("*[id='field_nombre']")).sendKeys('').then(callback);    
});
Then('The button Save should be enabled', function() {
JSDOM.fromFile("test.html").then(dom => {
dom.window.document.getElementById("ref_button").should.not.have.attr("[disabled]");

});
Now the test fails because it always finds the attribute disabled, when the button is disabled or not, when the datas are valid or not.

Is this a chai-dom issue, or something I implement the wrong way and maybe it doesnt make take the form status valid or invalid?

Run tests with Maven on pre-compiled project

Using Maven, I want to run unit and integration tests on a pre-compiled/ pre-jar'ed multi-module project. I am finding this exceedingly difficult.

My business case is, I want to compile and jar up a multi-module Maven project in one place, and then have the unit test and integration tests run using different Java versions and on different operating systems, to check for compatibility. Let's just say {Java 8, Java 10} x {Ubuntu, Windows} to keep it simple.

The reason I want to compile and jar up in one pace is, I want to ensure that I run tests on the actual code getting shipped. If I re-compiled everywhere I fear I might introduce errors unwittingly.

One solution is to do mvn deploy -DaltDeploymentRepository=$mydir on Ubuntu to produce a compiled project tree and a directory full of jars; then zipping up the project tree and deploy directory and shipping them off to a Windows machine; and there running mvn surefire:test -Dmaven.repo.local=$mydir on the project tree.

That works but it is hella clumsy. Surefire seems to read the test classes in the project tree and use the classes in the same project + jar dependencies from the deployment repo to link against. A problem there is, with -Dmaven.repo.local Maven needs to download all 3rd party dependencies again because that repo only contains my project artifacts. So a solid solution, but not great.

Instead what I have been trying to do is, just use the compiled project tree:

  • If I just do mvn surefire:test I get problems resolving dependencies
  • I have tried mvn compile -Dmaven.main.skip surefire:test to fix dependency resolution, which seems to work - just not for test dependencies
  • I further tried mvn compile -Dmaven.main.skip test-compile -Dmaven.test.skip surefire:test, but for some reason that also does not work, the build again fails trying to resolve test dependencies.

Interestingly, it is not deterministic, the failures happen at different stages and sometimes not at all - I get the occasional green build!

And now I am at my wits' end: I keep thinking this should be simple, and that I can't possible be the first person struggling with this simple problem.

It is opaque to me what happens with the reactor, when and how it triggers. The dependency graph must have been well-formed, or it couldn't compile. So why can I not get Maven to reproduce the same dependency graph for running tests?

Regards,

Lasse

PS: This is related to what me esteemed colleague Ben has had problems with, too: How can I run integration tests after building all modules in a multi-module Maven project?

Develop a AI based testing tool

We are developing an AI based automation tool, which record and playback(Selenium or protractor) tool is suitable to customize and apply AI algorithms. If anyone has worked on such concept, please share your insight

Extract data from a URL to use in a selenium test

I am testing a football betting website currently. In this website there is a different game every day. So each game has a different id in the URL. An example of this would be https://web-game-stage.sportgames.com/games/5b310f8967ef5ad461d75aef/ so the 5b310f8967ef5ad461d75aef is the game id. How can i extract this code from the URL and basically just make it a string??

Generating unit php tests -> codecept.phar permission denied

I am trying to execute this command in console

test generate:test unit ClassName

Right after that, I get an error that says, " /Users/silversurfer/PhpstormProjects/Kalkulacka/codecept.phar generate:test unit Kalkulacka Cannot run program "/Users/silversurfer/PhpstormProjects/Kalkulacka/codecept.phar" (in directory "/Users/silversurfer/PhpstormProjects/Kalkulacka"): error=13, Permission denied"

ClassName is "Kalkulacka"

So I guess that the codecept.phat file does not have global permission. I could not find anything about it on the internet. Could you please help me with this problem ? Thanks. I am using PhpStorm and mac os X.

Need to run 50 selenium web drivers at the same time

I need to simulate a team of about 50 users for my tests. Ive been using selenium so far but find that once I'm firing out more than 4 web drivers my results become more and more unstable and the result vary alot. Is Selenium Grid the way to go or is there something else out there for what I need?

Using mock with koin in androidtest to capture lambda

I spent many time to find a smart way to mock Koin bean in android activity. Unfortunatly none was satisfying ... until the koin-1.0.0-alpha22 launches

Thanks @arnaudgiuliani.

A full sample can be found here AndroidTestKoin sample project

Hope this helps Patrice

mercredi 27 juin 2018

How test cases are run on Control Flow Graph?

can any anyone tell me how test cases are run on control flow graph. I m working on Regression test selection tool , where I want to run test cases on Control Flow Graph of program and note down the execution trace(i.e the nodes visited during walk through the Control Flow Graph using test data from corresponding test case).

Can I ignore 'Instrumentation run failed due to 'Process crashed.' - so Test Runner will continue

When I run my test (to launch a video stream, and then let it run for 10 seconds), everything works (the stream runs, and I can even confirm views exist, etc), but the "Test Runner" crashes when my @Test is finished (after everything else has completed).

I get an error:

Test running failed: Instrumentation run failed due to 'Process crashed.'

But at this point in my test, I don't actually care about this, and would like to just ignore this.

Is there a way to just ignore this exit crash?

In my current situation, the test runner will exit the process, and not repeat, or run any other tests.

This is my test class:

@RunWith(AndroidJUnit4.class)
public class PlayerActivityTest extends InstrumentationTestCase {

    private LiveTvApplication app = (LiveTvApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();

    @Rule
    public ActivityTestRule<PlayerActivity> mActivityTestRule =
            new ActivityTestRule<>(PlayerActivity.class, true, true);

    @Rule
    public DaggerMockRule<LiveTvApplicationComponent> tvRepositoryRule = new DaggerMockRule<>(LiveTvApplicationComponent.class, new LiveTvModule(app))
            .set(new DaggerMockRule.ComponentSetter<LiveTvApplicationComponent>() {
                @Override
                public void setComponent(LiveTvApplicationComponent component) {
                    LiveTvApplication app = (LiveTvApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
                    app.setComponent(component);
                }
            });

    @Mock
    TvStreamDataRepository tvStreamDataRepository;

    /**
     * Launch Live TV Stream
     */
    @Test
    public void launchTV() {
        Context targetContext = InstrumentationRegistry.getInstrumentation()
                .getTargetContext();

        String argsKey = "value123";
        when(tvStreamDataRepository.getStreamArgs(argsKey)).thenReturn(tvStreamArgs);


       Intent mpdIntent = new Intent(targetContext, PlayerActivity.class)
            .putExtra(BundleKeys.APP_CONFIG, Parcels.wrap(appConfig))
            .putExtra(BundleKeys.STREAM_ARGS_KEY, argsKey);

            mActivityTestRule.launchActivity(mpdIntent);

            try {
                Thread.sleep(WAIT_TIME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

// I CAN ALWAYS GET HERE - After this I don't care
// But the Test Runner will exit with the "Process Crashed" error
// and not run any other test

    }


}

Run database once per Spek suite

Some tests require running a database, for instance, using Test Containers Library. It obviously takes time to boot it up.

Is there a way to do this only once per entire Spek suite which spans across multiple files? The docs don't say anything about this.

Anyone knows why this has not been implemented?

Run iOS Apps on Windows Server

We are selling an iOS app on the app store which requires an extremly complicated server-side setup. The problem is that most of our customers have strict IT restrictions and they only allow us to connect to their servers via software (such as GoToAssist, LogMeIn, GoToMyPC, etc..).

The problem is that when support is configuring their server, they have absolutely no way to run the iOS app and test their configurations. We need a way to download the iOS app onto a simulator on their Windows server and run the simulator from their internal network so we can open the app and test.

Ideally this would be all done from their Windows server. However, if there is a way to do it from the Mac, that is acceptable too. However, we cannot use the iOS simulator that comes with XCode because that will require us to put our source-code on the customers Mac in order to run the app. We need a simulator that will download and run the app from the app-store.

Selenium Python find element by name doesn't work

I'm testing the web form with several fields using a PyCharm and Selenium web driver.

There are a two similar DIVs on the webpage for a phone and e-mail:

<div class="popup-subscribe-new__content">
                        <div class="field field_type_email js-field-custom-email js-field">
                            <input type="phone" name="phone" placeholder="Phone Number" autocomplete="off" required="required" class="field__input js-field-input js-inputmask-phone" pattern="^[0-9\+\-\( \)]+$" data-trim="true" pattern-flags="i">
                            <div class="field__error">Enter the phone number</div>
                        </div>
                    </div>

and

<div class="popup-subscribe-new__content">
                    <div class="field field_type_email js-field-custom-email js-field">
                        <input type="email" name="email" placeholder="E-mail" autocomplete="off" required="required" class="field__input js-field-input" pattern="^([A-Za-z0-9_\.\+\-])+@([A-Za-z0-9_\.\-])+\.([A-Za-z]{2,4})$" data-trim="true">
                        <div class="field__error">Enter the e-mail</div>
                    </div>
                </div>

in my test I using phone_field = driver.find_element_by_name('phone') for the phone search and phone_field = driver.find_element_by_name('email') for the e-mail search

As the result, the test successfully found the phone field but after trying to find the email field the PyCharp answered with ElementNotVisibleException: Message: element not visible

Where was I wrong? Thank you, Eugene

How application log lead to software quality assurance?

For me, there are multi log files obtained,How application log lead to software quality assurance?

How Can i Click on The Same Button For 99 Times or Till The Code Ends?

Need a Solution, Please Help.

Am Having Same Skip Button Type,name id Property For All Products. Only The Xpath Changes. Please Guide Me How Can i Shortly Click on 99 Same Skip Buttons and One Cancel Popup Button.

Here My Image For Skip Button

Skip Button Image

Here My Image, After Clicking on SKip, I Will Get a Pop Up Like This. I That I Need To Click on Cancel

Cancel Image

Down i Will Be Attaching The Code For SKIP and Cancel.

From The Html Code For Skip Button, I Took an Xpath its Working Only,

My Xpath is

//input[@id='CustomPaging_GridView_gv_edit1_0'])-Product1
 //input[@id='CustomPaging_GridView_gv_edit1_1'])-Product2
  //input[@id='CustomPaging_GridView_gv_edit1_2'])-Product3

Like this 99 Products I Have To Write Xpath. It's Going Too Lengthy

Html Code For Skip Button is

 <input type="submit" name="CustomPaging_GridView$ctl02$gv_edit1" value="SKIP" onclick="product_skip(37639 );" id="CustomPaging_GridView_gv_edit1_0" class="button2">

HTML Code For Cancel Button,

<div class="modal-footer">
                <span id="prcid" style="display:none;">processing...</span>
                <button type="button" id="skipok" onclick="skipoverall(this)" class="btn btn-primary" data-id="37639">Ok</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            </div>

PS: Each Time When i Click on The Skip button i Need To Click on The Cancel Button Simultaneously. Like That I Need To Click On Skip Button and Cancel Button For 99 Products

API testing with DTO message

Our system designed with DTO messages post the request using REST service as per below attachment.Soap UI or Postman supports XML/JSON input.Is any possible to test this system using API tools which currently in market? enter image description here

Thanks

Java Stomp WebSocket TimeoutException

I have issues with integration tests with WebSockets and SpringBoot. If I try to connect with StomJS from web page, client gets notification. But in integration test with Java client I get exception.What is a proper way to write these tests? My Config class look like:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends 
AbstractWebSocketMessageBrokerConfigurer  {
@Autowired
private ConnectionInterceptor connectionInterceptor;

@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
    registration.interceptors(connectionInterceptor);
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry
        .addEndpoint(ApiConstants.SOCKET_BASE_URL)
        .setAllowedOrigins("*")
        .withSockJS();

}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker( "/topic", "/queue" );
    registry.setApplicationDestinationPrefixes("/app");
    registry.setUserDestinationPrefix("/user");
}

}

My test is:

 @Test
 @WithMockUser(authorities = "ADMIN")
 public void ShouldLogoutGroupOfUsers() throws Exception {
    String url = "ws://127.0.0.1:" + port+ "/socket";
    StompSessionHandler sessionHandler = new MyStompSessionHandler();
    CompletableFuture<SocketMessage> completable = new 
    CompletableFuture<>();

    val stompHeaders = new StompHeaders();
    //add authorization headers
    stompHeaders.add(
            tokenHeaderKey,
    getUserHeaders().getValuesAsList(tokenHeaderKey).get(0)
    );

    val session = getStompClient().connect(
            url,
            new WebSocketHttpHeaders(),
            stompHeaders,
            new StompSessionHandlerAdapter() {
            }
    ).get(1, SECONDS);

    assertTrue(session.isConnected());
    stompHeaders.setDestination("/user/queue/action/logout");

    val subscription = session.subscribe(
            stompHeaders,
            new StompMessageHandler<>(completable, 
            SocketMessage.class)
    );

Now I call controller method that will call :

sender.convertAndSendToUser(registeredUser, DEVICE_LOGOUT_PATH,new 
SocketMessage("hello socket"));

And test fails on this line:

SocketMessage message = completable.get(30, SECONDS);

Add Multiple test agents into test controller in local machine visual studio 2017

I have installed 'Test agent configuration tool' and 'Test controller configuration tool' in my machine. I have successfully added an agent into my controller.

Now I want to add more test agents in the controller.

I am using visual studio 2017, and doing this testing into my local machine (not using more machines)

checking button disabled in chai

How can I test that a button is disabled after filling forms data?

 <button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">
              

I am using protractor an dcucmber and Chai to write the exectation. Ii fill teh data during atest and what I exepct is this:

dom.window.document.getElementById("ref_button").should.have.attr("[disabled]");
Now this always says that the attribute exists and does not change according to teh condition, id the data is valid the button should be enabled. Is there any other way I should do this?? Thannks!

Appium drop down select issue

I am unable to select drop down item in Appium using java test case. I am using eclipse ide to write test cases. I already used findElementBy id,class,name. All are not working.It is a hybrid application(js + Angular).Actual Image of code to select one of the language given in drop down

Testing code written in java to select drop down.

What assertive library to use for testing

I am using Cucumber, Protrator to test an angular app. Now since they do not have an assertion library I need to integrate one to write my expectations.

I read that Chai is the most common one, but in my case I need dom testing, so I tried chai-dom, but it has some issues.

What is another assertion library that can be used to test dom an dintegrate with protractor-cucumber?

C++ Sockets and stress testing

I've written a very simple socket server in C++ (MinGW) using these common functions like

socket( PF_INET, SOCK_STREAM, 0 )...
setsockopt( s, SOL_SOCKET, SO_REUSEADDR, &OptVal, sizeof( OptVal ) )...
bind( s, ( struct sockaddr * ) &ServerAddress, sizeof( ServerAddress ) )...
listen( s, 10 )...

The handling of multiple client connections is done by

select( s, &FileDescriptorClient, NULL, NULL, &tv )...
accept( Server->GetSocketHandle(), (struct sockaddr*) &ClientAddress, &Length )...

Everything looked very good and pretty,... until I decided to stress test my server.

My first test was a very simple client which did only one thing: connect and disconnect in an endless loop - as fast as possible. Although this test was extremly simple it failed immediately.

It wasn't a too big surprise to me that the server will choke on so many toggeling connections, so I added a Sleep(5) (milliseconds) in the client before each connect and disconnect and everything was OK. For the moment.

My questions are:

  • How do I handle these reconnects correct?
  • And what is the proper way to stress test a socket server application?

Right now the procedure is as follows:

  1. client: connects to server using connect(...)
  2. server: the new connection is recognized by select(...) and accept(...). Every new connection is stored to a std::vector.
  3. client: disconnects from server using closesocket(...) (MinGW...)
  4. server: recv(...) reads 0 bytes what means the client has disconnected from server
  5. server: performs a closesocket(...) and removes connection from std::vector
  6. goto 1

As already mentioned: this will only work when I throttle the client with sleeps. As soon as I reduce the sleeping times, the server starts skipping pt. 4 (disconnects) and stockpiles open connections down the line.

What is the point I am missing?

Error: expected [object HTMLButtonElement] to have an attribute

I have this testing file of an html button:

const { Given, When, Then } = require('cucumber');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const chai = require('chai');
const expect  = chai.expect;
chai.use(require('chai-dom'));

Given('I go to the project', {timeout: 90 * 1000},function(callback) {
  browser.driver.manage().window().maximize();
        browser.get('http://localhost:8080/#/').then(callback);   

  });
  
  //WHEN i FILL A FORM
   When('I put  a BLANK id',{timeout: 90 * 1000},  function( callback) {
        
        element(by.css("*[id='field_identificador']")).click();
        element(by.css("*[id='field_identificador']")).sendKeys('').then(callback);
       
    });
    
    Then(' button Save should be DISabled', function() {
    
     const dom = new JSDOM(` <button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary"> `);
     
     dom.window.document.getElementById("ref_button").should.have.attr('disabled');
     
     }
    

When I do the same thing with jasmine it works. But now I am using Chai to write the expectations. And it appears to not fing th disabled attribute. The error is this:** AssertionError: expected [object HTMLButtonElement] to have an attribute 'disabled'**

mardi 26 juin 2018

Chai POST request test does not send email

New to unit testing an API.

Using Chai, I am trying to test a POST request to an API. Basically, the POST request should add the details into the database and send a confirmation email to the entered email address.

My tests checks for the data been added to the database. But whenever the test is run, it does not sends the confirmation email from the POST request.

Mocking RestTemplate while Testing

I am using restTemplate within a @services in spring boot. That service is making a rest call to an external api's. But during testing can I mock a restTemplate so that instead of calling a external api's it will return a certain file from the resources directory.

This is so far I am using, but not working..

 byte[] responseBody = readAllBytes(get("src", "test", "resources", "templates", "content", "xxx.txt"));
        Mockito.doReturn(ResponseEntity.ok(new String(responseBody, StandardCharsets.UTF_8)))
                .when(restTemplate).exchange("https://xxxxxxx.xxxx",
                                            HttpMethod.GET,
                                            entity,
                                            String.class);

Thank you..

Swift - App crashes at name.first! on running test cases

I have written the following code to get the first character of a string.

name.first!

It works fine when build and ran. But, the app crashes at this line on running the test cases.

Is it because of different build environment? Is there any other way to get this done, without the app being crashed?

Writing a test for a conditional block in a reducer/action creator

Say I have a reducer or action creator that has some conditional logic in it and depending on the logic it will either call window.location.assign or dispatches an action. how can I mock out/change the const (which is local to the function) which causes it to either jump into the if or else block

literally googled so much for this and cannot find it anywhere. anyone got any ideas? even pointing me to docs

literally all I want to test is:

const url = getState().url
if(url){
  window.location... // one test for this
} else {
  dispatch({ type: MY_ACTION }) //a second test for this
}

why the heck is it so hard to find any docs or examples on this

Why CrossBrowser Automated Script Throws Error in Edge Browser?

Guys i Was Doing Cross Browser Automation in Chrome, FireFox and Edge . I Cant Able To Complete The Test Script in Edge Browser. I Was Getting an Error Message

"org.openqa.selenium.WebDriverException: Unknown error (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 42 milliseconds
    Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
    System info: host: 'rcktechiess-06', ip: '192.168.1.44', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
    Driver info: org.openqa.selenium.edge.EdgeDriver
    Capabilities [{applicationCacheEnabled=true, InPrivate=false, pageLoadStrategy=normal, platform=ANY, acceptSslCerts=true, browserVersion=42.17134.1.0, platformVersion=10, locationContextEnabled=true, webStorageEnabled=true, browserName=MicrosoftEdge, takesScreenshot=true, takesElementScreenshot=true, platformName=windows}]
    Session ID: B339099D-F7C6-41A7-A6E6-12D22C3D9937

I Have Attched Image For Exception. Please Check it

**Test 1 Code Using Testng**

package Crossbrowser;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class Test1 {

    WebDriver driver;

    @BeforeTest

    @Parameters("browser")

    public void setup(String browser) throws Exception
    {
        //Check if parameter passed from TestNG is 'firefox'

        if(browser.equalsIgnoreCase("firefox"))
        {
        //create firefox instance

            driver = new FirefoxDriver();
        }
        //Check if parameter passed as 'chrome'

        else if(browser.equalsIgnoreCase("chrome"))
        {
            //set path to chromedriver.exe

            System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");

            //create chrome instance

            driver = new ChromeDriver();
        }

        //Check if parameter passed as 'Edge'

                else if(browser.equalsIgnoreCase("Edge"))
                {
                    //set path to IE.exe

                    System.setProperty("webdriver.edge.driver","F:\\New folder (2)\\MicrosoftWebDriver (1).exe");
                    //create Edge instance

                    driver = new EdgeDriver();

                }
        else
        {
            //If no browser passed throw exception

            throw new Exception("Browser is not correct");
        }

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test

    public void testParameterWithXML() throws InterruptedException
    {

        driver.get("http://xxxxxxxxxx/");

        driver.manage().window().maximize();

        driver.findElement(By.xpath("/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/div[1]/span[1]/a[1]")).click();

        Thread.sleep(2000);
        //Find user name
        WebElement userName = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/ss-auth-form[1]/md-card[1]/ss-login-form[1]/div[1]/form[1]/input[1]"));
        //Fill user name
        userName.sendKeys("koushick@rcktechiees.com");
        //Find password
        WebElement password = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/ss-auth-form[1]/md-card[1]/ss-login-form[1]/div[1]/form[1]/input[2]"));
        //Fill password
        password.sendKeys("1234567890");

        Thread.sleep(2000);

        driver.findElement(By.xpath("//form[@name='myForm']//ss-submit-button[@label='Log In']//input[@class='submit']")).click();

        Thread.sleep(1000);

        Test2 obj = PageFactory.initElements(driver, Test2.class);

         Thread.sleep(2000);

         try
         {
             Actions a1 = new Actions(driver);
             a1.moveToElement(obj.getE1()).click(obj.getE2()).build().perform();
         }
         catch(Exception e)
         {
             System.out.println("Can't Click on The Elemnet");
         }

         Thread.sleep(2000);

         try
         {
         Actions a2 = new Actions(driver);
         a2.moveToElement(obj.getE3()).click(obj.getE3()).build().perform();
         }
         catch(Exception e)
         {
             System.out.println("Can't Click");
         }

         Thread.sleep(2000);

         try
         {
             Actions a3 = new Actions(driver);
             a3.moveToElement(obj.getE4()).click(obj.getE5()).build().perform();
         }
         catch(Exception e)
         {
             System.out.println("Can't Click on The Elemnet");
         }

         Thread.sleep(2000);

         obj.getE6().sendKeys("ss@gmail.com");

         Thread.sleep(2000);

         obj.getE7().click();

         Thread.sleep(2000);

         obj.getE8().click();

         Thread.sleep(2000);


       driver.navigate().to("http://XXXXXXXXXXXX/");

       Thread.sleep(2000);

       driver.findElement(By.xpath("//a[@classname='nav-link men']")).click();

       Thread.sleep(2000);

        }


    @AfterTest
    public void MatchitnowWithXML() throws InterruptedException
    {

        Test2 obj1 = PageFactory.initElements(driver, Test2.class);

         Actions a4 = new Actions(driver);
          a4.moveToElement(obj1.getE9()).click(obj1.getE9()).build().perform();

          Thread.sleep(2000);

          obj1.getE10().click();

          Thread.sleep(2000);

          obj1.getE11().click();

          Thread.sleep(2000);

          JavascriptExecutor js = (JavascriptExecutor) driver;
          js.executeScript("arguments[0].scrollTop = arguments[1];",driver.findElement(By.id("sylnk-it")), 500);

          Thread.sleep(2000);

          obj1.getE12().click();

          Thread.sleep(2000);

          Actions a5 = new Actions(driver);
          a5.moveToElement(obj1.getE13()).click(obj1.getE13()).build().perform();

          Thread.sleep(2000);

          try
          {
          driver.findElement(By.xpath("//button[@class='cal-sly']")).click();
          }
          catch (Exception e)
          {
              System.out.println("Not Visible To Click");
          }

          Thread.sleep(2000);

          driver.navigate().back();

          Thread.sleep(2000);

          driver.navigate().back();

          Thread.sleep(2000);

          try
          {
          Actions a6 = new Actions(driver);
          a6.moveToElement(obj1.getE14()).click(obj1.getE15()).build().perform();
          }
          catch(Exception e)
          {
              System.out.println("Can't Move To The Element and Click");
          }

        Thread.sleep(2000);

        try
        {
            Actions a7 = new Actions(driver);
            a7.moveToElement(obj1.getE16()).click(obj1.getE17()).build().perform();
        }
        catch(Exception e)
        {
            System.out.println("Can't Click on the Element !");
        }

        Thread.sleep(3000);

          JavascriptExecutor jse = (JavascriptExecutor) driver;
          jse.executeScript("window.scrollBy(0,250)"); 

          Thread.sleep(1000);

          try
          {
              Actions a8 = new Actions(driver);
              a8.moveToElement(obj1.getE18()).click(obj1.getE19()).build().perform();
          }
          catch(Exception e)
          {
              System.out.println("Can't Move To The Element and Click");
          }

          Thread.sleep(2000);



        try
        {

            Actions a9 = new Actions(driver);
            a9.moveToElement(obj1.getE20()).click().build().perform();
        }
        catch(Exception e)
        {
            System.out.println("Can't Click");
        }

        Thread.sleep(2000);

        try
        {
            driver.findElement(By.xpath("/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[2]/ss-search-filters[1]/ss-slide-filter[1]/ss-search-filter[1]/div[1]/div[2]/span[1]")).click();
        }
        catch(Exception e)
        {
            System.out.println("Can't Click");
        }




    }


    }

Down am Attaching Page ObjectModel Framework Code

**Test2 Code Using POM Framework Using GET Method**

    package Crossbrowser;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class Test2 {

    public WebElement getE1() {
        return e1;
    }

    public WebElement getE2() {
        return e2;
    }

    public WebElement getE3() {
        return e3;
    }

    public WebElement getE4() {
        return e4;
    }

    public WebElement getE5() {
        return e5;
    }


    public WebElement getE6() {
        return e6;
    }

    public WebElement getE7() {
        return e7;
    }


    public WebElement getE8() {
        return e8;
    }

     public WebElement getE9() {
        return e9;
    }

    public WebElement getE10() {
        return e10;
    }

    public WebElement getE11() {
        return e11;
    }

    public WebElement getE12() {
        return e12;
    }


    public WebElement getE13() {
        return e13;
    }

    public WebElement getE14() {
        return e14;
    }

    public WebElement getE15() {
        return e15;
    }

    public WebElement getE16() {
        return e16;
    } 

    public WebElement getE17() {
        return e17;
    }

    public WebElement getE18() {
        return e18;
    }

    public WebElement getE19() {
        return e19;
    }

    public WebElement getE20() {
        return e20;
    }



    @FindBy(xpath="/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/ss-user-dropdown[1]/div[1]/ss-svg-icon[1]/span[1]/i[1]")
    private WebElement e1;


    @FindBy(xpath="/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/ss-user-dropdown[1]/div[1]/div[1]/a[9]")
    private WebElement e2;


    @FindBy(xpath="//button[@id='ranomizeButton']")
    private WebElement e3;


    @FindBy(xpath="/html/body/div[2]/header/ss-header/div/div[2]/ss-user-dropdown/div")
    private WebElement e4;


    @FindBy(xpath="/html/body/div[2]/header/ss-header/div/div[2]/ss-user-dropdown/div/div/a[3]")
    private WebElement e5;


    @FindBy(xpath="/html[1]/body[1]/div[2]/div[4]/div[2]/div[1]/div[2]/div[2]/div[1]/div[1]/input[1]")
    private WebElement e6;


    @FindBy(xpath="/html[1]/body[1]/div[2]/div[4]/div[2]/div[1]/div[2]/div[2]/div[1]/button[1]")
    private WebElement e7;

    @FindBy(xpath="/html[1]/body[1]/div[2]/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/button[1]")
    private WebElement e8;


    @FindBy(xpath="/html/body/div[2]/ss-app/ss-search-page/div[4]/div[2]/ss-products-list/div[2]/span[3]/ss-product-cell/div/div[4]/span")
     private WebElement e9;


    @FindBy(xpath="/html/body/div[2]/ss-app/div[6]/div/ss-auth-form/md-card/div[1]/span[1]/div/div[2]/label/span")
    private WebElement e10;


    @FindBy(id="C5")
    private WebElement e11;


    @FindBy(id="slynk_save")
    private WebElement e12;


    @FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-header[1]/div[1]/div[1]/span[2]")
    private WebElement e13;


    @FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[4]/div[2]/ss-products-list[1]/div[2]/span[1]/ss-product-cell[1]/div[1]/div[5]")
    private WebElement e14;


    @FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[4]/div[2]/ss-products-list[1]/div[2]/span[1]/ss-product-cell[1]/div[1]/div[5]/a[2]/span[1]/i[1]")
    private WebElement e15;


    @FindBy(xpath="//ss-product-cell[@id='110743~Dresslily~womens-tops~womens-tops']//div[@class='product-cell-container extended-cell']//div[@class='bottom-icons']")
    private WebElement e16;


    @FindBy(xpath="//span[@id='~110743~Stylish Lace Embellished Short Sleeve Scoop Neck Womens TShirt~Dresslily~Dresslily~Dresslily~womens-tops~womens-tops~~undefined~$4.99~$9.67~~^^womens-tops^womens-clothes^women ']//i[@class='icon-12']")
    private WebElement e17;


    @FindBy(xpath="//ss-product-cell[@id='304028~GuessFactory~shorts~shorts']//div[@class='product-cell-container extended-cell']//div[@class='bottom-icons']")
    private WebElement e18;


    @FindBy(xpath="//span[@id='~304028~Shelby Denim Shorts~GuessFactory~Guess Factory~Guess Factory~shorts~shorts~~undefined~~$44.99~~^^shorts^womens-clothes^women ']//i[@class='icon-12']")
    private WebElement e19;


    @FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[2]/ss-search-filters[1]/ss-slide-filter[1]/ss-search-filter[1]/span[1]")
    private WebElement e20;

PS: While Executing The Test Script are Sucessfully Passing in Chrome and FireFox. But Failing in Edge Only at The Middle of Automation Some Kind of Stack Error. Down Am Also Attching The XML Please Give Me a Solution To Find a BetterWay.

  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" >

  <test name="FirefoxTest">
  <parameter name="browser" value="firefox">
    <classes>
      <class name="Crossbrowser.Test1"/>
    </classes>
     </parameter>
     </test> <!-- Test -->

     <test name="chromeTest">
  <parameter name="browser" value="chrome">
    <classes>
      <class name="Crossbrowser.Test1"/>
    </classes>
     </parameter>
     </test> <!-- Test -->

      <test name="EdgeTest">
  <parameter name="browser" value="Edge">
    <classes>
      <class name="Crossbrowser.Test1"/>
    </classes>
     </parameter>
     </test> <!-- Test -->



</suite> <!-- Suite -->

Testing API error with supertest and jest fails even though response is correct

I'm using jest 23.1.0 and supertest 3.1.0. I'm writing some tests for my backend and things have been going ok, however for a specific case of a specific route, the test is failing even though the response object seems to contain the right information. The test is to check if a parameter is valid JSON, and is as such:

describe('GET /graph', () => {
    it('invalid JSON', (done) => {
        request(app)
            .get('/graph')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(415)
            .then(done);
        });
});

In this case I'm not actually sending any parameter at all, but even if I do send some invalid JSON the issue is the same. Both cases trigger the same backend check anyway, which is:

module.exports = (req, res, next) => {

    let dataParameters;
    try {
        dataParameters = JSON.parse(req.query.dataParameters);
    }
    catch(error) {
        return(res.status(415).send({
            message: "Request parameters are not a valid JSON object",
            other: `${error.name} - ${error.message}`
        }));
    }
    ...

When I run jest, the test fails and the output to the console is this:

  GET /graph
    ✕ invalid JSON (6ms)

  ● GET /graph › invalid JSON

    Failed: Object {
      "header": Object {
        "connection": "close",
        "content-length": "125",
        "content-type": "application/json; charset=utf-8",
        "date": "Tue, 26 Jun 2018 13:58:48 GMT",
        "etag": "W/\"7d-GGhtZ8CfzWfmANZW28JTNC5bNjU\"",
        "x-powered-by": "Express",
      },
      "req": Object {
        "data": undefined,
        "headers": [Object],
        "method": "GET",
        "url": "http://127.0.0.1:35875/graph",
      },
      "status": 415,
      "text": "{\"message\":\"Request parameters are not a valid JSON object\",\"other\":\"SyntaxError - Unexpected token u in JSON at position 0\"}",
    }

      at Env.fail (node_modules/jest-jasmine2/build/jasmine/Env.js:537:34)

So looking at the object jest prints it seems the route is returning the right HTTP status and message, however instead of supertest handling that, the actual test itself is failing. I use the same response format and testing technique for testing other API errors and this doesn't happen. I've tried changing the request parameters, error codes and various other things but to no avail.

Jest Setup and CleanUp

Is it possible to do some tasks only once before all test suites and do the clean up once after all the test suites have completed?

The scenario is I want to create a user before any of the test suites are executed and once all the test suites complete executing then I want to clear all the trace of that user. How can I achieve that using jest and puppeteer?

I tried globalSetup globalTeardown and setupTestFrameworkScriptFile but they all run once before each test suites.

Disabled is not considered an HTML attribute

I have this button in html

<button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">
           

I am testing it like this using Chai:

 dom.window.document.getElementById("ref_button").should.have.attr('type');

And it works perfectly. But if I want to test the same way the disabled attribute the test doesn't work:

  dom.window.document.getElementById("ref_button").should.have.attr('disabled');

Maybe it is not an attribute??? How can I test it?

Errors I'm Having a Hard time Finding In This Code

so I have a final in 2 days, and I'm trying to understand a piece of code that is supposed to have a number of errors, and I'm not succeeding in finding any.. There is no solution with which I could analyze and fully understand and I feel that understanding this test fully will help me succeed in the final.

Any consideration would be appreciated, thank you.

The code:

#include <string.h>
#include <iostream>
using namespace std;

class Str
{
        char* word;
        int len;
public:
        Str(const char* w);
        Str(const Str& other);
        ~Str() {delete []word;}

        Str& operator=(const Str& other);
        char operator[](int i) const {return word[i];}
};

Str::Str(const char* w)
{
        len = strlen(w) + 1;
        word = new char[len];
        strcpy(word, w);
}

Str::Str(const Str& other)
{
        (*this) = other;
}

Str& Str::operator=(const Str& other)
{
        delete []word;
        len = other.len;
        word = new char[len];
        strcpy(word, other.word);
        return (*this);
}

int main()
{
        Str s1("hello");
        Str s2("hey");
        s2 = s1;
        s2 = "hi";
        Str s3(s1);
        s3[0] = 'H';

        return 0;
}

Running multi platform Kotlin test in IntelliJ produces No JDK specified error

I have several tests in common module for multi platform Kotlin project. When I execute those tests using gradle, e.g. ./gradlew :android:test, they all go through and the tests run.

I have now encountered a more complicated problem where I would like to debug an actual test in IntelliJ. Unfortunately, upon selecting the debug option in IntelliJ, I get an No JDK specified error.

No JDK specified

I am using the following dependencies for testing:

testImplementation "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlin_version"
testImplementation "org.jetbrains.kotlin:kotlin-test-common:$kotlin_version"

with $kotlin_version being 1.2.41.

The common module settings looks like this:

Common module settings

SDKs section also correctly recognises JDKs:

SDKs

I have tried changing the Module SDK from Kotlin SDK to java, however IntelliJ then wants me to require jUnit for test execution, which I would prefer not to, if possible.

Is there a way how to make the debugger run in IntelliJ for the Kotlin code?

spring boot test h2 data.sql wrong locale date format

I have a spring boot app with the file data.sql containing these DML commands:

insert into example (id, created) values (1, to_date('01-JAN-18', 'DD-MON-RR'));

insert into example (id, created) values (2, to_date('01-JAN-18', 'DD-MON-RR'));

Spring boot tests will fail after loading of spring context because of following error:

Function "TO_DATE": Invalid date format: " Tried to parse one of '[dÚc., juin, mai, fÚvr., mars, ao¹t, nov., janv., avr., juil., sept., oct.]' but failed

This problem was caused after I upgraded spring-boot but previously it worked correctly in version 2.0 ie. there in h2 was used default locale date as english (01-JAN-18), not germany.

Where can be the root problem?

Can't able to use Internet after installing OpenSTA

Installed a testing tool named OpenSTA on desktop, after exiting and uninstalling it. I was not able to use any of my browser for accessing Internet including IE.

Surfed lot about it, but couldn't come up with a solution. Even my administrator couldn't also able to fix it.

Gradle Wrapper 4.6 not recognising test filtering parameter

I'm having trouble filtering tests with gradle wrapper as the --tests parameter is not being recognized:

❯ ./gradlew test --continuous --tests "pt.joaomneto.titancompanion.adventure.twofm.TWOFMAdventureStateTest"                                                                                                                                                                                                              

Continuous build is an incubating feature.

> Configure project :
TitanCompanion: 'annotationProcessor' dependencies won't be recognized as kapt annotation processors. Please change the configuration name to 'kapt' for these artifacts: 'com.android.databinding:compiler:3.2.0-alpha10' and apply the kapt plugin: "apply plugin: 'kotlin-kapt'".


FAILURE: Build failed with an exception.

* What went wrong:
Problem configuring task :test from command line.
> Unknown command-line option '--tests'.

* Try:
Run gradlew help --task :test to get task usage details. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

As you can see, there is no such parameter in the help output.

❯ ./gradlew help --task :test                                                                                                                                                                                                                                                                                          

> Configure project :
TitanCompanion: 'annotationProcessor' dependencies won't be recognized as kapt annotation processors. Please change the configuration name to 'kapt' for these artifacts: 'com.android.databinding:compiler:3.2.0-alpha10' and apply the kapt plugin: "apply plugin: 'kotlin-kapt'".

> Task :help
Detailed task information for :test

Path
     :test

Type
     Task (org.gradle.api.Task)

Description
     Run unit tests for all variants.

Group
     verification

And I'm using gradle 4.6

❯ ./gradlew --version                                                                                                                                                                                                                                                                                                    

------------------------------------------------------------
Gradle 4.6
------------------------------------------------------------

Build time:   2018-02-28 13:36:36 UTC
Revision:     8fa6ce7945b640e6168488e4417f9bb96e4ab46c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_162 (Oracle Corporation 25.162-b12)
OS:           Mac OS X 10.13 x86_64

What am I doing wrong here? The documentation clearly states that I can use this parameter to filter testing: https://docs.gradle.org/4.6/userguide/java_plugin.html#test_filtering

Can you help me here?

How do i test android viewmodels with livedata

Help needed , First of all i've searched the net but haven't fallen on a post to address my needs

I have ViewModel class, I have Fragment that uses the ViewModel class via the ViewModelProvider, The ViewModel class has inputtext mutable livedata and list livedata

How to i use Mockito to test my UI using the viewmodel using the following example.

E.g A todo app example found here https://dukescript.com/best/practices/2015/02/16/tdd-with-dukescript.html

TodoListViewModel model = new TodoListViewModel();
assertEquals(model.getTodos().size(), 0);
model.setInputText("bu");
model.addTodo();
assertEquals(model.getTodos().size(), 0);
model.setInputText("buy milk");
model.addTodo();
assertEquals(model.getTodos().size(), 1);
assertEquals("", model.getInputText());

Error: document is not defined

I have this html button:

 <button id="ref_button" type="submit" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">
           

And I want to test if it is disabled in a special case using Chai. I do all the previous part, putting data in the from and now expect that this button to be disables like this:

  const chai = require('chai');
      const expect  = chai.expect;
     expect(document.getElementById('ref_button')).to.have.attr('disabled');

The erro that I get is docuemntis not defined. Is there something I do wrong? I am based here: enter link description here

lundi 25 juin 2018

NightwatchJS Unable to locate element using CSS Selector

I've currently got a section of a web site that looks like so:

<form id="product_form" method="POST" action="/cart/add" role="form">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <div>
        <img class="product-image" src="/static/images/products/4388801543.jpg" width="500px" alt="">
      </div>
    </div>
    <div class="col-md-3 product-variants other_options">
      <h1 itemprop="name" class="product-single__title h3 uppercase">Samburu Shorts - Mens</h1>
      <p class="product-single__price product-single__price-product-template">
        <span id="ProductPrice" itemprop="price" content="$55.95">$55.95</span>
      </p>
      <input type="radio" name="variant_id" class="hidden" id="14903870471" value="14903870471" onclick="enableSubmit()"><label for="14903870471" class="option text-center  selector size-value">29x11 Sand-Grey</label>
      <input type="radio" name="variant_id" class="hidden" id="16304664135" value="16304664135" onclick="enableSubmit()"><label for="16304664135" class="option text-center  selector size-value">29x11 Aubergine-Grey</label>
      <input type="radio" name="variant_id" class="hidden" id="16304665799" value="16304665799" onclick="enableSubmit()"><label for="16304665799" class="option text-center  selector size-value">34x7-5 Sand-Grey</label>
      <div class="product-add">
        <button id="add-to-cart" class="addItemToCart btn addToCart-btn product-form__cart-submit" disabled="" type="submit">Add to Cart</button>
      </div>
      <div class="social-sharing">
        <a target="_blank" href="#" class="btn clear btn--share share-facebook" title="Share on Facebook">
        <img src="//cdn.shopify.com/s/files/1/0281/7544/t/59/assets/img_share_fb.png?3517946130637841476">
        <span class="visually-hidden">Share on Facebook</span>
        </a>
        <a target="_blank" href="#" class="btn clear btn--share share-twitter" title="Tweet on Twitter">
        <img src="//cdn.shopify.com/s/files/1/0281/7544/t/59/assets/img_share_twitter.png?3517946130637841476">
        <span class="visually-hidden">Tweet on Twitter</span>
        </a>
        <a target="_blank" href="#" class="btn clear btn--share share-pinterest" title="Pin on Pinterest">
        <img src="//cdn.shopify.com/s/files/1/0281/7544/t/59/assets/img_share_pin.png?3517946130637841476">
        <span class="visually-hidden">Pin on Pinterest</span>
        </a>
      </div>
    </div>
  </div>
</form>

I'm scripting out a test through NightwatchJS where I am trying to select one of the radio buttons so I can automate a user experience. The code test block that I have written out is as follows:

'Check that widget loaded on new product page' : function(browser) {
   browser
      .waitForElementVisible('#monsoon-inline-reco-div-ul', longWait, () => {
      })
      .elements('css selector', '#monsoon-inline-reco-div-ul li', (results) => {
         browser.assert.equal(results.value.length, 4);
      })
      .click('#product_form > div > div:nth-child(2) > input[type=radio]')
      .pause(longWait)
      .end();
  }

The line in question is the click command. I keep getting errors about how the script cannot find the element given the css selector. I've tested this in the console in the browser itself using document.querySelector('#product_form > div > div:nth-child(2) > input[type=radio]').click() and the radio button is clicked. Could use some thoughts on something I might be doing wrong because I've been working this for a couple hours now and have tried a variety of different things.