dimanche 30 avril 2017

Is it possible to run XCTest tests in an iOS app?

We have a backend test suite written with XCTest. The suite runs great in Xcode, but for various reasons it would be nice for us if we could also run the suite in an iOS app. Is that possible? I don’t mind writing some glue code for it, but as it is I can’t even import the XCTest framework in a non-testing target:

SomeController.swift:2:8: Cannot load underlying module for 'XCTest'

Clicking button results in displaying Activity- Test fails

I'm new writting test code and I'm trying to create a test case that when i click a button verify is an Activity is displayed but it fails.

Here is my code:

@Test
public void mainActivityTest() {
    ViewInteraction floatingActionButton = onView(
            allOf(withId(R.id.fab), isDisplayed()));
    floatingActionButton.perform(click());

    intended(hasComponent(SecondActivity.class.getName()));
}

The Exception i'm getting is the follow:

java.lang.RuntimeException: Could not launch intent Intent { 
act=android.intent.action.MAIN flg=0x10000000 
cmp=com.google.developer.bugmaster/.MainActivity } within 45 seconds. 
Perhaps the main thread has not gone idle within a reasonable amount of  time? 
There could be an animation or something constantly repainting the screen. 
 Or the activity is doing network calls on creation? See the threaddump 
logs. For your reference the last time the event queue was idle before your 
activity launch request was 1493545934967 and now the last time the queue 
went idle was: 1493545937373. If these numbers are the same your activity 
might be hogging the event queue.atandroid.support.test.runner.MonitoringInstrumentation.startActivitySync(MonitoringInstrumentation.java:360)
at android.support.test.rule.ActivityTestRule.launchActivity(ActivityTestRule.java:

ArgumentError when trying to pass nested parameters in rspec

When I'm trying to execute the following line

post :create, user: Fabricate.attributes_for(:user)

I get this error message ArgumentError: unknown keyword: user.
Here's the code I was originally trying to run:

describe 'POST create' do context 'with valid input' do it 'creates the user' do post :create, user: Fabricate.attributes_for(:user) expect(User.count).to eq(1) end end end

Write modular UI Tests in XCode

I am pretty new to UI Testing on XCode. I found the record function pretty cool and it's working just fine but as long as you have decision points the code breaks the DRY principle. Therefore my idea is to write modular tests and invoke them depending of the user login status, role etc.

The problem is I don't find a way to tag my functions as not-tests (they are helpers invoked when appropriate from the main entry point). This is what I came up with

func testExample() {
   let exists = NSPredicate(format: "exists == true")

   let app = XCUIApplication()

   if(!app.staticTexts[""].exists){
       testLaunchScreen()
   }
   testAsRole1()

}

func testLaunchScreen(){
    let app = XCUIApplication()

    let scrollViewsQuery = app.scrollViews
    scrollViewsQuery.otherElements.containing(.image, identifier:"image0").element.swipeLeft()
    app.buttons["Continue"].tap()
    testFacebookLoginScreen()
}


func testFacebookLoginScreen() {
    let app = XCUIApplication()

    // set up an expectation predicate to test whether elements exist
    let exists = NSPredicate(format: "exists == true")
    // as soon as your sign in button shows up, press it
    let facebookSignInButton = app.buttons["Join with Facebook!"]
    expectation(for: exists, evaluatedWith: facebookSignInButton, handler: nil)
    facebookSignInButton.tap()


    self.waitForExpectations(timeout: 10, handler: nil)  
    if(app.staticTexts["Confirm"].exists){
        // create a reference to the button through the webView and press it
        let webView = app.descendants(matching: .webView)
        webView.buttons["OK"].tap()
    } else {
        let webViewsQuery = app.webViews
        webViewsQuery/*@START_MENU_TOKEN@*/.textFields["Email or Phone"]/*[[".otherElements[\"Welcome to Facebook\"]",".otherElements[\"main\"].textFields[\"Email or Phone\"]",".textFields[\"Email or Phone\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.typeText("user@tfbnw.net")
        webViewsQuery/*@START_MENU_TOKEN@*/.secureTextFields["Facebook Password"]/*[[".otherElements[\"Welcome to Facebook\"]",".otherElements[\"main\"].secureTextFields[\"Facebook Password\"]",".secureTextFields[\"Facebook Password\"]"],[[[-1,2],[-1,1],[-1,0,1]],[[-1,2],[-1,1]]],[0]]@END_MENU_TOKEN@*/.typeText("password")
        webViewsQuery.buttons["Login"].tap()   
    }
    // wait for your app to return and test for expected behavior here
    self.waitForExpectations(timeout: 10, handler: nil)  
}


func testAsRole1(){

  ///
}

The problem is that all the testXXX functions are run in order which is not what I want, I'd like to run just testExample. I have found some post regarding extensions but I don't think those would fit in my case

Many thanks

Modify shape of data returned by Angular 2 MockBackend

So I did some testing with Karma, and using MockBackend provided from '@angular/http/testing'
The shape of data returned by MockBackend is like this :

{ data: [Object1, Object2, Object3] }

however, in my real backend (Spring), I'm not adding 'data' property, so the shape of data to be like this :

[Object1, Object2, Object3]

The error will be like this :

Error: Expected Object({ data: [ Object({ cityId: 1, city: 'Lorem' }), Object({ cityId: 2, city: 'Ipsum' }), Object({ cityId: 3, city: 'Dolor' }), Object({ cityId: 4, city: 'SitAmet' }) ] }) to equal [ Object({ cityId: 1, city: 'Lorem' }), Object({ cityId: 2, city: 'Ipsum' }), Object({ cityId: 3, city: 'Dolor' }), Object({ cityId: 4, city: 'SitAmet' }) ].

How do I modify returned data from MockBackend so that it doesn't automatically add 'data' property? Or I have to switch to other mock tool?

Here is my service :

getAllCities(): Promise<City[]> {
    return this.http.get(this.getCityURL + `/fetch`).toPromise()
        .then(response =>  {
        console.log('data', response.json());
        return response.json() as City[];
     }).catch(this.handleError);
}

Here is test unit :

import { TestBed, inject } from '@angular/core/testing';
import { BaseRequestOptions, Http, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { Observable } from 'rxjs';

import { CityService } from './city.service';
import { City } from './city';

let mockBackend: MockBackend;
let cityService: CityService;

let MockCity: City = <City>{cityId: 1, city: 'Lorem'};
let MockCity2: City = <City>{cityId: 2, city: 'Ipsum'};
let MockCity3: City = <City>{cityId: 3, city: 'Dolor'};
let MockCity4: City = <City>{cityId: 4, city: 'SitAmet'};

let MockCitiesArray: Array<City> = [ MockCity, MockCity2, MockCity3, MockCity4 ];

let setup = (httpMock) => {
  TestBed.configureTestingModule({
    providers: [
      CityService,
      MockBackend,
      BaseRequestOptions,
      {
        provide: Http,
        useFactory: (backend: MockBackend, options: BaseRequestOptions) => new httpMock(backend, options),
        deps: [ MockBackend, BaseRequestOptions ]
      }
    ]
  });
  inject([ MockBackend, Http ],
    (mb: MockBackend, http: Http) => {
      mockBackend = mb;
      cityService = new CityService(http);
    })();
};


describe('CityService', () => {

  it('should return the cities array from the promise when getAllCities succeeds', (done) => {
    setup(MockSuccessGetHeroesHttp);
    spyOn(cityService, 'handleError');

    cityService.getAllCities().then((heroes) => {
      expect(cityService.handleError).not.toHaveBeenCalled();
      expect(heroes).toEqual(MockCitiesArray);
      done();
    });
  });

});

class MockFailedGetHeroesHttp extends Http {
  constructor(backend, options) {
    super(backend, options);
  }

  get() {
    return Observable.throw('error');
  }
}

class MockSuccessGetHeroesHttp extends Http {
  constructor(backend, options) {
    super(backend, options);
  }

  get() {
    return Observable.from([ new Response(new ResponseOptions({body: {data: MockCitiesArray}})) ]);
  }
}

How to get values from ng-repeat in protractor?

<div ng-repeat="obj in list">
</div>

This obj is having 6 properties like name, country, state, city, street, and contact. I have written following code for this but it is giving me undefined as the value if i try to fetch the stored value in obj.

var elm = element.all(by.repeater('obj in list'));

elm.then(function(obj){
    console.log("Number of Rows : "+ rows.length);
    for(var i=0; i< rows.length; i++){
         console.log("App name : " + rows[i].name);
    }
});

This is printing "App name : undefined" only.

samedi 29 avril 2017

Ecto.Association.NotLoaded error on update action test in Phoenix 1.3.0-rc1

I'm running the automatically generated tests for an update action on a model (or whatever they're called now?) in Phoenix 1.3.0-rc1 and getting ** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Association.NotLoaded<association :associated_models is not loaded> on the line with the put function call. Adding preloading to the fixture function like this...

def fixture(:model) do
  with {:ok, model} <- MyContext.create_model(@create_attrs),
  {:ok, preloaded_model} <- Repo.preload(model, : associated_models),
  do: preloaded_model
end

...does not change the error at all.

Test looks like this:

 test "updates chosen model and renders model when data is valid", %{conn: conn} do
    %Model{id: id} = model = fixture(:model)
    conn = put conn, model_path(conn, :update, model), model: @update_attrs
    assert %{"id" => ^id} = json_response(conn, 200)["data"]

    conn = get conn, model_path(conn, :show, id)
    assert json_response(conn, 200)["data"] == %{
      "id" => id,
      "name" => "some updated name"}
  end

I'm somewhat new to both Phoenix and Elixir.

How to convert line with UNIQUE INDEX key words from mySql to H2

CREATE TABLE IF NOT EXISTS Account (
  `userId` INT NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(45) NOT NULL,
  `last_name` VARCHAR(45) NOT NULL,
  `email` VARCHAR(45) NULL,
  `ICQ` INT NULL,
  `home_address` VARCHAR(45) NULL,
  `work_address` VARCHAR(45) NULL,
  `skype` VARCHAR(45) NULL,
  `additional_info` VARCHAR(450) NULL,
  PRIMARY KEY (`userId`))
 UNIQUE INDEX `userID_UNIQUE` (`userId` ASC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Account';

how to convert this line: UNIQUE INDEXuserID_UNIQUE(userIdASC) from mySQL syntax to H2 syntax ?

Why use Selenium instead just injected JS in a page?

I am looking for any explanation why Selenium became such popular tool for integration testing within browser when there is easier way to inject JS code (load it) and run tests without webdriver's overhead (which is, for IE especially, enormous). To be honest I see one advantage - it is not JS, and X developers can write testing code in X.

jest + enzyme, using mount(), document.getElementById() returns null on component which appear after _method call

I faced a problem with my jest+enzyme mount() testing. I am testing a function, which switches displaying components.

Switch between components: when state.infoDisplayContent = 'mission' a missionControl component is mounted, when state.infoDisplayContent = 'profile' - other component steps in:

_modifyAgentStatus () {
    const { currentAgentProfile, agentsDatabase } = this.state;
    const agentToMod = currentAgentProfile;

    if (agentToMod.status === 'Free') {
        this.setState({
            infoDisplayContent: 'mission'
        });
        agentToMod.status = 'Waiting';
    } else if (agentToMod.status === 'Waiting') {
        const locationSelect = document.getElementById('missionLocationSelect');

        agentToMod.location = locationSelect[locationSelect.selectedIndex].innerText;
        agentToMod.status = 'On Mission';
        this.setState({
            infoDisplayContent: 'profile'
        });
    }
}

When I trigger this function everything looks Ok, this test runs well and test successfully pass with required component:

import React from 'react';
import { mount } from 'enzyme';
import App from '../containers/App';

const result = mount(
    <App />
)

test('change mission controls', () => {
    expect(result.state().currentAgentProfile.status).toBe('Free');
    result.find('#statusController').simulate('click');
    expect(result.find('#missionControls')).toHaveLength(1);
    expect(result.find('#missionLocationSelect')).toHaveLength(1);
    expect(result.state().currentAgentProfile.status).toBe('Waiting');
});

But when I simulate onClick two times: 

test('change mission controls', () => {
    expect(result.state().currentAgentProfile.status).toBe('Free');
    result.find('#statusController').simulate('click');
    expect(result.find('#missionControls')).toHaveLength(1);
    expect(result.find('#missionLocationSelect')).toHaveLength(1);
    expect(result.state().currentAgentProfile.status).toBe('Waiting');
    result.find('#statusController').simulate('click');
    expect(result.state().currentAgentProfile.status).toBe('On Mission');
});

I get this assert:

    TypeError: Cannot read property 'selectedIndex' of null

  at App._modifyAgentStatus (development/containers/App/index.js:251:68)
  at Object.invokeGuardedCallback [as invokeGuardedCallbackWithCatch] (node_modules/react-dom/lib/ReactErrorUtils.js:26:5)
  at executeDispatch (node_modules/react-dom/lib/EventPluginUtils.js:83:21)
  at Object.executeDispatchesInOrder (node_modules/react-dom/lib/EventPluginUtils.js:108:5)
  at executeDispatchesAndRelease (node_modules/react-dom/lib/EventPluginHub.js:43:22)
  at executeDispatchesAndReleaseSimulated (node_modules/react-dom/lib/EventPluginHub.js:51:10)
  at forEachAccumulated (node_modules/react-dom/lib/forEachAccumulated.js:26:8)
  at Object.processEventQueue (node_modules/react-dom/lib/EventPluginHub.js:255:7)
  at node_modules/react-dom/lib/ReactTestUtils.js:350:22
  at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-dom/lib/Transaction.js:140:20)
  at Object.batchedUpdates (node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js:62:26)
  at Object.batchedUpdates (node_modules/react-dom/lib/ReactUpdates.js:97:27)
  at node_modules/react-dom/lib/ReactTestUtils.js:348:18
  at ReactWrapper.<anonymous> (node_modules/enzyme/build/ReactWrapper.js:776:11)
  at ReactWrapper.single (node_modules/enzyme/build/ReactWrapper.js:1421:25)
  at ReactWrapper.simulate (node_modules/enzyme/build/ReactWrapper.js:769:14)
  at Object.<anonymous> (development/tests/AgentProfile.test.js:26:38)
  at process._tickCallback (internal/process/next_tick.js:109:7)

It is obvious that:

document.getElementById('missionLocationSelect');

return null, but I can not get why. Element passes tests, as I mention.

expect(result.find('#missionLocationSelect')).toHaveLength(1);

But it could not be captured with document.getElementById().

Please, help me to fix this problem and run tests.

RxJava2: TestSubscriber.AssertNoErrors always pass

I am testing some features of Rxjava2(2.0.7) and have some troubles in unit test

here is my code

    RxJavaPlugins.setErrorHandler(null);
    Observable<String> o = Observable.create((ObservableOnSubscribe<String>) e -> {
        String s = System.currentTimeMillis() + "";
        System.out.println("runing observable@" + s);
        throw new RuntimeException();
    }).delay(1, TimeUnit.SECONDS);

    o
            .doOnNext(x -> {
                System.out.println(x);
                throw new RuntimeException();
            })
            .doOnError(e->e.printStackTrace())
            .test()
            .assertNoErrors()
            .awaitCount(1)
            .awaitDone(5, TimeUnit.SECONDS);

The problem is this test always passed, but I can still find exception printed in log

What am I doing wrong?

Automation Testing related query

Facing the below issue in Eclipse. Attached the logs. please help with your suggestions 1493505852004 geckodriver INFO Listening on 127.0.0.1:32725 1493505852739 mozprofile::profile INFO Using profile path C:\Users\arora\AppData\Local\Temp\rust_mozprofile.ameyOkKY6RPS 1493505852744 geckodriver::marionette INFO Starting browser C:\Program Files (x86)\Mozilla Firefox\firefox.exe with args [] 1493505852744 geckodriver::marionette INFO Connecting to Marionette on localhost:53292 IPDL protocol error: Handler returned error code!

!!! [Parent][DispatchAsyncMessage] Error: PLayerTransaction::Msg_ReleaseLayer Processing error: message was deserialized, but the handler returned false (indicating failure)

IPDL protocol error: Handler returned error code!

!!! [Parent][DispatchAsyncMessage] Error: PLayerTransaction::Msg_ReleaseLayer Processing error: message was deserialized, but the handler returned false (indicating failure)

[GPU 6784] WARNING: pipe error: 109: file c:/builds/moz2_slave/m-rel-w32-00000000000000000000/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 346 1493505857734 Marionette INFO Listening on port 53292 Apr 29, 2017 3:44:18 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: W3C Exception in thread "main" org.openqa.selenium.InvalidArgumentException: Expected [object Undefined] undefined to be a string Build info: version: '3.3.1', revision: '5234b32', time: '2017-03-10 09:04:52 -0800' System info: host: 'SAGAR', ip: '192.168.1.3', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_91' Driver info: org.openqa.selenium.firefox.FirefoxDriver Capabilities [{moz:profile=C:\Users\arora\AppData\Local\Temp\rust_mozprofile.ameyOkKY6RPS, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, platform=ANY, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=false, browserVersion=53.0, platformVersion=6.3, moz:processID=6264, browserName=firefox, platformName=windows_nt}] Session ID: f85ef783-51ac-4d6b-a228-6835999ae465 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:133) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:99) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:43) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:604) at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274) at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:98) at Gmail.main(Gmail.java:25)

how to test javascript in node repl (no browser)

I have file mycode.js and mycode.test.js. I want to test it in Node console (repl) - (no browser), in karma style - mycode.test.js looks as below:

var expect = require('expect');
var mycode = require("./mycode");

describe("mycode", () => {
    it("should properly run tests", () => {
        expect(1).toBe(1);
    });
});

what is the simplest possible setup to achieve this?

Rails Integration Testing: Is Capybara necessary for interacting with Javascript?

I'm new to testing in Rails and I'm trying to get into integration testing. I'm working with a Rails 4.2 project. I've written some simple tests in the default Minitest framework and I've quickly got to the point where I need to interact with the html by clicking a button and verifying that a modal appears.

From the research that I've done, it doesn't seem to be possible to to do anything like this with the syntax and driver that comes with Minitest. In order to do this I need to use Caypbara or something equivalent.

Firstly - Is that really the case? is there really no way to test Javascript with the default setup in Rails?

Assuming that is the case, I've pulled in Capybara to my project to utilize it's DSL and drivers for testing Javascript, but in doing so, it has rendered my initial tests useless. They no longer work as the Capybara DSL overwrites the assert_select method, forcing me to use Capybara syntax for writing tests - not something that I'm against, I'm just figuring this out.

So it seems like that if I ever want to test Javascript, then I need to use Capybara? and if I pull in Capybara then all my tests need to use Capybara snytax? If this is true, then it seems like I should just use Capybara from the get-go on all projects.

vendredi 28 avril 2017

Android testing tool that generates reports of tests

For testing in android, I've tried espresso & robotium recorder. I've also tried integrating spoon & emma, but no success.They work pretty well as far as automation testing is concerned. However, I'm interested to get reports of tests performed like, test cases passed, number of issues, latency, memory and network related numbers. Can you guys suggest some of the tools? Any help is most appreciated.

It would be good even if some of the above results aren't displayed..

I want sample test case & test data to test iso 20022 xml messge. can someone provide information regarding this?

I want sample test case & test data to test ISO 20022 XML message. can someone provide information regarding this ?

Excel's random number generator not random at all?

I'm triying to test wheter Excel's random generator is really random, that's why I'm using Wald's test

By so doing this I have obtained a p-value of 0 thus I have not to accept null hypotesis i.e the sample is not random.

My question is:

1) Am I making some mistake either coding or interpreting?

Code:

'By Julio Jesús Luna moreno
'jlqmoreno@gmail.com
Option Base 1
Sub WALDTEST()
 Dim x, r(), i, n, mu, sigma, plus(), minus(), k, h, f, mediana As Variant
  Dim w As Double
  n = 1000: k = 0: h = 0
  Set f = Application.WorksheetFunction
  ReDim r(n)
  For i = 1 To n
  Randomize
   x = Rnd()
    r(i) = IIf(x >= 0.5, 1, 0)
     If r(i) = 1 Then
      h = h + 1
      ReDim Preserve plus(h)
       plus(h) = r(i)
        Else
         k = k + 1
         ReDim Preserve minus(k)
          minus(k) = r(i)
           End If
     Debug.Print r(i)
 Next i
  Debug.Print f.Count(plus)
  Debug.Print f.Count(minus)

  mu = ((2 * f.Count(plus) + f.Count(minus)) / n) + 1
  sigma = (mu - 1) * (mu - 2) / (n + 1)
   w = f.Norm_Dist(n, mu, sigma, False)
    Debug.Print w
End Sub

Thanks in advance!

Timing issue with ActionCable, Capybara Webkit, and Capybara Session#window

I have a Rails 5 app that uses ActionCable to register 'guest' appearances. When you visit the site, you're prompted for your name. Once entered, your appearance is broadcast to all subscribers. When you exit your window, or 'disappear', you are shown to have left. It works great; the problem I have is testing disappearances - it passes only about half the time.

Here's the relevant test:

RSpec.feature "Appearances", type: :feature, js: true do
  let(:picard) { 'Picard' }
  let(:riker) { 'Riker' }

scenario "A guest disappears" do
  create_guest picard
  new_window = within_new_incognito_window do
    visit '/'
    expect(page).to have_content picard
    create_guest riker
  end  
  new_window.close
  expect(page).to_not have_content riker
end

And the helpers:

module GuestHelpers
  def within_new_incognito_window
    new_window = open_new_window
    within_window new_window do
      Capybara.current_session.driver.clear_cookies
      yield
    end
    new_window
  end

  def create_guest(name)
    within('#new_guest') do
      fill_in('guest[name]', with: name)
    end
    click_on("Go")
    expect(page).to have_content name
  end
end

I've tried setting the default_max_wait_time to 100, I've tried inserting sleep(10) around closing the window, and I've tried ditching the helpers and just doing it procedurally. I think it's a timing issue around closing the window - am I missing something obvious?

UFT giving error while using descriptive programming

My script is working normally but when i am using function & descriptive programming its giving me result failed without any proper result. Attaching error screenshot.Attaching error screenshot

Script

systemutil.Run "http://ift.tt/2qgimPC"

executefile "C:\Users\tusha\Documents\Automation\Automation\Function_library\Tokri_Function\tokri_class.qfl"

Set oh = new tokri

oh.tokri_webedit("Tokri Login" , "username" , "xyz")

Function

Class tokri

'WebEdit Function
Function tokri_webedit(br,we,v)
If Browser("title := "&br).Page("title:="&br).WebEdit("name:="&we).Exist Then
Browser("title := "&br).Page("title:="&br).WebEdit("name:="&we).Set v
reporter.ReportEvent micPass , "Success", "Data Entry Successfull"
else
reporter.ReportEvent micFail , "Fail" , "Object Identification Unsuccessfull"
End If
tokri_webedit = "Data Entered Successfully In Textbox"  
End Function
End Class

How to do integ test using mockito

I have following two methods which i want to test

public class Orders {
    private final LambdaLogger logger;
    private final DynamoDBMapper dynamoDBMapper;

    public Orders(LambdaLogger logger, AmazonDynamoDB amazonDynamoDB){
        this.logger = logger;
        this.dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
    }

    public List<Orders> getOrders(){
        logger.log("getting all orders");

        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
                .withProjectionExpression("OrderId");
        logger.log("Expression created");

        PaginatedScanList<Orders> scan = dynamoDBMapper.scan(Orders.class, scanExpression);

        return scan.stream()
                .collect(Collectors.toList());
    }
}

Now, I want to do testing using Mockito for this class. There are couple of things that I am confuse (or unable to get working).

First, DynamoDBMapper is being created using amazonDynamoDBClient. So if in my class i Mock AmazonDynamoDB, how the dynamoDBMapper would get created?

How would I test that my function is actually setting projection right?

How would i test on paginatedScanList?

Data race when using Gock with HTTP calls in goroutine

I am mocking my HTTP calls during tests with Gock and it works well unless I run the HTTP call from a separate goroutine (think go Post("https://myapi.com", "this body"). I don't really care about the HTTP response in this case and just want to fire the request.

This results in a race condition between http.Client.send() and gock.New(). Is there a way around it or what is the recommended way to mock the API calls in this case?

Thanks!

Rails 5 routing spec requires :path value

After upgrading Rails 4.2.8 to 5.0, all of my routing specs are failing with the same error message:

1) UsersController routing routes to SHOW
     Failure/Error: expect(get: '/users/joe-smith').to route_to('users#show', id: 'joe-smith')

       The recognized options <{"path"=>"users/joe-smith", "controller"=>"users", "action"=>"show", "id"=>"joe-smith"}> did not match <{"id"=>"joe-smith", "controller"=>"users", "action"=>"show"}>, difference:.
       --- expected
       +++ actual
       @@ -1 +1 @@
       -{"id"=>"joe-smith", "controller"=>"users", "action"=>"show"}
       +{"path"=>"users/joe-smith", "controller"=>"users", "action"=>"show", "id"=>"joe-smith"}
     # ./spec/routing/users_controller_routing_spec.rb:10:in `block (3 levels) in <top (required)>'

Finished in 0.05154 seconds (files took 6.86 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/routing/users_controller_routing_spec.rb:9 # UsersController routing routes to SHOW

The spec:

it 'routes to SHOW' do
  expect(get: '/users/joe-smith').to route_to('users#show', id: 'joe-smith')
end

Anyone have any insight into WHY this is happening? I didn't see anything in the Rails 5 CHANGELOG.

How do I use nock to return a default for a path but overwrite that default when I want to?

I'm using nock to mock my api requests in my tests and using persist to set defaults for the requests.

nock('https://myurl.com')
    .persist()
    .get(/api\/endpoint/)
    .reply(200, data)

But I don't always want to reply with data. How would I return other data for a certain request?

Calabash Conditional Scenario Runs

To set the scene, this will be in regards to Calabash-iOS tests. I have a dashboard with multiple scrollable cells. The cells can also be individually resized and reorganized. In addition to that, when you log out and log back into the app, it will remember the state it was in previously before.

I currently have a test that will pinch on the cell to enlarge it and pinch again to shrink it. However, I am unsure of how to check the state of the cell to run specific scenarios. I have a text that will either appear or disappear depending on the state of the cell. So, I will have the following:

Example:
Scenario 1: Enlarging small cell state
  And I don't see the text "text1"
  When I pinch to zoom in on "Cell1"
  And I wait for 5 seconds
  Then I should see "text1"   
  When I pinch to zoom out on "Cell1"   
  And I wait for 5 seconds   
  Then I should not see "text1"

Scenario 2: Enlarge small cell
  Given the app has launched
  And I don't see the text "text1"
  When I pinch to zoom in on "Cell1"
  And I wait for 5 seconds
  Then I should see "text1"
  When I pinch to zoom out on "Cell1"
  And I wait for 5 seconds
  Then I should not see "text1"

My question is - Is there a way for me to determine before hand if "text1" exists to run one scenario and if it doesn't exist, then run the other one?

which browser emulation software has the widest range of browsers / devices?

which browser testing software has the widest range of browsers / devices?

I'm looking for something that will allow connecting to remote devices for full device emulation as opposed to simply responsive design testing.

I'd also (if it exists) like one that allows testing on "in-app" browsers such as apps like Facebook, Instagram, Youtube, Gmail etc.

The Facebook in-app browser must surely be rising to the top of most widely used browser list yet I've seen no reliable way to test.

DIfference between assertEquals and assertSame

have a similar problem

Genericindex a; 
Genericindex b; 

a= datafrommethod();//returns object of Genericindex 
b= datafrommethod();//returns object of Genericindex 

b= anothermethod(b);//sometimes object might be overriden 

if(notoverridden){ 
assertEquals(a,b);}// this fails 

can someone explain why is assert failing?

Python Unittest. Testing a method that prints dynamic data

I am very new to unittest in python (and testing generally). I have written a simple console application which offers the user multiple options which they can choose by entering a number (1-15), and I have a function that, once the input has been checked, prints a response to screen. In addition the response changing depending on the users choice, the response is also dependant on data held in text files and as such is subject to change.

How do I go about testing a function like this?

Thanks

Separate integration tests in Play!/Gradle setup

I'm trying to move my integration tests in Play! Framework app to separate folder and run them separately from other tests. It would be an easy task to do in SBT, but i'm not that good in gradle setup.

My goal is: - move integration tests from play-app/test to play-app/itest - create separate task in build.gradle to run only integration tests

Is there a working example I can follow?

How to test std::bitset for randomity?

I create random bitsets with following code below. Now I wanna write some test and asking myself how to test the randomness of bitsets? Is there a good solution to this problem?

As bitsets can not be represented as numbers AFAIK, I don't know hot to apply some sort of test like chi-square or whatever.

Should I count the ocurrences of 1s and 0s like

 1001
+0101
+1110
+0010
 ----
 2222 = good as half of 4 (bitsets) equal 2

Are there other ways?

template <size_t N>
using bitset_t = std::bitset<N>;

and

template <size_t N>
struct random_bitset_t
{
  static_assert(N % 64 == 0, "random_bitset_t<N> only with N % 64 == 0");

  std::bitset<N> operator()() const;
};

template <size_t N>
std::bitset<N> random_bitset_t<N>::operator()() const
{
  static thread_local std::mt19937 g{std::random_device{}()};

  static thread_local std::uniform_int_distribution<uint64_t> d;

  std::bitset<N> bitset;

  for (int i=0,j=N/64; i<j; ++i)
  {
    bitset <<= 64;

    bitset |= std::bitset<N>(d(g));
  }
  return bitset;
}

and

template <size_t N>
using bitsets_t = std::vector<bitset_t<N>>;

and

template <size_t N>
struct random_bitsets_t
{
  random_bitsets_t(size_t);

  bitsets_t<N> operator()() const;

  size_t size;
};

template <size_t N>
random_bitsets_t<N>::random_bitsets_t(size_t size)
: size(size)
{}

template <size_t N>
bitsets_t<N> random_bitsets_t<N>::operator()() const
{
  bitsets_t<N> bitsets;

  bitsets.reserve(size);

  std::generate_n(std::back_inserter(bitsets),size,random_bitset_t<N>());

  return bitsets;
}

How to test single file Vue components

I would like to use ava for unit testing my Vue components. Right now I have a very simple setup:

package.json

{
    "name": "vue-testing",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "babel": {
        "presets": [
            "es2015"
        ]
    },
    "ava": {
        "require": [
            "babel-register",
            "./test/helpers/setup-browser-env.js"
        ]
    },
    "devDependencies": {
        "ava": "^0.18.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-register": "^6.22.0",
        "browser-env": "^2.0.21"
    },
    "dependencies": {
        "vue": "^2.1.10"
    }
}

./test/helpers/setup-browser-env.js

import browserEnv from 'browser-env';

browserEnv();

./test/Notification.js

import Vue from 'vue/dist/vue.js';
import test from 'ava';
import Notification from '../src/Notification';

let vm;

test.beforeEach(t => {
    let N = Vue.extend(Notification);

    vm = new N({ propsData: {
        message: 'Foobar'
    }}).$mount();
});


test('that it renders a notification', t => {
    t.is(vm.$el.textContent, 'FOOBAR');
});

src/Notification.js

export default {
    template: '<div><h1></h1></div>',
    props: ['message'],
    computed: {
        notification() {
            return this.message.toUpperCase();
        }
    }
};

When I run ava everything works as expected: 1 passed.

I'd be more happy if I could use the following component syntax:

./src/Notification.vue

<template>
    <div>
        <h1></h1>
    </div>
</template>
<script>
     props: ['message'],

    computed: {
        notification() {
            return this.message.toUpperCase();
        }
    }
</script>

But then ava will return the following error:

> 1 | <template>
    | ^
  2 |     <div>
  3 |         <h1></h1>
  4 |     </div>

I can't figure out how to make this work, any help would be greatly appreciated!

Rails 4.2 Integration Tests - Is there any way to reuse test code?

If I start off with a test that checks the user can login:

test "can login successfully" do
  get "/session/new"
  assert_select "h1", "Log in to the Portal"
  assert_response :success
  post "/session", { username: "nick1", password: "password1" }
  assert_response :redirect
  follow_redirect!
  assert_select "h1", "Welcome to the Portal"
end

And in the rest of my tests, I want to test things that depend on the user to being logged in - I obviously don't want to be copying the above code into every test that requires the user to be logged in.

In my case, simulating a logged in user is simply a case of setting a session[:user_id] so I had a look around at setting session data inside the test but it appears to be very tricky. This leads me to think that maybe I could put the above code in some kind of re-usable function and call it from any test that needs a logged in user.

Does this sound like the right approach? if not, how is this problem normally solved?

Enzyme Jest window.getSelection() does not work

How to fix my situation? Jest + Enzyme testing of function below returns "TypeError: window.getSelection is not a function".

    _addNewAgent () {
    window.getSelection().removeAllRanges();

    const newAgent = generateNewAgent();
    const newDataBase = this.state.agentsDatabase;

    newDataBase.push(newAgent);

    this.setState({
        currentAgentProfile: newAgent,
        agentsDatabase:      newDataBase,
        infoDisplayContent:  'profile'
    });
}

My test:

import React from 'react';
import { mount } from 'enzyme';
import App from '../containers/App';

const result = mount(
    <App />
);

test('add agent', () => {
const agentsList = result.state().agentsDatabase.length;

result.find('#addNewAgent').simulate('click');
expect(result.state().agentsDatabase.length).toBe(agentsList + 1);

expect(result.state().currentAgentProfile)
    .toEqual(result.state().agentsDatabase[agentsList]);

expect(result.state().infoDisplayContent).toBe('profile');
});

Swift 3 - UI Tests Mach-O Linker error

I'm trying to write UI & Unit Tests for an app we're working on. In order to make it easy, I've written a class that randomly instantiates objects that can then be used by all the test classes.

The problem I'm encountering right now is that when building UI Tests, the Mach-o linker is throwing some errors saying Symbols not found for architecture ... and referencing my project's main classes and that random object generator.

The weird thing is that, for Unit Tests, the same random generator works just fine !

For context: Doesn't matter if I run everything on actual device or simulator (so the architecture argument in the error is irrelevant)

My project is setup in the following manner:

  • Workspace:
    • Project: My Project
      • Class Foo
      • Class Bar
    • Target: Unit Tests
      • Class RandomObjectGenerator
      • Unit test 1
    • Target: UI Tests
      • UI test 1

Note that RandomObjectGenerator class is assigned to the following targets: RandomObjectGenerator Target

As such, my Unit/UI test classes always specify @testable import MyProject.

Here's the error message thrown during compilation: Compiler Linker error

While in the editor, I can reference those classes just fine...

If anyone has any idea, I'd be glad to hear it. I'm kinda losing my mind to those errors :(

Improve Java LinkList implimentation

I am trying to implement linklist data structure in java. Following is my implementation:

// A singly Linked List
class Node{

int value;
Node next;

Node(int n){
    this.value = n;
    this.next = null;
}

public void printNode(){
    System.out.println("Value: " + value);
}

}

class LinkList{

private Node first;
private Node last;

public LinkList(){
    first = null;
    last = null;
}

public boolean isEmpty(){
    return first == null;
}

public void insertFirst(int n){


    Node node = new Node(n);


    if(first == null){
        System.out.println("1. Vlaue of n: "+n);
        first = node;
        last = node;
    }else{
        System.out.println("2. Vlaue of n: "+ n);
        Node tmp = first; 
        first = node;
        node.next = tmp;

    }

}

public void deleteFirst(){
    if (!isEmpty()){
        Node tmp = first; 
        first = tmp.next;
    }
}

public void deleteLast(){

    if(!isEmpty()){

        Node tmp = first;
        Node oneBeforeLast = null;

        while (tmp.next != null){
            oneBeforeLast = tmp;
            tmp = tmp.next;
        }

        oneBeforeLast.next = null;

    }
}

public void deleteNode(int value){

    if (!isEmpty()) {

        Node tmp = first;
        Node oneBeforeLast = first;

        while (tmp.next != null) {

            if (tmp.value == value) {

                if (oneBeforeLast == first) {
                    first = tmp.next;
                } else
                    oneBeforeLast.next = tmp.next;
            }
            oneBeforeLast = tmp;
            tmp = tmp.next;
            System.out.println("Btmp: " + oneBeforeLast.value + " tmp: 
            " + tmp.value);
        }

        if (tmp.next == null && tmp.value == value) {
            oneBeforeLast.next = null;
        }
    }
}

public void printList(){

    Node tmp = first;

    System.out.println("\nPrinting List:");

    while(tmp != null){
        tmp.printNode();
        tmp = tmp.next;
    }
  }
}


public class LinkListTest {



public static void main(String[] args) {
    // TODO Auto-generated method stub
    LinkList linklist = new LinkList();
    linklist.insertFirst(1);
    linklist.insertFirst(2);
    linklist.insertFirst(3);
    //linklist.insertFirst(3);
    linklist.insertFirst(4);

    linklist.printList();

    //linklist.deleteFirst();
    //linklist.printList();

    //linklist.deleteLast();
    //linklist.printList();

    linklist.deleteNode(1);
    linklist.printList();
 }

}

I would like to improve it further and check its efficiency for large inputs. Can anyone give some pointers on these two pointers please?

Difference between end-to-end testing and unit testing

I cannot quite understand what end-to-end testing means. So what exactly is end-to-end testing and how does it differ from unit testing?

How can i access to another testcase's teststep request?

I have 1 TestsSuite, which contains 2 TestCases. In First TestCase i have a SOAP Test Request. I want to access to this Test Request and i want exactly request of this Request! I used:

def myTestSuite=testRunner.testCase.testSuite.project.getTestSuiteByName("To internal")
def myTestCase=myTestSuite.getTestCaseByName("Create&Repeat")
def myTestStep=myTestCase.getTestStepByName("create")
log.info (myTestStep.getAssertableContent()) //this step to see what i get

So, in this way everything I get is response, but I want request!

How can I do that?

Excluding automatically test without @Test

We have a Java project which relies on Junit and failsafe plug-in to execute the test cases. In order to select the test cases to execute we have created our own @Category annotation and we mark each test to execute with our annotation. In the pom.xml we have added the parameter referring to our annotation. The approach is fine and it works. Now, what I'd like to do is: - to get rid of @Category annotation, marking each test to execute is boring - find a way to exclude automatically all those tests that do not have @Test (we have some super-class that do not need to be executed on their own).

Is there any way to do that?

Thank you

How to make each TestCase call a hook after setUp?

In my project I have a subclass of TestCase (call it BaseTest) which does some stuff to prepare and then reset the testing environment, and a large number of actual test case subclasses (about 80) which each have their own unique setUp methods.

I want each of the individual test case subclasses to call a particular hook at the end of their setUp methods. I would like to do this without making a change to every one of those methods.

Basically, the situation looks roughly like this example file:

import unittest


class BaseTest(unittest.TestCase):
    def setUp(self):
        super().setUp()
        print('prepping env')

    def tearDown(self):
        super().tearDown()
        print('resetting env')

    def post_setup_hook(self):
        print('in post_setup_hook')


class TestFeatureA(BaseTest):
    def setUp(self):
        super().setUp()
        print('prepping a')

    def tearDown(self):
        super().tearDown()

    def test_0(self):
        print('testing a0')

    def test_1(self):
        print('testing a1')


class TestFeatureB(BaseTest):
    def setUp(self):
        super().setUp()
        print('prepping b')

    def tearDown(self):
        super().tearDown()

    def test_0(self):
        print('testing b0')

    def test_1(self):
        print('testing b1')


if __name__ == '__main__':
    unittest.main()

I would like the result of running python -m unittest example to print 'in post setup hook' after each time it prints 'prepping a' or 'prepping b', but without modifying TestFeatureA or TestFeatureB. Can this be done?

Note that I'm using python 3.6. I don't think this will run in python 2.x.

jeudi 27 avril 2017

Testing a method with Akka Actor parameters

I have a task, which I need to test. This task takes some actors as parameters, so I created a test with a TestActor as follows:

Few questions: 1. Is it a normal practice to create ActorSystem for test purposes? 2. The code doesn't end. I have tried to

val system = ActorSystem("TestRoutingSystem")
val actorRef = system.actorOf(Props(new TestActor), name = "testActor")


var poisonReceived = false
var workReceived = 0
class TestActor extends Actor with Logging {
  def receive = {
    case msg: WorkerMessage =>
      workReceived += 1
    case x: Boolean => {
      poisonReceived = true
    }
  }
}

val t = new java.util.Timer()
val task = new TestTask(...)
task.run()
t.schedule(task, 10, 10)
system.shutdown()



Thread.sleep(150)
println(poisonReceived )
println(workReceived)

Odoo unit test dependencies

Running Odoo unit tests seems to be overly complicated. There are a lot of dependencies that I could not find documentation for. Is there some place where these dependencies are documented? Seems like the documentation on odoo's website just has a small section for testing, which does not even list all the available flags.

Alternatively, what are the other options I have for automated testing? I am using Odoo 10 for my development, using gitlab, and I have been told that the runbot has not been ported for v10 yet.

Implemented inteligent/evolutionary testing solutions?

Currently what are the best and most interesting testing solutions that make use of Artificial Intelligence (deep learning also) or Genetic programming.

any links to research papers or technologies would be very useful

Why might a Mockito test pass for any expected number of invocations?

I'm writing the following test using specs2 and Mockito.

class HttpServiceSpec extends Specification with Mockito {
"not accept self-signed certificates if acceptSelfSignedCerts is false" in {
  val httpClientBuilder = mock[HttpClientBuilder]
  HttpService.build(
    httpClientBuilder,
    httpConnectionManager,
    httpRoutePlanner,
    idleConnectionManager,
    _ => sslConnectionSocketFactory,
    sslContextBuilder,
    trustSelfSignedStrategy
  )(0, 0, acceptSelfSignedCerts = false)

  there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)
}
}

Here is the relevant code under test:

object HttpService {
  def build(
    httpClientBuilder: HttpClientBuilder,
    httpConnectionManager: PoolingHttpClientConnectionManager,
    httpRoutePlanner: HttpRoutePlanner,
    idleConnectionManager: IdleConnectionManager,
    makeSSLConnectionSocketFactory: SSLContext => SSLConnectionSocketFactory,
    sslContextBuilder: SSLContextBuilder,
    trustSelfSignedStrategy: TrustSelfSignedStrategy
  )(maxConnections: Int, maxConnectionsPerRoute: Int, acceptSelfSignedCerts: Boolean): HttpService = {
    httpClientBuilder.setRoutePlanner(httpRoutePlanner)

    if (maxConnections > 1) {
      httpConnectionManager.setMaxTotal(maxConnections)
      httpConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute)
      idleConnectionManager.fireEvictionThread()
      httpClientBuilder.setConnectionManager(httpConnectionManager)
    }

    if (acceptSelfSignedCerts) {
      val sslContext: SSLContext = sslContextBuilder.loadTrustMaterial(trustSelfSignedStrategy).build()
      httpClientBuilder.setSSLSocketFactory(makeSSLConnectionSocketFactory(sslContext))
    }

    val client = httpClientBuilder.build()

    new HttpService(client, Some(idleConnectionManager))
  }
}

If I change the last line of the test to either of the following the test will pass:

  there was one(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)
  there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)

However, if I assert both at once, the test fails (as expected):

  (there was one(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)) and
  (there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory))

I don't understand why the test passes with either one of these conditions, but not with both. Am I writing something incorrectly?

How to unit-test channelWritabilityChanged

I am writing a netty server. To handle the slow consumer situation, I use channelWritabilityChanged to detect when the channel becomes un-writable. So how can I write test for this?

I haved tried to use EmbeddedChannel with my InboundHandler, but when I do a EmbeddedChannel.writeOutbound to write something big, the writability changes twice (change to un-writable, and then writable again). It seems that when EmbeddedChannel flushes, the channel will become writable.

Since I cannot use EmbeddedChannel, how can I unit-test my code? How can I create a local channel and write something big to it?

Prevent HtmlUnitDriver headless Selenium test invoke a browser window

We are trying to use HtmlUnitDriver for our GUI-less test automation. Actually we want to test for Chrome browser for compatibility purpose wise. Meaning most of our users are Chrome users. Our invocation is like this ...

driver = new HtmlUnitDriver(BrowserVersion.CHROME); driver.get(baseURL);        driver.sleep(2000);

But when ran, it briefly invoking a Chrome browser window, which closes by itself and the test proceeds OK. HOw can we prevent the Browser intance to open ? This exercise is to avoid the "Chrome not reachable" problem with normal Selenium WebDriver code.

How to loop over a certain time?

I am creating a script that should wait until a certain file (e.g. stop.dat) appears or after certain time (e.g. 500 Seconds) has passed.

I know how to wait until the file appears:

while [ ! -f ./stop.dat ]; do
  sleep 30
done

How can I add the other statement in my while loop?

How to Download and Configure JCov?

I'm new to testing.. I have asked to give a 2 page document about any structural code coverage tools. So thought of JCov. How do i download and configure ? Please do give me Steps or methods else Video Tutorial would be fine too..

How to test if a class is abstract in Typescript using Mocha?

I don't even know if this makes sense as a test, but I was trying to test if some class Component was abstract in Typescript using Mocha by the only way I could think of:

expect( new Component() ).to.throw( new Error( "" ) );

however this gives me an error that makes sense but breaks the test:

Cannot create an instance of the abstract class 'Component'.

Is there any way to correctly test this?

Thank you

Java employment test questions

first time posting here and I'm still fairly junior in Java so please be gentle.

Basically applying for jobs and they get you to do tests to see how proficient you are. The test has since been failed by me, but they never gave the answer for me to learn from. Could you guys please help me to solve this?

Question One

Design and implement a static method map that takes two arguments, a “function” f and a list l, and returns a new list generated from applying f to each element of l. The original list l and its elements should remain unchanged.

Provide example code which uses your map implementation and shows how to implement the function plusOne which takes a number n and returns a new number n+1.

If three is the list containing the numbers 1, 2 and 3, then: map(plusOne, three) will return a new list containing the numbers 2, 3 and 4.

Question Two

You are working on a system which receives prices from an external component at a fast rate. The system needs to process the prices, and typically they cannot be processed as quickly as they arrive, so the implementation must sample the latest price. The external system produces prices for several entities, interleaved into a single sequence of the form:

EntityA: pa1, pa2, pa3…

EntityB: pb1, pb2, pb3…

Time ► ► ►

For example, if during the time taken to process price pa1 the prices pa2, pa3 and pa4 arrive, then the next price the application should process is pa4 and all previous prices should be ignored. Prices for other entities (e.g. pb i) do not affect the latest price for entity a, but are processed independently in the same way with respect to entity b.

Below is the skeleton code for a component that manages prices in this manner. The component needs to be thread-safe (i.e. work without error with concurrent access to update and get prices for the same or different entities, since prices may be updated and accessed by multiple different threads). Complete the code on the following page, implementing the constructor and three methods which are documented.

The following example shows how the component may be used (although single threaded) and the expected output:

Example Output:

    ph.putPrice("a", new BigDecimal(10));

    System.out.println(ph.getPrice("a"));

    ph.putPrice("a", new BigDecimal(12));

    System.out.println(ph.hasPriceChanged("a"));

    ph.putPrice("b", new BigDecimal(2));

    ph.putPrice("a", new BigDecimal(11));

    System.out.println(ph.getPrice("a"));

    System.out.println(ph.getPrice("a"));

    System.out.println(ph.getPrice("b"));

Use the following skeleton: public final class PriceHolder {

       // TODO Write this bit
        public PriceHolder() {
        // TODO Write this bit
        }
        /** Called when a price ‘p’ is received for an entity ‘e’ */
        public void putPrice(String e, BigDecimal p) {
        // TODO Write this bit
        }
        /** Called to get the latest price for entity ‘e’ */
        public BigDecimal getPrice(String e) {
        // TODO Write this bit
        }
        /**
        * Called to determine if the price for entity ‘e’ has
        * changed since the last call to getPrice(e).
        */
        public boolean hasPriceChanged(String e) {
        // TODO Write this bit
        }
    }

Question Three

Extend PriceHolder to provide a method which waits for a price change:

    /**
     * Returns the next price for entity ‘e’. If the price has changed since the last
     * call to getPrice() or waitForNextPrice(), it returns immediately that price.
     * Otherwise it blocks until the next price change for entity ‘e’.
    */
   public BigDecimal waitForNextPrice(String e) throws InterruptedException;

Copy your answer to question two, add this new method and make any necessary modifications to your existing code

Controller test for nested resources

can't go over the problem with CREATING INDEX ROUTE TEST for nested attribute. I've been trying all my ideas but nothing works

I have Service model and ServiceRoute model.

ServiceRoute belongs_to Service

and

Service has_many ServiceRoutes.

Here is my controller:

class ServiceRoutesController < ApplicationController

before_action :set_service_route, only: [:show, :update, :destroy]
before_action :set_service, only: :create


def create
  @service_route = @service.service_routes.build(service_route_params)

  if @service_route.save
    render json: @service_route, status: :created, location: @service_route
  else
    render json: @service_route.errors, status: :unprocessable_entity
  end
end


private

  def set_service_route
    @service_route = ServiceRoute.find(params[:id])
  end

  def set_service
   @service = Service.find(params[:service_id])
  end

  def service_route_params
    params.require(:service_route).permit(:routes_list, :service_id)
  end
end

I create ServiceRoute with build method

My routes.rb file:

resources :services do
  resources :service_routes
end

Test "should create service route" has an error:

ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"service_routes"} missing required keys: [:service_id]

test "should create service_route" do
 assert_difference('ServiceRoute.count') do
  post service_service_routes_url, params: { service_route: {routes_list: 
  @service_route.routes_list, service_id: @service_route.service_id } }, 
 as: :json
end

How should I refactor this test to match the route: /services/:service_id/service_routes

How to test DOM manipulation with Mocha, Chai, Sinon?

I have a function that manipulates an iframe's href. How can I test for DOM manipulation, if at all possible?

Junit 4 global setup and teardown

i want a separate class with setup and teardown for my entire tests. i managed to crate a class that do that (its a bit tricky, hope there is a better way...).

but when running a specific test from intellij (right click on the file), the setup class is not called.

this is my setup class

public class BaseTest extends TestCase {

    private final static Logger logger = Logger.getLogger(BaseTest.class);

   @Override
   protected void setUp() throws Exception {
       ///Some setup code ...

   }

    @Override
    protected void tearDown() throws Exception {
        //Put teardown code here 
    }

    @Test
    public void testMethodA() {} // For some reason i must add this method, for my code to run

}

Web Service Request with Curl

I have requirement where i need to use a curl command to invoke a Webservice and then get a response out of it. I know there are many post with using curl but m question is how can i use curl command to pass the parameters which may be in the request.xml. I cant use the file as a input. Below is the sample file I want a curl command which will run the request and get me a response without an input file.

<soapenv:Header/>
<soapenv:Body>
<web:LogOnUser>
<web:username> </web:username>
<web:password> </web:password>
</web:LogOnUser>
</soapenv:Body>
</soapenv:Header>

How can I run tests from a folder other than the test project's output folder, using MSTest?

Scenario:

I have multiple C# projects in my solution. Each project is built to bin\Debug\. From there, the output from all the projects is copied to a few common output folders using a post-build step. The post-build also creates some necessary files in the common output folders, to create an environment ready to run the complete application. Each project with tests only goes to one of these output folders, but some other projects end up in every output location.


The problem is that my integration tests need to run from the common output folder, because they only work as part of the whole package. (This is because of some of the files created by the post-build, as well as some dynamically loaded assemblies from other projects that are not referenced.)

I've done some reading on test deployment, such as How to: Deploy Files for Tests. That page mentions being able to run tests "in a local test deployment folder on the same machine as the build." This sounds like what I need, but I cannot find any more details on this.

What is a deployment folder? How do I configure it to use a deployment folder? Can I point it to my common output folders and tell it to load and run tests from there? If so, how? If not, is there any other way to run tests based on the complete set of output from the entire solution, rather than just the output from the test project?

How to access a controller helper method from a helper test in Rails 4?

I've got a method defined in ApplicationController as a helper method.

helper_method :can_access_participant_contact_data?

I'm trying to write a test for a helper method that resides in a helper file. This helper method makes a call to 'helper_method :can_access_participant_contact_data?'

def redacted_contact_data participant, attribute_name
  attribute = participant.try(:contact_data).try(attribute_name)
  return attribute if can_access_participant_contact_data?(participant)
  return nil       if attribute.blank?
  return attribute.gsub(/\S/i, '*') # Asterisked string
end

When I run my test, I'm getting this message

undefined method `can_access_participant_contact_data?' for #<ParticipantsHelperTest:0x007fd6c7c6d608>

I've been having a look around but I'm not sure how to get around this issue. Do I need to mock the application controller method somehow? or can I just include the method into the test?

uncaught assertion using mocha/chai

I am using Mocha and Chai to test my code. I have three assertions the first two pass fine but my PUT assertion is failing with an "Uncaught AssertionError: {message:"success" } to have property "name". The structure is the same for the previous tests but this one fails. Here is the test code: More eyes on this would be appreciated since I cannot seem to sort it out:

it("should edit an item on PUT", function (done) {
    chai.request(app)
        .put("/items/3")
        .send({"name":"Kale Dog"})
        .end(function (err, res) {
should.equal(err, null);
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a("object");
res.body.should.have.property("name");
res.body.should.have.property("id");
res.body.name.should.be.a("string");
res.body.id.should.be.a("number");
res.body.name.should.be.equal("Kale Dog");
storage.items.should.be.a("array");
storage.items.should.have.length(3);
storage.items[3].should.be.a("object");
storage.items[3].should.have.property("name");
storage.items[3].should.have.property("id");
storage.items[3].id.should.be.a("number");
storage.items[3].name.should.be.a("string");
storage.items[3].name.should.equal("Kale Dog");
done();
});
});

Here is the actual error message:

Shopping List should edit an item on PUT:
Uncaught AssertionError: expected { message: 'success' } to have 
property 'name'

Exploratory testing with selenium

I need good, specific tutorials to my exploratory testing with selenium. I know selenium can be used to automate testing, but I want to do exploraty testing with this.

How do I test ActionMailer receive method with attachments in local development?

I'm writing an application that will receive emails forwarded by postfix to the rails app, and the app should behave differently if an email has or hasn't attachments.

I saw this in this stackoverflow post and it seems fine to test receiving emails. But I need to test attachments too, how could I do that?

require 'test_helper'
class ReceiverTest < ActionMailer::TestCase


test "parse incoming mail" do
    email = TMail::Mail.parse(File.open("test/fixtures/emails/example1.txt",'r').read)
    assert_difference "ProcessedMail.count" do
      Receiver.receive email
    end
  end

And finally, would I need to install and configure postfix to try the app locally and check if all goes well or do Rails provide another method to do that and leave that configuration for production server?

How can I decrease the threads while running jMeter?

I create a test plan when working with jMeter, and I want to create a test plan with 100 concurrency users.

After first page(homepage) I want to decrease 50 users(drop-off and do not access to next page) while 50 another users continue access to another page.

Someone suggested me use Ultimate Thread Group but I think it can't help.

Any idea for this issue?

Automation test multi languages for android app?

I have a multi-language application and a data.xlsx file that contains the text used in my application. How do I setup automation test for multi languages for android app? thanks all!

Testing if Undefined method error occures

In my Rails project I'm testing one of my model's :currency attribute presence validation.

I'm also using Money gem and in case of creating a model without a :currency attribute it gives me following error:

"NoMethodError Exception: undefined method `subunit_to_unit' for nil:NilClass"

Because of this my assert(account).invalid? test does not fail, but gives error.

How should I rewrite my test now so that it checks for error occurence instead of model validation?

Or should I do something else in the model instead?

mercredi 26 avril 2017

is there a way to include MockNgZone to test an angular app?

I was creating my own mocks for testing an Angular service that I wrote and then noticed that the Angular code has a mock for NgZone, but I can't figure out if there is a way to include it in my code.

Source file is here: http://ift.tt/2p5STtw

Python-Selenium-Chrome minimized window is maximizing itself

I am using Selenium with chromedriver in Python for testing 2 functionalities in parallel. Basically my webpage have 2 dropdown menus. Choosing an option from any dropdown menu will download a file. I have 2 scripts testing both dropdown menus separately. Now let say script-1 opens chrome and load the webpage. Now script-1 opens the dropdown-1 and it is in process of selecting an option from it as per the given input. During this if I navigate away from opened webpage to any other window eg. file explorer, the dropdown will get close without choosing the option and test case hangs. Also if I minimize the window before the dropdown is opened, the window will reopen itself when option is clicked for downloading the file. How can I stop the window from re-opening. Is there any Chrome setting for this?

Even if I move away from computer during execution, I want to run both the scripts in parallel side by side as they both open separate windows but after sometime one of them hangs the other window and I have to manually click on dropdown to bring it back to life. I am planning to run the scripts using multithreading with 2 threads referring to each of the scripts.

Note : I cannot use urlretrieve as there is no pre-defined URL for the files in webpage. PhantomJS do not support file download.

Rails spec test error, no password supplied

I have an existing project, with created many years ago. No one at out company has succeeded in running them. I have updated files to fit the latest rails version but when I run bundle exec rspec spec/models/promo_code_spec.rb,

I get

   /Users/mmiller/.rvm/gems/ruby-2.1.6@global/gems/activerecord-4.1.9/lib/active_record/connection_adapters/postgresql_adapter.rb:888:in `initialize': fe_sendauth: no password supplied (PG::ConnectionBad)

I have followed these steps in this post: fe_sendauth: no password supplied but still getting the same error. Any advice on how to resolve this issue?

Test Google Analytics on Android devices

Is there an automation test framework to test Google Analytics on Android? Ex. to be sure that correct events are triggered on the particular screen for user action? And that events not sent to Google from places where they are not supposed to be?

how to pass gradle systemProperties JUnit5 tests

i am using gradle 3.5 and Unit 5 (jupiter).

i wish to pass System property to my tests, in order to configure the test

i am running the test using this command gradle test -Denv=envFile1

here is my grade file :

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M4' //JUnit 5
    }
}

repositories {
    mavenCentral()
}   

ext.versionJunitPlatform        = '1.0.0-M4'
ext.versionJunitJupiter         = '5.0.0-M4'
ext.versionLog4j                = '1.2.17'
ext.versionRestAssured          = '2.9.0'
ext.versionRestAssuredJsonValid = '3.0.2'
ext.versionHamcrest             = '1.3'
ext.versionJacksonDatabind      = '2.9.0.pr2'
ext.versionSeleniumJava         = '3.3.1' 

test.systemProperties System.properties

dependencies {
    compile group: 'log4j'                      , name: 'log4j'                 , version: "$versionLog4j"               //Log4j
    compile group: 'com.jayway.restassured'     , name: 'rest-assured'          , version: "$versionRestAssured"         //Rest Assure
    compile group: 'io.rest-assured'            , name: 'json-schema-validator' , version: "$versionRestAssuredJsonValid"     //Rest Assure schema validation
    compile group: 'org.hamcrest'               , name: 'hamcrest-all'          , version: "$versionHamcrest"      //Rest Assure assertion
    compile group: 'com.fasterxml.jackson.core' , name: 'jackson-databind'      , version: "$versionJacksonDatabind" //Serilize/Deserialize Request/Response objects
    compile group: 'org.seleniumhq.selenium'    , name: 'selenium-java'         , version: "$versionSeleniumJava"    //Selenium core, E2E testing

    testCompile group: 'org.junit.jupiter' , name: 'junit-jupiter-api'     , version: "$versionJunitJupiter"
    testRuntime group: 'org.junit.jupiter' , name: 'junit-jupiter-engine'  , version: "$versionJunitJupiter"
}

Here is my test:

package com.somecompany.someProject.tests;

import org.junit.jupiter.api.Test;

public class AaTest {
    @Test
    public void a() {
        System.out.println("a test: " + System.getProperty("env"));
    }
} 

This is the output i get

gradle test -Denv=envName
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:junitPlatformTest
a test: null

thank you

shay

Unit Test a private field which is behavior relevant

first of all: I found few solutions for my problem but the "newest" one was from 2014 and used reflections so I hope I could maybe find some more advanced solutions for my question.

Thats the case and its about migrateUser and canAdd. This is an example class to make my question easily visible.

public class UserInterfaceImpl implements UserInterface {

    private final List<T> accountList = new LinkedList<>();
    private final AccountInterface accountInterface;
    private boolean bonusReceived = false;

    public UserInterfaceImpl(AccountInterface accountInterface) {
        this.accountInterface = accountInterface;
    }

    public void migrateUser(AccountMergerInterface accountMerger, UserInterface oldUser) {
        boolean success = accountMerger.performChange(this, oldUser);
        if (success && !bonusReceived) {
            //addBonus
            accountInterface.deposit(1);
            bonusReceived = false;
        }
    }

    public boolean canAdd() {
        return accountList > 0;
    }

    public AccountInterface getAccount() {
        return accountInterface;
    }
}

The migrateUser class changes the some account Data which is not relevant for my test because I would test it seperatly of course (should be like that what I read so far).

So I wonder, how can I see if the behavior of that class changes the bonusReceived correctly? Without using reflections and do it as sophisticated as possible?

My first attempt was that:

@Test
public void testMigrateUser() {
    AccountMergerInterface test = mock(AccountMergerInterface.class);

    // define return value for method getUniqueId()
    when(test.performChange()).thenReturn(true);
}

But know I cannot continue. The rule should be in my example to have no getter and setter! The class should be like my example.

I don't know how to:

  1. set bonusReceived to false before migrateUser is executed that accountInterface.deposit(1); is not executed
  2. see if bonusReceived will be set to false if the if() continue is true
  3. Same questions for the List. How can I access the private field of List, add an Object so that the return value is true and false. Or should I "simulate" a List and if yes, how can I do that?

Thanks in advance!

Bypass google recaptcha for bot test

Has there anyone come out with a good way to bypass a Recaptcha check in a page to launch a bot test?

Basically, I want for a particular bot (for which I know the IP address) to bypass a google recaptcha check and not sure what would be the most apropiate way of doing it.

I have seen this question How to bypass recaptcha human check in nightwatch test? but it does not seem to give a clear anwser.

Thanks

Mocking HttpClient for component testing an aurelia class

I have an aurelia class which looks like this:

import {HttpClient} from 'aurelia-fetch-client'

export class Lobby {
  constructor() {
    this.propertyName = 'description'
  }

  fetch() {
    new HttpClient().fetch('/api/package.json')
      .then(response => response.json())
      .then(data => {
        this.response = data[this.propertyName] || Object.keys(data)
      })
  }
}

I want add a component test for this class where I trigger #fetch() and control the server response in my test, essentially mock the http backend. My tests looks like this:

describe('the lobby', () => {
  let component
  beforeEach(done => {
    component = StageComponent.withResources('lobby')
      .inView('<lobby></lobby>')
      .boundTo({})

    component.bootstrap(aurelia => {
      aurelia.use.standardConfiguration()
    })

    component.create(bootstrap).then(() => {
      window.Promise = Promise
      done()
    })
  })

  it('should fetch a result via HttpClient', (done) => {
    const inputElement = document.querySelector('input');
    const button = document.querySelector('button')
    const output = () => document.querySelector('pre')
    expect(inputElement.value).toBe('description')
    button.click()

    waitFor(() => output().innerText !== '').then(() => {
      expect(output().innerText).toBe('foo');
      done()
    })
  })
})

This does not work because aurelia-fetch-client performs an actual HTTP request and there is no backend running. How do I mock the HttpClient in a way that I have control over the response?

Note: #waitFor() is a function that I derived from here, I created a gist with it here. I have created a pull request for my version of the #waitFor(). When it gets accepted the gist becomes irrelevant.

Integration testing of React front end with Django REST backend

Does anybody know how to do integration testing of a (React) frontend with Django REST backend. I was able to write functional tests for the frontend with Nightwatch.js and with a fake server API. I am also able to separately test Django REST API - Django offers a LiveServerTestCase that can start a test server for you with a test database and destroy it at the end. I'm wondering if it's possible to somehow use/setup Django's test server that can be called by the front end (i.e. Nightwatch tests). I'm open to other ideas on how I can approach this problem.

Test component metadata

We just would like to test ChangeDetection value on few components but we don't find a way to access easly to component metadata. For pipe we have found:

it('should be marked as pure', () => {
        expect(new PipeResolver().resolve(TranslatePipe).pure).toEqual(true);
    });

Main problem here is to find a easy way to do it for component and check if it is OnPush or not. Any idea here? So thanks.

ALM QC Test Coverage Progress Report

I have been handed over responsibility of improving the current reporting structure of a project on ALM QC. What is the best way for me to produce a graph/report showing planned vs actual vs actual passed?

Ideally this would be directly via QC rather than querybuilder and then excel. The test cases had not been linked with Releases/Cycles which I have now done, however the coverage progress graph is not pulling the data so I wonder if I am missing a step?

Any help would be much appreciated

Thank you

Angular4 junit test with karma : does not load javascript

I've converted my project to angular 4 / angular-cli 1.0.0 And since then, I have a strange behavior when I want to run the tests

my config :

 @angular/cli: 1.0.1 
 node: 7.8.0
 os: win32 x64
 @angular/common: 4.0.3
 @angular/compiler: 4.0.3
 @angular/core: 4.0.3
 @angular/forms: 4.0.3
 @angular/http: 4.0.3
 @angular/platform-browser: 4.0.3
 @angular/platform-browser-dynamic: 4.0.3
 @angular/router: 4.0.3
 @angular/cli: 1.0.1
 @angular/compiler-cli: 4.0.3

my karma.config.js

 module.exports = function (config) {
   config.set({
   basePath: '',
   frameworks: ['jasmine', '@angular/cli'],
   plugins: [
    require('karma-jasmine'),
    require('karma-phantomjs-launcher'),
    require('karma-firefox-launcher'),
    require('karma-chrome-launcher'),
    require('@angular/cli/plugins/karma'),
    require('karma-jasmine-html-reporter'),
    require('karma-coverage-istanbul-reporter')
    ],
   client:{
       clearContext: false // leave Jasmine Spec Runner output visible in 
        browser
   },
   files: [
      { pattern: './src/test.ts', watched: false }
   ],
   preprocessors: {
      './src/test.ts': ['@angular/cli']
   },
   mime: {
     'text/x-typescript': ['ts','tsx']
   },   
   coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ]
   },
   reporters: config.angularCli && config.angularCli.codeCoverage
          ? ['progress', 'coverage-istanbul']
          : ['progress'],
   port: 9876,
   colors: true,
   logLevel: config.LOG_INFO,
   autoWatch: true,
   browsers: ['PhantomJS','Firefox','Chrome'],
   singleRun: false
  });
 };

when i launch test with ng test --browsers Chrome No test run (nut there is no errors),it seems that he does not find any test enter image description here

indeed , in browser , i don't see my javascripts

enter image description here

BUT when i modify one of junit test (xxx.psec.ts with an editor) (by adding a space line), the javascripts are loaded in browser enter image description here

and my tests are running enter image description here

why are not my tests running at first time?

Order of Resource files causing InvalidElementStateException in robot framework

I have strange problem with Robot framework. Order of my Resource files in which I keep Keywords is causing Error: invalid element state: Element is not currently interactable and may not be manipulated.

To be more specific, in one file i have keyword which is signing in user to application in another i have keyword which is registering user. Test case is using both keywors. It looks like this:

*** Settings ***
Resource | RegistrationPage.robot
Resource | LoginPage.robot


*** Test Case ***
RegistrationPage.Register
LoginPage.Login

Now in example above Register Keyword is working but Login is not and I get mentioned error. If I change order of Resource files Register keyword stops working with the same error but Login starts working properly. The page is displayed correctly but it seems like robot framework has issues connecting with page elements. Maybe someone knows why. Because I have no idea.

Spring Boot tests always running schema-${platform}.sql

When I run tests on Spring Boot the both schema-${platform}.sql and data-${platform}.sql is running.

In my scenario I have to remove the schema.sql from tests and set the datasource property datasource.jpa.hibernate.ddl-auto=update. When I remove the 'Schema 2' from test folder the 'Schema 1' keep running.

I have the following directory structure:

├───src
│   ├───main
│   │   └───resources
│   │       ├───locale
│   │       └───static
│   │       └data-mysql.sql
│   │       └schema-mysql.sql //Schema 1
│   └───test
│       └───resources
│          └data-mysql.sql
│          └schema-mysql.sql //Schema 2

-> Both Schema 1 and Schema 2 has the same sql instructions.

Is there anyway to keep the data-mysql.sql on tests folder, remove the schema-mysql.sql from test folder and the tests not run the 'Schema 1'?

How to inject mocked objects from Test to Controller

Currently I am sending the mocks to the controller through the request method in the returnURL function, but I'd like to know if there is a better way to use/send this mocks in the controller, because it seems like this way is a bad practise.

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

    $this->client = static::createClient();
    $this->peopleManager = $this->getMockBuilder(PeopleManager::class)
        ->setMethods(['createPerson','peopleUpdate', 'peopleDelete', 
        'peopleRead'])
        ->disableOriginalConstructor()
        ->getMock();

   $this->repository = $this->getMockBuilder(EntityRepository::class)
       ->disableOriginalConstructor()
       ->getMock();

   $this->em = $this->getMockBuilder(EntityManager::class)
       ->disableOriginalConstructor()
       ->getMock();

   $this->client->getContainer()->set('people.manager', $this->peopleManager);
}

public function returnURL($secc)
{
   return $this->client->request('POST', '/api/' . $secc, array('array' => array([
       "name"=>"Juan",
       "surname"=>"Hernandez",
       "secondSurname"=>"Macias",
       "nationality"=>null,
       "birthday"=>null,
       "identityCard"=> "12345678a",
       "identityCardType"=> null
   ]),
        'em' => $this->em,
        'repository' => $this->repository
   ));
}

public function test_update_person_action()
{
    $persona= $this->returnPerson();
    $personaSinActualizar = $this->returnPeople('210', 'Anton', 'Antonyan', 'A', '42226114T');
    $this->peopleManager->method('peopleUpdate')->will($this->returnValue($persona));

    $this->repository->expects($this->exactly(1))->method('find')->will($this->returnValue($personaSinActualizar));
    $this->em->expects($this->exactly(1))->method('getRepository')->will($this->returnValue($this->repository));

    $this->returnURL('updateperson/210');
    $content = json_decode($this->client->getResponse()->getContent());
    $testValues = array
    (
        '212',
        'Juan',
        'Hernandez',
        'Macias',
        '12345678a'
    );
    $contador=0;
    foreach ($content as $partContent)
    {
        $this->assertEquals($testValues[$contador], $partContent);
        $contador++;
    }
}




class RestController extends FOSRestController
{
private $repository;
private $em;

public function updatePersonAction($id, Request $request)
{
    $this->em = $request->request->get('em');
    $this->repository = $request->request->get('repository');

    $this->repository = $this->em->getRepository('GeneralBundle:People');
    $person= $this->repository->find($id);
    if($person)
    {
        $data = $request->request->get('array');
        $createdPeople = array();
        $UpdatedPerson = "";
        foreach($data as $content)
        {
            $UpdatedPerson = $this->get('people.manager')->peopleUpdate(
                $person,
                $content['name'],
                $content['surname'],
                $content['secondSurname'],
                $content['nationality'],
                $content['birthday'],
                $content['identityCard'],
                $content['identityCardType']
            );
            array_push($createdPeople, $person);
        }
        $serializedEntity = $this->get('serializer')->serialize($UpdatedPerson, 'json');
        return new Response($serializedEntity);
    } else {
        $serializedEntity = $this->get('serializer')->serialize('Doesn\'t exists any person with this id', 'json');
        return new Response($serializedEntity);
    }
}

Get auth token in Gatling from meta tag

This is the sample DOM content of our app.

<head>
<title>aaa</title>
<meta name="sample" content="sample">
<meta name="sample" content="sample">
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="token">

Hi I would like to extract the token content (in 4th line) and save it in a variable to use it. But I am unable to achieve using Regex too. gatling do support meta tags?

Anyone faced the same?

Thanks, jay

Test cases execution slowed down after upgrade to rails 5

I have upgraded rails to rails-5, Now test cases are taking too much time to execute. There are lots of warnings. What can be done to minimize test case execution time? Before that, it was running in very less time.

How to setup Arrivals Thread Group(Custom Thread Groups)

I haved used a Jmeter plugin named as Custom Thread Group -> Arrivals Thread Group available at location http://ift.tt/2ovdPM2 for arrival rate simulation. I have a vague idea about its configuration perperties. This is the configuration of my test plan arrival thread group properties:

Target Rate(arrivals/min): 60
Ramp Up Time(min): 1
Ramp-Up Steps Count: 10
Hold Target Rate Time(min): 2
Thread Iterations Limit: 

Can anybody help me to understand clearly what is the usage of all these properties.

enter image description here

How to test dummy credit card details in PayPal?

I'm setting up a WooCommerce website and I'm testing PayPal payments. I've tried the numbers on here: http://ift.tt/1lzAnRb

I'm trying to test payment with a credit card without having a PayPal account, but doing it through PayPal's system.

Problem is, the list only includes card numbers, but the payment requires a CVV, correct address/location/country etc. and phone number. I've tried putting in random information for the rest but it throws and error, saying that its invalid.

Thankyou for any help in advance.

getTitle() function returns incorrect result in Selenium web driver

I am trying to run a simple automated test script to get webpage title and verify it by using in selenium-webdriver by Java and IE, but getTitle() method returns strange result.

I could see when I run my test script initially is getting load a default page with below URL,

http://localhost:44585/

and then its navigating to my target URL (which is mentioned in script).

But still script is capturing the page title from above localhost URL not from target URL. Please advise how can I bypass the default (http://localhost:44585/) page.

Mocking and changing dependencies values in jasmine testcase

i recently started learning how to write unit test case using jasmine for my angular project.

i was writing test for my service and facing a problem

describe 
     var servicename;
     beforeEach
         load module
         mock data for some dependency x

     beforeEach
         take service in servicename using injector

     testcase 1
         check some assertion by calling method on servicename
         mock data for same dependency x to some other value
         check some assertion by calling method on servicename

i am not sure how i can change the value of mock data in testcase , please let me know how i can achieve this and if you have any other better way to do this

i can achieve this by writing 2 describe for different mock data but i don't want to do that

Survive segmentation fault with "rake test"

I have some Rails tests, using Minitest, which unfortunately trigger a segfault. This breaks execution of remaining tests.

Until I can fix the segfaults, what's a performant way to ensure "rake test" will run all tests instead of aborting on the first encounter of a segfault?

mardi 25 avril 2017

I am getting an error while trying to install macaca to inspect elements in iOS app using Appium 1.6.4

>> xctest-client start with port: 8900

WebDriverAgent version: 1.1.6 app-inspector:66:44 [master] pid:5022 undefined (node:5022) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: >> app-inspector:66:44 [master] pid:5022 undefined

Above is the error I get. Any solution or way to get it installed. Are there any other option to inspect elements for iOS app .

Can someone let me know the exact steps for configuring appium on mac

I want to test a native app on a real ios device. For now i have installed xcode 8.3, appium server 1.6.4. And i am using mac OS 10.12. i have included webdriver, java client jars on eclipse.

public class appiumtest {
public static void main(String[] args) throws MalformedURLException {
    WebDriver driver;
    DesiredCapabilities capabilities= new DesiredCapabilities();
    capabilities.setCapability("deviceName", "Nisha iphone");
    capabilities.setCapability(CapabilityType.BROWSER_NAME, "ios");
    capabilities.setCapability(CapabilityType.VERSION, "10.2");
    capabilities.setCapability("platformName", "ios");
    capabilities.setCapability("udid", "9ded1b716dd992f715f7b673ff6fd1ce7606860f");
    capabilities.setCapability("appPackage", "xxx");
   capabilities.setCapability("appActivity", "xxx");
    capabilities.setCapability("appWaitActivity", "xxx");
    driver=new RemoteWebDriver(new URL("http://ift.tt/1eWSHgW"), capabilities);
    driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    WebDriverWait wait = new WebDriverWait(driver, 50);

}

Thats my code. And i get this error :Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{browserName=ios, platformName=ios, udid=9ded1b716dd992f715f7b673ff6fd1ce7606860f, deviceName=Nisha iphone, version=10.2}], required capabilities = Capabilities [{}] Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'

Can i know the exact steps for setting up appium on mac for testing ios applications.

Expect-lite skipping program output?

I'm writing a test for a very simple local program that will read a book collection information and then print the whole list on screen. So a program run might look like this:

Title:
Romeo and Juliet
Author:
Shakespeare
ISBN:
9780199535897
Publisher:
Oxford University Press
Pages:
464
Title:
The prince
Author:
Machiavelli
ISBN:
9781545067680
Publisher:
CreateSpace Publishing
Pages:
94
======FULL LIST:======
Title: Romeo and Juliet
Author: Shakespeare
ISBN: 9780199535897
Publisher: Oxford University Press
Pages: 464
---
Title: The prince
Author: Machiavelli
ISBN: 9781545067680
Publisher: CreateSpace Publishing
Pages: 94
---

I'm using regex to ignore case in user prompts like "title" and also ignore if there are any other characters (e.g.: spaces, a colon, etc.) so the script also accepts "--Title:--" and such. I basically want to test that it's correctly storing and displaying the data I enter.

My script looks like this:

*/\n/
>./myTestProgram
<.*t|Ti|It|Tl|Le|E.*
>Romeo and Juliet
<.*a|Au|Ut|Th|Ho|Or|R.*
>Shakespeare
<.*i|Is|Sb|Bn|N.*
>9780199535897
<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*
>Oxford University Press
<.*p|Pa|Ag|Ge|Es|S.*
>464
<.*t|Ti|It|Tl|Le|E.*
>The prince
<.*a|Au|Ut|Th|Ho|Or|R.*
>Machiavelli
<.*i|Is|Sb|Bn|N.*
>9781545067680
<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*
>CreateSpace Publishing
<.*p|Pa|Ag|Ge|Es|S.*
>94
<.*
<.*t|Ti|It|Tl|Le|E.*Romeo and Juliet
<.*a|Au|Ut|To|Or|R.*Shakespeare
<.*i|Is|Sb|Bn|N.*9780199535897
<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*Oxford University Press
<.*p|Pa|Ag|Ge|Es|S.*464
<.*
<.*t|Ti|It|Tu|Ul|Lo|O.*The prince
<.*a|Au|Ut|To|Or|R.*Machiavelli
<.*i|Is|Sb|Bn|N.*9781545067680
<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*CreateSpace Publishing
<.*p|Pa|Ag|Ge|Es|S.*94
<.*

But when I run it, it fails, and using verbose mode shows it seems to not be waiting for the program output before feeding it data, so it's taking the wrong data each time:

$ ./expect-lite -c myTestProgram.elt -r Localhost -vv
expect-lite version 4.9.0
Env Vars -> Constants:
EL_CONNECT_METHOD=none
spawn bash
<<$ >>
INFO: User Defined Prompt: \n
[\u@\h:\w]\$ "
[hp@hp-HP:~/expect-lite.proj]$
[hp@hp-HP:~/expect-lite.proj]$ ./myTestProgram



find<<.*t|Ti|It|Tl|Le|E.*>>
>>in<<./myTestProgram


Romeo and Juliet



find<<.*a|Au|Ut|Th|Ho|Or|R.*>>
>>in<<Romeo and Juliet


Shakespeare
Title:
Author:
ISBN:



find<<.*i|Is|Sb|Bn|N.*>>
  in<<Shakespeare
Ti>>


9780199535897
Publisher:



find<<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*>>
  in<<9780199535897
Pu>>


Oxford University Press
Pages:



find<<.*p|Pa|Ag|Ge|Es|S.*>>
  in<<Oxford University Press
Pa>>


464
Title:



find<<.*t|Ti|It|Tl|Le|E.*>>
  in<<464
Tit>>


The prince



find<<.*a|Au|Ut|Th|Ho|Or|R.*>>
  in<<Th>>


Machiavelli



find<<.*i|Is|Sb|Bn|N.*>>
  in<<Machiavelli>>


9781545067680
Author:
ISBN:
Publisher:



find<<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*>>
  in<<9781545067680
Author:
ISBN:
Pu>>


CreateSpace Publishing



find<<.*p|Pa|Ag|Ge|Es|S.*>>
>>in<<CreateSpace Publishing





find<<.*>>
  in<<>>


94
Pages:
======FULL LIST:======:
Title: Romeo and Juliet
Author: Shakespeare
ISBN: 9780199535897
Publisher: Oxford University Press
Pages: 464
        --------------
Title: The prince
Author: Machiavelli
ISBN: 9781545067680
 ublisher: CreateSpace Publishing


find<<.*t|Ti|It|Tl|Le|E.*Romeo and Juliet>>
  in<<94
Pages:
======FULL LIST:======:
Title: Romeo and Juliet
Author: Shakespeare
ISBN: 9780199535897
Publisher: Oxford University Press
Pages: 464
        --------------
Title: The prince
Author: Machiavelli
ISBN: 9781545067680
Publisher: Creat>>





find<<.*a|Au|Ut|To|Or|R.*Shakespeare>>
  in<<eSpa>>





find<<.*i|Is|Sb|Bn|N.*9780199535897>>
  in<<ce Publishi>>



Pages: 94
        --------------
[hp@hp-HP:~/expect-lite.proj]$


find<<.*p|Pu|Ub|Bl|Li|Is|Sh|He|Er|R.*Oxford University Press>>
  in<<ng
Pages: 94
        --------------
[hp@hp-HP:~/expect-lite.p>>



Waiting: ....+....


find<<.*p|Pa|Ag|Ge|Es|S.*464>>
  in<<ng
Pages: 94
        --------------
[hp@hp-HP:~/expect-lite.p>>




 FAILED COMMAND:94

    Expect Failed:.*p|Pa|Ag|Ge|Es|S.*464

exit


##Overall Result: FAILED

Any ideas on what might be the problem? Is there a way to force expect-lite to wait for the program output before it sends anything to it?

Symfony how to test an AJAX request

In my project I have a piece of my form that sends an AJAX request:

 $.ajax({
     url: '/bio_control/sample',
     type: 'POST',
     dataType: 'json',
     data: {sample_number: $(input_field).val()}, 
 });

Which activates the following controller method:

/**
 * @Route("/bio_control/sample", name="get_bio_control_sample")
 */
public function getBioControlSampleAction(Request $request)
{

    $sample_number = $request->request->get('sample_number');

    /**
     * Additional logic not shown for brevity.
     */

    $user_id = $user->getId();
    $response = array("code" => 100, "success" => true, "sample_number" => $sample_number, "sample_data" => $sample[0], "new_user" => false, "user_id" => $user_id);

    return new JsonResponse($response);
}

I'd like to be able to test this request in isolation, but I'm unsure how to write the request object.

So far my first attempt:

public function testGetBioControlSample()
    {
        $helper = $this->helper;
        $client = $this->makeClient();
        $crawler = $client->request('POST', "/bio_control/sample", array(), array('sample_number' => 67655), array(
            'CONTENT_TYPE' => 'application/json',
            'HTTP_X-Requested-With' => 'XMLHttpRequest'
        ));
        $this->assertStatusCode(200, $client);
    }

Fails because it appears to be submitting the form (I get an error related to a form field completely unrelated to the AJAX request being blank).

Can anyone demonstrate how to correctly write such a test?

iOS UI Test typeText With Custom Keyboard

I have a UIKeyInput that essentially renders LaTeX. It's paired with a custom keyboard, that can send LaTeX commands. When commands are pressed on the keyboard, they invoke the insertText method on the input. These commands are often more than one character. For example, \sigma.

When testing, I'm calling typeText('\sigma').

The issue is that it's sending the characters one-by-one, so it's not able to handle commands.

What are my best options here? If I could get access to the underlying UIView, I could just perform the insertText selector.