jeudi 31 août 2017

Where to test default method implementation of superclass

I have fallowing classes:

Parent.java

interface Parent{
    void method1();

    default void method2(){
       //some default impl
    }
}

ChildOne.java

class ChildOne implements Parent{
    @Override
    void method1(){
        //ChildOne specific implementation
    }
}

ChildTwo.java

class ChildTwo implements Parent{
    @Override
    void method1(){
        //ChildTwo specific implementation
    }
}

Question is: where I should put a method 2 test? I know that for unit tests I should test concrete implementation so ChildOne and ChildTwo but when I have the same implementation of method2 I don't want to duplicate my test for it. However putting it into one of these classes don't seems to be good either.

Ofc, question is the same for abstract class with default implementation instead of interface.

how to grand all camera permission for chrome driver in selenium

iam a begiiner in selenium,one part of my testing is to open a page and click a picture using the camera, but while automating in chrome driver every time a pop up occurs asking"to allow permission", how to automate it, how to grant all the permission at initializtion of the driver itself.

How to test a function which loads a DLL

I have a dll (MyDLL.dll), which I am loading in some class function and then calling a function "DLLProc" from it. Can I write this FuncLoad to be able to test it using a test framework like GTest / GMock...

HMODULE module;
SomeInterface service;
.
.
.
void MyClass::FuncLoad()
{
    auto libPath = std::wstring(L"MyDLL.dll");
    module = LoadLibrary(libPath.c_str());

    if (NULL != module)
    {
        ProcType fnObj = (ProcType)GetProcAddress(module, "DLLProc");
        if (NULL != fnObj)
        {
            service = fnObj();
        }
    }
}

Not Able To Send Audio File Send Using SIPp tool

<nop>
 <action>
   <exec rtp_stream="file.wav" />
 </action>
</nop>

Sipp displays error illegal scenario file.

What is Android Test Orchestrator?

Google released Android Testing Support Library 1.0 recently. After reading the overview, I'm a little confused with Android Test Orchestrator.

It said

Typically, AndroidJUnitRunner runs all tests in the same instrumentation process, which can cause a number of problems.

Can you explain which kinds of problems will be caused by using the same instrumentation process?

if one test crashes, it prevents the remainder of the test suite from running

Through my experience, one test crash won't prevent from other test cases from running. Please point out what I misunderstood here?

And from Android Testing Orchestrator developer guide,

For completeness, Android Test Orchestrator runs pm clear after each test.

So Android Test Orchestrator will run pm clear [test_package_name] after each test, right?

Through my test, pm clear [app_package_name] won't be executed after each test. That means the data of application under test will not be cleared. So test cases might still have dependencies on each other. For example:

  • Test case A stores a SharedPreference key-value
  • Test case B which runs after test case A can read out the value stored by test case A

Overall, after some trial, I did not find any advantage of Android Test Orchestrator. Can somebody help to address my confusion? Thanks.

Enzyme cannot find child component in shallow test

Is this not the correct way to render a react/reflux test with enzyme but without the store, ie, "dumb"

import React from 'react'
import { shallow, render } from 'enzyme'
import { Controls } from '../Controls' // named export
import LoadingSpinner from '../LoadingSpinner'
let wrapper
let loadingFlags = {
  controls: true
}
describe('<Controls />', () => {
  it('should render only the loading spinner', () => {
    wrapper = shallow(<Controls loadingFlags={loadingFlags} />) // this ensures the spinner will show until data is ready
    expect(wrapper.length).toEqual(1) // test passes
    expect(wrapper.find(LoadingSpinner)).to.have.length(1)
    // ^ TypeError: Cannot read property 'have' of undefined
  })
})

When I log wrapper.html() I can see the <img class='spinner' /> is rendered, but enzyme cannot find it as a component. To me, the docs indicate this is exactly what I should be doing. I suppose I could check for a child with that class, but that seems messier than checking for the component itself, eg the class changes within the Spinner component.

How can I test for the existence of this child component?

Delphi Executable specification tools

Are there Delphi tools or frameworks for creating executable specifications.

I know there are unit testing tools but I am interested specifically in creating human readable tests similar to cucumber or specflow?

Should beginner programmers use unit testing?

I have been learning PHP for several months now. It is not my first language, but it is the first language I have tried to use for real-life projects. Currently I am writing a web application that can be easy for experienced programmers but is rather hard for me. And the more I write it, the more I realise that I spend more time pressing buttons and entering inputs to test my code than actually writing code. I have heard about unit testing (and other kind of testing) and it got me wondering: does my simple web application need any automated testing or is it a complete overkill? Is unit testing something a beginner can learn or is it only something experienced programmers use correctly? And since I am writing a web application, can all its code be tested or only the small logic parts?

Thank you.

Using Mocha with TypeScript paths

I'm having an issue with running mocha when using the paths + baseUrl configuration in TypeScript

My tsconfig.js is set like so:

"baseUrl": "./src/", /* Base directory to resolve non-absolute module names. */
"paths": {
  "interfaces/*": [
    "interfaces/*"
  ],
  "models/*": [
    "models/*"
  ],
  "schemas/*": [
    "schemas/*"
  ],
  "classes/*": [
    "classes/*"
  ],
  "libs/*": [
    "libs/*"
  ],
  "config/*": [
    "config/*"
  ]

and I'm runnings mocha as "mocha build/test"

The compiled TS code fails to find my references since it compiles to

var user_1 = require("interfaces/user");

and if I add "../" beforehand it will compile without problems

Any ideas what I'm doing wrong here?

mercredi 30 août 2017

Perfomance Testing for a one class java application [duplicate]

This question already has an answer here:

I need to run perfomance testing for a simple java class which does some simple file read and write. I am new to perfomance testing and all the tools I am seeing are for web application. Which tool should I use.

My program has four methords doing same purpose and written in different logic I want to find which of the methord is more efficient

C# - Array of an different classes objectes

im sitting here with a bit problem. I have to create a program to solve tests. There's need to be one basic class, and 4 inheriting from it, all for other kind of tasks (some with 1 answer, some with numeric answer etc.). Also need an task collection, an array of different class objects. Array containts different tasks, then i have to draw 10 tasks from it. Is there any easier way to do the task collection that im doing?

     public class Program
{

    public class Task
    {
        protected string contents;
        protected int nr_pyt;
    };

    public class Task4Answ : Task
    {
        private
            char odp;
        public
        Task4Answ(string contents1, int nr, string odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1[0];
        }
    };

    public class TaskNumber : Task
    {
        private
            int odp;
        public
        TaskNumber(string contents1, int nr, int odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
        }
    };

    public class TaskString : Task
    {
        private
            string odp;
        public
        TaskString(string contents1, int nr, string odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
        }
    };

    public class TaskFewAnsw : Task
    {
        private
            string odp;
            string odpp;
            string odppp;
        public
        TaskFewAnsw(string contents1, int nr, string odp1,string odpp1, string odppp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
            odpp = odpp1;
            odppp = odppp1;
        }
    };

    public class TaskCollection
    {
        public Task[] collection;
        public TaskCollection()
        {
            collection = new Task[60];
            collection[0] = new Task4Answ("Ile jest por roku w Polsce? \na) 1 \nb) 2 \nc) 3 \nd) 4", 1, "d");
            collection[1] = new Task4Answ("Kto wygral tegoroczny Roland Garros? \na) Federer \nb) Djokovic \nc) Nadal \nd) Thiem", 1, "c");
            collection[2] = new Task4Answ("Kto jest premierem Polski? \na) Macierewicz \nb) Duda \nc) Kaczynski \nd) Szydlo", 1, "d");
            collection[3] = new Task4Answ("Ktore slowo kluczowe w C++ jest uzywane do deklarowania typu zmiennoprzecinkowego \na) Float \nb) Int \nc) Enum \nd) Struct", 1, "float");
            collection[4] = new Task4Answ("Ktory z podanych modyfikatorow dostepu pozwala na uzywanie zmiennych klasy bazowej w klasach pochodnych, a w innych klasach nie? \na) Domyslny \nb) Public \nc) Private \nd) Protected", 1, "d");
            collection[5] = new Task4Answ("Jakiego slowa kluczowego uzywamy do zwrocenia obiektu z funkcji? \na) Back \nb) Reversion \nc) Return \nd) Void", 1, "c");
            collection[6] = new Task4Answ("Ktory z samochodow nalezy do fabryki Volkswagenta? \na) Mondeo \nb) Passat \nc) Vectra \nd) Yaris", 1, "b");
            collection[7] = new Task4Answ("Ktory czlowiek na swiecie pierwszy stanal na ksiezycu? \na) Gagarin \nb) Lajka \nc) Armstrong \nd) Ahonen", 1, "c");
            collection[8] = new Task4Answ("Ktory z samochodow nalezy do fabryki Opla? \na) Mondeo \nb) Passat \nc) Vectra \nd) Yaris", 1, "c");
            collection[9] = new Task4Answ("Z iloma panstwami graniczy Polska? \na) 5 \nb) 6 \nc) 7 \nd) 8", 1, "c");
            collection[10] = new Task4Answ("Od ktorego roku Polska nalezy do Unii Europejskiej? \na) 2004 \nb) 2006 \nc) 2002 \nd) 2000", 1, "a");
            collection[11] = new Task4Answ("Kto jest obecnym prezesem PZPN? \na) Boniek \nb) Lato \nc) Listkiewicz \nd) Gmoch", 1, "a");
            collection[12] = new Task4Answ("Ktora z planet posiada charakterystyczny pierscien? \na) Neptun \nb) Jowisz \nc) Saturn \nd) Merkury", 1, "c");
            collection[13] = new Task4Answ("Za pomoca jakiego slowa kluczowego definiujemy szablony w C++? \na) Template \nb) Pattern \nc) Stencil \nd) Stereotype", 1, "a");
            collection[14] = new Task4Answ("Ktory z podanych jezykow posiada interfejsy? \na) C++ \nb) C \nc) C# \nd) HTML", 1, "c");
            collection[15] = new TaskNumber("Podaj date Bitwy Pod Grunwaldem", 15, 1410);
            collection[16] = new TaskNumber("Podaj maksymalna predkosc w terenie zabudowanym", 16, 50);
            collection[17] = new TaskNumber("W ktorym roku odbyly sie Mistrzostwa Europy w Pilce w Polsce?", 17, 2012);
            collection[18] = new TaskNumber("Ile bajtow pamieci zajmuje typ long w jezyku C++?", 18, 8);
            collection[19] = new TaskNumber("W ktorym roku w Polsce ogloszono stan wojenny?", 19, 1978);
            collection[20] = new TaskNumber("Po dodaniu dwoch zmiennych typu int, ile bajtow pamieci zajmie zmienna przechowujaca wynik tego dodawania?", 20, 4);
            collection[21] = new TaskNumber("Ile wynosi reszta z dzielenia liczby 60 przez liczbe 7?", 21, 4);
            collection[22] = new TaskNumber("Ile wynosi pierwiastek z liczby 49?", 22, 7);
            collection[23] = new TaskNumber("W ktorym roku rozpoczela sie II Wojna Swiatowa?", 23, 1939);
            collection[24] = new TaskNumber("W ktorym roku mial miejsce chrzest Polski?", 24, 966);
            collection[25] = new TaskNumber("Ile zlotych medali zdobyl Adam Malysz na Igrzyskach Olimpijskich?", 25, 0);
            collection[26] = new TaskNumber("Ile lat trwa kadencja prezydenta w Polscce", 26, 4);
            collection[27] = new TaskNumber("Jezeli na kazde 15 metrow kwadratowych przypada 6 wezy, ile wezy przypadnie na 90 metrow kwadratowych", 27, 36);
            collection[28] = new TaskNumber("W ktorym roku mial miejsce atak terrorystyczny na World Trade Center", 28, 2002);
            collection[29] = new TaskNumber("Jezeli 3 lata temu Ania ktora ma teraz 18lat byla 3 razy starsza od Tomka, to ile lat ma teraz Tomek", 29, 8);
            collection[30] = new TaskString("Podaj wzor chemiczny wody", 30, "H2O");
            collection[31] = new TaskString("Podaj gdzie urodzil sie Kopernik", 31, "Torun");
            collection[32] = new TaskString("Na jakim instrumencie gral Fryderyk Chopin", 32, "Fortepian");
            collection[33] = new TaskString("Podaj slowo kluczowe, ktorego uzywa sie do zwalniania pamieci w C++", 33, "Delete");
            collection[34] = new TaskString("Jak nazywa sie program w C# pelniacy role destruktora?", 34, "Garbage Collector");
            collection[35] = new TaskString("Jakiego slowa kluczowego uzywamy w C# do przyslaniania funkcji klasy bazowej?", 35, "Override");
            collection[36] = new TaskString("Jakie miasto jest stolica Kanady?", 36, "Ottawa");
            collection[37] = new TaskString("Jaka jest najwieksza wyspa na swiecie?", 37, "Grenlandia");
            collection[38] = new TaskString("Skad pochodzi sprinter Usain Bolt?", 38, "Jamajka");
            collection[39] = new TaskString("Jakiego slowa kluczowego uzywamy do deklarowania klas abstrakcyjnych w C#", 30, "Abstact");
            collection[40] = new TaskString("Jakiego slowa kluczowego uzywamy do deklarowania klas wirtualnych w C#", 40, "Virtual");
            collection[41] = new TaskString("Podaj slowo kluczowe, ktorego uzywa sie do deklarowania struktur w C# i C++", 41, "Struct");
            collection[42] = new TaskString("Jak nazywa sie dziedzina nauki, zajmujaca sie m.in kosmosem?", 42, "Astronomia");
        }

Then here i have to draw 10 tasks from this collection, but i can't just copy it from collection cause all are from different classes.

Is there a way to run "setup" only once for the entire suite of Python tests?

I know about the "setUp" and "setUpClass" test fixtures in Python but I have not been able to find a way to implement a setup just once for the entire suite of tests ... no matter if one test or one test class or all test classes are run.

Might anyone know a way to do this?

Robert

Mock request/post with mockito

I am having trouble covering the following function with tests (JUnit/Mockito), and can't find a way to mock the line response = getTarget(path).request().post(entity, Map.class);

Client client;

public Map<String, ?> postJson(String path, Map<String, ?> data){
    Map<String, ?> response = null;

    try {
        Entity<Map<String, ?>> entity = Entity.entity(data, MediaType.APPLICATION_JSON);
        response = getTarget(path).request().post(entity, Map.class);   
    } catch (Exception e) {
        LOG.error(e.toString());
    }

    return response;
}

public WebTarget getTarget(String path){
    return client.target(BASE_URI + path);
}

Anyone can give me an example/explain how I can go about covering this function with mockito ?

avocado-vt testing qcow2 imgae with error “ login timeout expired “

I use avocado-VT to test myself debian based .qcow2 file ,just obtained a login timeout expired error,but it work well when testing the default jeos image. it breaks in function wait_for_login, Besides . I notice that the VT use a ssh root@127.0.0.1 -p 5000 to connect to guest-os, I wonder if it is correct, or any settings need to be setted to make it go smootly? thank!

Mocks vs Stubs in PHPUnit

I know stubs verify state and the monks verify behavior

How can I make a mock in PHPUnit to verify the behavior of the methods? Phpunit does not have verification methods (verify()), And I do not know how to make a moks is PHPUnit.

In the documentation, to create a stub is well explained:

    // Create a stub for the SomeClass class.
    $stub = $this->createMock(SomeClass::class);

    // Configure the stub.
    $stub->method('doSomething')
         ->willReturn('foo');

    // Calling $stub->doSomething() will now return 'foo'.
    $this->assertEquals('foo', $stub->doSomething());

But in this case, I am verifying status, saying that return an answer.

How would be the example to create a mock and verify behavior?

Factory girl association self referencing the parent model

In my application an account can have a single owner (user) and multiple users.

In my tests I do this:

# account_factory_static.rb
FactoryGirl.define do
  factory :account do
    name 'demoaccount'
    association :owner, :factory => :user
  end
end

# user_factory_static.rb
FactoryGirl.define do
  factory :user do
    email 'demo@example.com'
    first_name 'Jon'
    last_name 'Doe'
    password 'password'
  end
end

and use them like below:

let(:account) { FactoryGirl.create(:account) }

The problem is that right nowaccount.users.count equals 0 because I have no way to do something like @account.users << @account.owner like I do in my controllers when a user signs up.

The question is how can I add the associated account's id to the account_id attribute of the user in FactoryGirl?

In other words how do you do it in FactoryGirl?

Thanks.

Selenium WebDriver Testing before Deployment

we want to integrate Selenium WebDriver-Tests in our Maven-Project. We do our deployment with Jenkins. Is it possible to execute the tests and deploy the application after the successful tests? I guess we need a Selenium Server for testing. I´m new in this topic and found not very much about the process (TEST the application BEFORE the deployment)

What are the requirements for that?

Are there any helpful links out there?

I hope some of you have a litte experience about that and could give me some helpful advice.

Thanks!

Is it possible to postpone the initialization of the test subject until the test case with EasyMock?

Is it possible to initialize the object to test not on declaration but in each test case? I can't initialize the object on declaration because the parameters passed to the constructor are part of the test cases. I would need something as:

  @TestSubject
  private ClassUnderTest classUnderTest;

  @Mock
  private Collaborator mock;

  @Test
  public void test12() {
    classUnderTest = new ClassUnderTest(1, 2);
    replay(mock);
    Integer result = classUnderTest.work(3, 4);
    // Assertions
  }

But if I do the above, Easymock complains:

java.lang.NullPointerException: Have you forgotten to instantiate classUnderTest?

I've taken a look at MockBuilder, but I don't see how it can help in this case.

Django tests broken when I have two database in settings

I have a Django (1.9.2) application with two databases (Postgres) in the settings.

And I have migrations with migrations.RunPython.

When I try to run the tests (manage.py test), migrations run twice breaking the tests. On the second execution, the database already updated to the latest version and the code called on the RunPython raise an exception.

Someone have some tip to solve this?

Thanks

Testing logic in Firebird database

I have a project with logic implemented in the database. At the moment, testing this logic also does not happen. Share the experience of real testing in triggers and stored procedures. May be, advise a framework or a literature that I can read. Database is Firebird.

How to store data in an array that is stored in a variable?

Following is my problem:

I am testing a system now, that has multiple ID's in every request. There are 2 ID's I want to store in an array and let them run again a response later.

Following is the Body I recieve

{
"id" = 1234;
"Name" = "Meier"
}

So, I store the ID normally with

var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", body.id);

with that I can store 1 ID in the variable, but can't put a second one in it. For that I would have to duplicate the request, set a second variable, change code everytime the needed cases are changed.

What I want to know now is: How can I store multiple ID's in a Environment Variable to compare them with a response at the end of the collection?

Laravel tests with sqlite doesn't create users table

I'm with problem with tests in Laravel. I don't know why the users table isn't be created, because all other tables are ok.

The database for tests is Sqlite running in :memory:

My PHP Unit configuration file (phpunit.xml)

      <php>
              <env name="APP_ENV" value="testing"/>
              <env name="DB_CONNECTION" value="sqlite"/>
              <env name="DB_DATABASE" value=":memory:"/>
              <env name="CACHE_DRIVER" value="array"/>
              <env name="SESSION_DRIVER" value="array"/>
              <env name="QUEUE_DRIVER" value="sync"/>
          </php>

Users Migration ( create_users_table )

      use Illuminate\Support\Facades\Schema;
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Database\Migrations\Migration;

      class CreateUsersTable extends Migration
      {
          /**
           * Run the migrations.
           *
           * @return void
           */
          public function up()
          {
              Schema::create('user', function (Blueprint $table) {

                  $table->increments('id');
                  $table->integer('status')->nullable()->default(1);
                  $table->string('name');
                  $table->string('email')->unique();
                  $table->string('password');
                  $table->string('sysid', 20)->nullable();
                  $table->string('avatar')->nullable();
                  $table->string('cpf', 18)->nullable();

                  $table->rememberToken();
                  $table->timestamps();
              });
          }

          /**
           * Reverse the migrations.
           *
           * @return void
           */
          public function down()
          {
              Schema::dropIfExists('user');
          }
      }

tests/Unit/RoleTest.php

    <?php

    namespace Tests\Unit;

    use Tests\TestCase;
    use Illuminate\Foundation\Testing\DatabaseMigrations;
    use Illuminate\Foundation\Testing\DatabaseTransactions;

    class RoleTest extends TestCase
    {

        use DatabaseMigrations;

        protected $role;
        protected $permission;


        public function setUp() {

            parent::setUp();
            $this->role = factory('App\Model\ACL\Role')->create();
            $this->permission = factory('App\Model\ACL\Permission')->create();
        }


        /** @test */
        public function a_role_has_permissions ()
        {

            $this->assertInstanceOf(
        'Illuminate\Database\Eloquent\Collection', $this->role->permissions
            );
        }

        /** @test */
        public function a_role_gives_permission_to ()
        {
            $permission = $this->role->givePermissionTo($this->permission);
            $this->assertInstanceOf('App\Model\ACL\Permission', $permission);

        }


        /** @test */
        public function a_role_has_permission ()
        {
            $permission = $this->role->givePermissionTo($this->permission);
            $this->assertTrue($this->role->hasPermission($this->permission));
        }


        /** @test */
        public function a_role_has_many_users ()
        {

            $this->assertInstanceOf(
                'Illuminate\Database\Eloquent\Collection', $this->role->users
            );

        }
    }

The tests are given the following errors:

    1) Tests\Unit\RoleTest::a_role_has_many_users
    Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: users (SQL: select "users".*, "role_user"."role_id" as "pivot_role_id", "role_user"."user_id" as "pivot_user_id" from "users" inner join "role_user" on "users"."id" = "role_user"."user_id" where "role_user"."role_id" = 1)


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

How do I test onSelect function in a table (Angular 2)?

Right now I am trying to test some components in my Angular 2 project. I've got a table, which is getting the whole content from a database. You can select one of these rows get to the onSelect() function.

<tbody>
  <tr *ngFor="let c of Contents" [class.selected]="c.content === selectedContent" (click)="onSelect(c.content)" >
     <td>  </td>
     <td> </td>
     <td> </td>
  </tr>
</tbody>

And the function onSelect():

onSelect(contents: Content): void {
    this.selectedContent = contents;
    var url =  configuration.baseURL + contents.content;
    this.detailsContent.update(url);
}

So, how do I test that onSelect is called, when I click on the first Content?

Microsoft Visual Studio Unit Test Doubts

I am using microsoft visual studio 2017 for my development. My project has lot of unit test cases written and working fine as well.

I have few doubts about unit test cases. It will be great if someone can answer my below questions.

  1. Which are the available unit test frameworks in microsoft?
  2. What is pex? Is it unit test framework.
  3. Is there any design pattern for unit test? (i.e. mock unit)
  4. Any example link for best unit test practice.

Overall, I want to redesign my unit test project which is in MSTest framework. Since i am developer, I don't have much knowledge about unit test.

docker image testing: file not found

I made a docker image and was trying to test it. The image seems fine if I check the version of the application, but can't find the file if I give a legitimate command:

| => docker run -ti http://ift.tt/2vDAvt4 fastqc --version

FastQC v0.11.4

| => docker run -ti http://ift.tt/2vDAvt4 fastqc /Users/jedi/Documents/raw_data/Sample1_PE_R1.fastq.gz

Skipping '/Users/jedi/Documents/raw_data/Sample1_PE_R1.fastq.gz' which didn't exist, or couldn't be read

I tried putting the filepath in quotes, but got the same result. What am I doing wrong? How should I be testing a docker image?

thanks!

Angular CLI - ng e2e throws error

I've just set up a new Angular 4 project using the Angular CLI. Just after creating it, I ran ng e2e and the sample end-to-end test executed perfectly. After this, I've added a subfolder inside the app folder called services, and generated a service inside that folder. Now, when I run ng e2e, it errors out with the following error:

[09:11:56] E/configParser - Error message: failed loading configuration file protractor.conf.js [09:11:56] E/configParser - Error: Cannot find module 'C:\Projects\new\test-project\src\app\services\protractor.conf.js

Any idea why this could be happening? I think I might need to prevent the e2e script from looking inside the services folder, but I'm not sure how to do that.

mardi 29 août 2017

Which are good testing tools for Website?

  1. http://ift.tt/2tu6kU9
  2. http://ift.tt/1RAk6Jx
  3. http://ift.tt/2vIevMK

Which of these tools are better for SQA testing (UI) on mobile devices, when it comes to cost effective and cloud environment ? or is there any other tool that is better than these three?

Really appreciate your quick and soft responses.

Can't run rspec when using Rails 5 and acts-as-taggable-on 4

Versions

  • Ruby: 2.3.3
  • Bundler: 1.14.6
  • Rails: 5.0.2
  • acts-as-taggable-on: 4.0.0

Gemfile

gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
gem 'acts-as-taggable-on', '~> 4.0'

Exception

When running rpsec, got these errors:

/Users/user/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.14.6/lib/bundler/runtime.rb:94:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'acts-as-taggable-on'. (Bundler::GemRequireError)
Gem Load Error is: uninitialized constant ActsAsTaggableOn::GenericParser

How to fix it?

Redux Testing unexpected Token error

I am running into an issue with a test_helper file that use to work perfectly fine. It is a project I am coming back to after a while. The error and file are below along with the package.json as I suspect it maybe the compiler causing the issue.

The Error

SyntaxError: /Users/mikewalters/Projects/video-
frontend/test/test_helper.js: Unexpected token (20:4)
18 | function renderComponent(ComponentClass, props = {}, state = {}) {
19 |   const componentInstance =  TestUtils.renderIntoDocument(
> 20 |     <Provider store={createStore(reducers, state)}>
|     ^
21 |       <ComponentClass {...props} />
22 |     </Provider>
23 |   );

The test_helperjs

import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
const $ = _$(window);

chaiJquery(chai, chai.util, $);

function renderComponent(ComponentClass, props = {}, state = {}) {
  const componentInstance =  TestUtils.renderIntoDocument(
    <Provider store={createStore(reducers, state)}>
      <ComponentClass {...props} />
    </Provider>
  );

  return $(ReactDOM.findDOMNode(componentInstance));
}

$.fn.simulate = function(eventName, value) {
  if (value) {
    this.val(value);
  }
  TestUtils.Simulate[eventName](this[0]);
};

export {renderComponent, expect};
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
const $ = _$(window);

chaiJquery(chai, chai.util, $);

function renderComponent(ComponentClass, props = {}, state = {}) {
  const componentInstance =  TestUtils.renderIntoDocument(
    <Provider store={createStore(reducers, state)}>
      <ComponentClass {...props} />
    </Provider>
  );

  return $(ReactDOM.findDOMNode(componentInstance));
}

$.fn.simulate = function(eventName, value) {
  if (value) {
    this.val(value);
  }
  TestUtils.Simulate[eventName](this[0]);
};

export {renderComponent, expect};

The package.json

"scripts": {
    "start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js",
    "test": "mocha -r mock-local-storage --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch",
    "coverage": "babel-node ./node_modules/.bin/isparta cover --include 'src/**/*.js*' _mocha"
  },

These test have worked before and the fact that it isnt even getting to the test lends me to believe it is something with the compiler or package that changed. But I haven't been able to find anything online about the issue.

Trouble launching chromedriver in Spock test

I have a Maven web project for which I'm trying to run a couple of simple Spock web UI tests under Eclipse with Selenium and Chromedriver. I can run each test class individually by clicking on it and selecting "Run As>Junit Test" if I add the following to the file's run configuration VM arguments:

-Dwebdriver.chrome.driver=/Users/mht/ChromeDriver/2.3.1/chromedriver

Obviously, this is the location of the Chromedriver on my system. Then I tried to set up a Maven build goal at the project level to run the tests. I click on the project name and select "Run Configurations>Maven Build" and create a "Verify" configuration to match the verify goal defined in my pom. In the "Goals, box I enter "verify" and on the JRE tab I also enter the above location for the chromedriver in the VM arguments box. When I run this goal, or on the command line type "mvn verify", I get the following error:

geb.driver.DriverCreationException: failed to create driver from callback 'script15040527017471153797989$_run_closure1@1046d517' at com.google.common.base.Preconditions.checkState(Preconditions.java:754) ...

This tells me the test can not locate the chromedriver. If I copy the chromedriver into the base directory of the project, the then the test will run using the verify goal or by typing "mvn verify" on the command line. Why isn't setting the chromedriver location not working at the maven goal level?

I don't think this really matters, but the build section of my pom is

<build>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.18</version>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <useFile>false</useFile>
                <includes>
                    <include>**/*Spec.java</include>
                </includes>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <executions>
                <execution>
                    <id>tomcat-run</id>
                    <goals>
                        <goal>run-war-only</goal>
                    </goals>
                    <phase>pre-integration-test</phase>
                    <configuration>
                        <port>9081</port>
                        <fork>true</fork>
                    </configuration>
                </execution>
                <execution>
                    <id>tomcat-shutdown</id>
                    <goals>
                        <goal>shutdown</goal>
                    </goals>
                    <phase>post-integration-test</phase>
                </execution>
            </executions>
        </plugin> 
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.4</version>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

Setup with ReturnsAsync, need to return passed in value but getting null

I need to mock my IVehicleRecordsRepository for some tests. So here's the repo interface:

public interface IVehicleRecordsRepository
{
    Task<VehicleRecord> StoreAsync(VehicleRecord veh, Guid? userId = null);
    //...
}

and now I try to mock it in the xUnit test so StoreMethod() should return the same value that was passed in as a parameter. Here's the test that tests this scenario:

[Fact]
public async Task ShouldGetValueFromMockedMethod()
{
    var mockRepo = new Mock<IVehicleRecordsRepository>();
    mockRepo
        .Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))
        .ReturnsAsync((VehicleRecord veh, Guid userId) => veh)
        // tried this too -> .Returns((VehicleRecord veh, Guid userId) => Task.FromResult(veh))
        ;

    VehicleRecord vr = new VehicleRecord(newVehicle, Guid.NewGuid());
    var testVeh = await mockRepo.Object.StoreAsync(vr);
    Assert.NotNull(testVeh); // ====> FAILS HERE
    Assert.AreEqual(vr, testVeh);
}

So, how can I get the same value I passed into StoreAsync() in return ?

Moq version: 4.7.99.0

Android Unit tests with multiple predefined varibales

Usually I develop using C# with the NUnit-Framework. With the help of it, several sets of Varibales can be easily tested, this is especially useful if you have functions with several configurations.

This is an example:

[TestCase("0", 1)]
[TestCase("1", 1)]
[TestCase("2", 1)]
public void UnitTestName(string input, int expected)
{
    //Arrange

    //Act

    //Assert
}

of course it would be even better if i could try several combinations, in C# this is achieved like

    public void UnitTestName(
      [Varibale("2", "1")] string input,
      [Varibale(2, 1)] int expected)
    {
        //Arrange

        //Act

        //Assert
    }

Thank you very much in advance!

How to test existence of parent object before testing value or child

What would be the best way to test for the existence of a deeply nested property using Jest. Trying to target the particular object I want will get me an undefined error because its parent object doesn't exist:

test('returns data from `server/index.js`', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data.els[4]).not.toBeNull() 
        // ^ TypeError: Cannot read property '4' of undefined
  })
})

Should I chain these in some way so I can first test for the existence of the object, then test for the existence of the inner object? The equivalent of doing something like this in an if-statement

if (obj && obj[4] && obj[4].hasOwnProperty('myProp')) {
  // pass
}

Or when doing multiple tests on one element like this, should there be separate tests?

test('returns data from `server/index.js`', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data).not.toBeNull() 
  })
})

test('data returned from `server/index.js` api contains my property', () => {
  const data = axios.get(httpObj)
     .then(data, => {
        expect(data.els[4]).not.toBeNull() 
  })
})

I have also tried:

const expected = {/* very large object */}
test('returns data from `server/index.js` and it contains an array containing the `expected` object', () => {
  expect(data.els[4]).toEqual(
    expect.objectContaining(expected)
  )
})

This works a bit? better, but requires me to have this very large object declared within the test file. This very deep comparison combined with just a static blob of data in my test file feels brittle to me. Is there a more canonical way than what I've tried

Moq - setup with ReturnsAsync, returning passed in value and get null

ok, I need to mock my IVehicleRecordsRepository to test ASP.NET Core 2.0 MVC Controller. The repo interface:

public interface IVehicleRecordsRepository { Task<VehicleRecord> StoreAsync(VehicleRecord veh, Guid? userId = null); ... }

and here's how I try to mock it in the xUnit test:

    [Fact]
        public async Task Added_Post()
        {
            var mockRepo = new Mock<IVehicleRecordsRepository>();
            mockRepo
                .Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))
                .ReturnsAsync((VehicleRecord veh, Guid userId) => veh)
                // tried this too -> .Returns((VehicleRecord veh, Guid userId) => Task.FromResult(veh))
                ;
[...]
            VehicleRecord vr = new VehicleRecord(newVehicle, Guid.NewGuid());
            var testVeh = await mockRepo.Object.StoreAsync(vr);
            Assert.NotNull(testVeh); // ====> FAILS
       }

So, how can I get in return the same value I passed into StoreAsync() ?

Where can I download various versions of MS Excel for free for testing purposes?

I am making a web app with a "Download as CSV" feature. I was hoping people using MS Excel would be able to open my CSV files by double-clicking on them, but it seems most versions of Excel don't handle utf-8 CSV files correctly out of the box (all other spreadsheet programs I've tried can do this, only MS Excel is problematic). So my plan B is to change the feature to "Export to Excel", which will offer a xlsx file for download instead of a csv file. This seems to work (there is no utf-8 bug for xlsx files) in the versions of Excel that I have tried so far. Of course, I'd like to verify on a few different versions of Excel on a few different versions of Windows and also on Mac. On http://modern.ie, I found a few virtual machines I can download with Win-7, Win81 and Win10. This is good but now I need a place to get all these different versions of MS Excel for free.

Where can I find the most commonly used versions of MS Excel for free for testing purposes?

Obviously I'm looking for a 100% legal solution to my problem here, illegal download links won't get a checkmark or any up-votes from me.

How do you all usually make sure your xlsx files will be correctly opened in all versions of MS Excel?

Jmeter - wait for a specific response

our application is testing file upload and I'm curious if I can make Jmeter wait for a specific response and then report collective time.

What I have now is:

whileLoop()
  -- HTTP Sampler
  -- JSON Extractor

JSON Extracor pulls out a specific field and if it's not null then the loop stops.

The problem is that JMeter doesn't report response time as a sum of all the responses (response times) it had to make and that is what I'm looking for. Is there a way to implement this?

I am looking for an automated tool to test a large web app for HTML5 compliance

My goal is to test a 1000+ page web app containing .aspx and .ascx for HTML5 compliance. As it currently complies only to HTML4 and the client would like to upgrade the product.

I'm seeking a solution that's automated, would be capable of checking not just HTML elements but also the elements attributes, and can also check style sheets page by page and deliver a report. We also need something that could make sure things like screen readers and other 3rd party UI like Kendo won't break during the upgrade.

Right now I'm looking at Telerik Test Studio and Selenium. They look like good options, but I wanted to make sure I wasn't overlooking other viable choices or caveats.

C# Find all tests in a solution

Are there any technologies I can use to find all tests in a solution that are annotated as a test ([TestMethod], [Fact], [Theory]...)?

Context: I am quite new to all this but attempting to iron out a continuous deployment strategy. I want to find and run all tests in a solution during/following a release process. These are not build dependent unit tests, these are part of end to end solution tests.

Please let me know if my thinking is away from the right track.

Using PyTest with a GUI in a Q&A fashion

Originally, I had a set of batch scripts which would change some files, open the gui, the user would confirm the effects of the change visually and then close the GUI. The test code could would then make changes and reopen the GUI for re inspection.

Is there a method to use PyTest in a similar way?

So the test function would make the changes, open the gui, ask the user if the changes are correct, if so the user would say yes and the test would pass. Otherwise it would fail and then move onto the next test.

Where should the testng.xml file reside in a Java project in Netbeans IDE?

I am studying the TestNG framework with the purpose of using it more specifically with threads, since from what I saw in some websites, it is more efficient in this context (I accept suggestions of other possibilities), but it was not very clear to me where the ".xml" file in question should be inside the project so that I can run it through the IDE itself (in this case Netbeans IDE). Every help is welcome.

Check if Elasticsearch has finished indexing

Is there a way to check if Elasticsearch has finished processing my request?
I want to perform integration tests for my application checking if a record can be found after insertion. For example if I make a following request:

POST /_all/_bulk
{  
   "update":{  
      "_id":419,
      "_index":"popc",
      "_type":"offers"
   }
}
{  
   "doc":{  
      "id":"419",
      "author":"foo bar",
      "number":"642-00419"
   },
   "doc_as_upsert":true
}

And I check immediately, the test fails, because it takes some time for Elasticsearch to complete my request.
If I sleep for 1 second before the assertion it works most of the time, but not always.
I could extend the sleep time to eg. 3 seconds, but it makes the tests very slow, hence my question.

I have tried using cat pending tasks and pending cluster tasks endpoints, but the responses are always empty.

If any of this is relevant, I'm using Elasticsearch 5.4, Laravel Scout 3.0.5 and tamayo/laravel-scout-elastic 3.0.3

Java Listener Error: Exception in thread "main" java.lang.Error: Unresolved compilation problems:

I saw a video tutorial where the code works. Its about to Programm a console. In The video this code works:

    package konsole;

    import java.util.Scanner;
    import console.Console;
    import konsole.commands.Echo;
    import console.ConsoleCommand;

public class Konsole {
public static final Console c = new Console();

public static void main(String[] args) {
    final Scanner s = new Scanner(System.in);
    c.registerCommand(new Echo());
    c.addListener(new ConsoleListener() {
        public void onCommand(ConsoleCommand cmd, String cmdname, String[] args) {
            Konsole.c.writeInfo("Command executed:" + cmdname);
        }
    });

    while(true) {
        System.out.print("consoleuser>");
        String in = s.nextLine();
        if(in.isEmpty() == false) {
            String[] scmd = in.split(" ");
            String cmdname = scmd[0];
            String[] cmdargs = new String[scmd.length - 1];
            for (int i = 1; i < scmd.length; i++) {
                cmdargs[i - 1] = scmd[i]; 
            }
            c.executeCommand(cmdname, cmdargs);
        } else {
            continue;
        }
    }
}

}

I get the Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method addListener(ConsoleListener) in the type Console is not applicable for the arguments (new ConsoleListener(){})ConsoleListener cannot be resolved to a type

Silex - Listeners not executed when dispatching from a test

I've written a class to load some fixtures in DB each time a functional test is executed. These fixtures are created calling a service which after creating some data, dispatches an event so that other data is created from listeners. The problem is that the listeners are not executed when loading the fixtures.

Do I need to mock all events dispatches to make the listeners to be executed? I mean, dispatching manually the desired events from the fixtures load method? Why aren't listeners executed?

abstract class APITest extends WebTestCase
{
    protected $app;

    public function createApplication()
    {
        $app = require __DIR__ . '/../../app.php';
        require __DIR__ . '/../../controllers.php';
        require __DIR__ . '/../../routing.php';
        $app['debug'] = true;
        unset($app['exception_handler']);
        $app['session.test'] = true;

        return $app;
    }

    public function setUp()
    {
        parent::setUp();
        /* @var $app Application */
        $app = $this->app;
        $fixtures = new TestingFixtures($app);
        $fixtures->load();
    }

    ...
}

Set sprint board for Test & Feedback extension

How do you set the sprint board which bugs & tasks are assigned to with the Test & Feedback extension?

We've installed and connected the Test & Feedback extension for Chrome on our Product Owner's laptop so that he can log bugs; but whenever he creates a bug or task it is always assigned to the sprint we were in when we set him up, not the current sprint. How does he ensure that his bug is assigned to the current sprint or, preferably, the backlog?

lundi 28 août 2017

Is this variation of Arrange-Act-Assertion for automated UI testing an anti-pattern

I am writing selenium tests to do regression tests against end-to-end business processes. Typically, the scenarios have been created by manual testers, and have test steps and expected outcomes.

My pattern becomes Arrange, Act-Assert, [ ... Act-Assert] potentially with another Assert at the end.

Whilst I could break these into many smaller tests, the steps don't typically make sense out of context, e.g. going through a wizard/multi-step process.

My tests have a fluent API. Verify (extension method) calls Assert.IsTrue on the condition, and my tests end up looking something like (this very contrived example):

PageModelFactory.Get<StartPage>() 
  .Login(...).Verify(x => x.IsLoggedIn)
  .GoToUserSettings()
  .SetAlternateEmailAddress(...).Verify(x => x.EmailAddressValidIndicatorDisplayed)
  .SaveChanges().Verify(x => x.SuccessMessageDisplayed)

The benefits I can see are that the tests align closely with the style that "testers" write the regression tests in, and it will fail-fast if an expected result for a step fails.

The downsides are that I will have to do a bit more to determine exactly what the cause of error was (which I could wrap into the Verify method), and that it moves away from the A-A-A pattern.

Are there any other benefits/concerns with this approach that would affirm my usage of it, or point me back towards pure A-A-A?

dynamically add test cases and suite in Mocha

var Mocha = require('mocha');
var Test = Mocha.Test;
var Suite = Mocha.Suite;

var mocha = new Mocha();
var suite = Suite.create(mocha.suite, 'Search Box');

suite.addTest(new Test('I\'m a dynamic test', function () {
    console.log("haha");
    browser.end();
}));

I assume addTest is for it - test cases, how do I add a describe inside suite

Is there official documentation for dynamic test that I can refer to?

service.$inject generates error in Jasmine test

I have this code:

app.module.js

'use strict';

angular.module('app', ['ui.testing.Modal']);

app.module.js

    'use strict';

angular.module('app').service('AppService', AppService);

AppService.$inject = ['ui.testing.Modal'];

function AppService() {

this.show = function () {
    return "Hello Service!";
}

}

app.service.spec.js

describe('blablabla', function(){

var service;

beforeEach(module('app', 'ui.testing.Modal'));

beforeEach(inject(function(_AppService_) {
    service = _AppService_;
}));

it('blablabla', function() {
    expect(service.show()).toBe("Hello Service!");
});

});

Running the tests...

Error: [$injector:unpr] Unknown provider: ui.components.ModalProvider <- ui.components.Modal <- AppService http://ift.tt/2xsdhr9$injector/unpr?p0=ui.components.ModalProvider%20%3C-%20ui.components.Modal%20%3C-%20AppService in bower_components/angular/angular.js (line 4826) bower_components/angular/angular.js:4826:86 getService@bower_components/angular/angular.js:4981:39

Any ideas? :(

How to unit test methods that construct the string?

I have method which construct the string from List. I want to test the method with Unit Test Method. What's the good idea to test that method? I need to use data base to get matchList. I don't know how to use mock object to do that, please help.

public class File_IO

{
    private string _rootDirectory;
    private string _taskName;

    private File_IO()
    {

    }

    public File_IO(string rootDirectory, string taskName)
    {
        _rootDirectory = rootDirectory;
        _taskName = taskName;

    }

    public string RootDir
    {
        get { return _rootDirectory; }
    }

    public string TaskName
    {
        get { return _taskName; }
    }

    public string constructString()
    {
        string result = string.Empty;
        string pipe = "|";
        StringBuilder stringBuilder = new StringBuilder();
        bool isFirst = true;

        IList matchList = new List<string> { "*.Ext","*.ext" };

        // Iterate over the results and construct the string.
        foreach (var item in matchList)
        {
            if (!isFirst)
            {
                stringBuilder.Append(pipe);
            }

            isFirst = false;
            stringBuilder.Append(item);
        }

        result = stringBuilder.ToString();
        return result;
    }

}

SinonJS calledOnce or callCount issue for a inner object function

Running tests with SinonJS 1.10.x (sorry, can't update the version) I'm facing the following issue

Error: PhantomJS:expected 0 to equal 1near

What's wrong with the test?

    var spyRequester = sinon.spy(util._requesterHandler, '_doCreate');

    var result1 = util._requesterHandler.createRequesterIfNotExists(url);
    var result2 = util._requesterHandler.createRequesterIfNotExists(url);

    assert.equal(spyRequester.callCount, 1); // assertion error

And requestHandler API is

    requesterHandler = {
        createRequesterSubscribers: function createRequesterSubscribers(url) {...},
        createRequesterIfNotExists: function createRequesterIfNotExists(url, options) {...}
        _doCreate: doCreate
    }

the piece of code which calls doCreate inside createRequesterIfNotExists

    createRequesterIfNotExists: function createRequesterIfNotExists(url, options) {

      var shouldCreate = typeof requesterMap[url] === 'undefined';
      var optionsArray = (requesterMap[url] || {}).optionsArray || [];
      optionsArray.push(options);

      if (shouldCreate) {
        requesterMap[url] = doCreate(url, optionsArray); // call doCreate
      }

What to Assert in E2E Test Cases - Best Practices

I recently transferred to an existing (but new) project, still in beta, that already has a fair amount of unit, integration, and system / e2e tests. Presently, a large portion of integration and system tests are asserting equality between an expected JSON payload and the actual JSON payload.

Considering the fast moving nature of this project (and that it's in beta), changes are often causing many tests to flip red, as they're changing the JSON payload. It seems redundant to frequently change expected JSON payload to match the new output, but I'll do it without complaining if I know that's the ideal way to test.

My question (TLDR): In the case of a JSON API, if I am only testing "Happy Path" e2e / system test scenarios; what would my ideal assertion statement? Am I looking to test the entire payload against an expected payload or would it make more sense to compare status codes, and maybe some high level JSON keys?

How do I test generators for delegated properties?

In my current project there is a class that will later on be implemented by many others. This class provides some generators for delegated properties.

abstract class BaseClass {
    protected val delegated1 get() = new Delegated1Impl()
    protected val delegated2 get() = new Delegated2Impl()
    ...
}

This base class can be used this way:

class Example : BaseClass() {
    var field1 by delegated1
    var field2 by delegated2
}

Now I want to test these delegated generators. Some of them contain logic which I want to test, but for now I only want to know that everytime they are called they return a new instance.

Now my question is: how can I test these generators?
The generators are not visible outside of extending classes so I cannot simply create an instance of it and call these methods.

@Test
fun `delegated1 should always return a new instance`() {
    val target = object: BaseClass()

    val first = target.delegated1    // This does not work since it is protected
    val second = target.delegated1

    assertTrue(first !== second)
}

How to write correctness test for concurrent class?(that 2 actions is not executed in parallel )

I've got task to write my custom executor service.

I should work almost as usual but 2 tasks with same key(field of task) should not execute in parallel. I've wrote the code and I am sure that it should work correct.

But I need to write test. I haven't encountered the with test like this.

I could not google something useful about this.

Please, share your experience.

Angular2 integration testing, how to test a child component that calls its parent's method in its template

I have a child component that has events in its template such as:

child.html 
<a (click)="parent.onClick()"></a>

Normally when I go about testing events in angular2, I would do something like:

 child.spec.ts
      it('', () => {
            let menu = fixture.debugElement.nativeElement.querySelector('a');
            menu.click();
            fixture.detectChanges();
            expect(something)
        });

with setup that looks something like:

 BeforeEach(async(() => {
                TestBed.configureTestingModule({
                    declarations: [ChildComponent]
                    providers: [ParentComponent]
                    })
                    .compileComponents();

But in the case of the calling the parent's method in the child's template, the .click(); never calls the parent's method. If I move the logic into the child component, the test will of course work, however, I was wondering if there was way to test the click event as it is currently setup.

Getting error when executing smartjmx through jmeter for ecommerce site

I have recorded the smart jmx of ecommerce site with blaze meter but when i'm using the same file in jmeter getting error's. It's working fine till add to cart, when it processing the customer information throw exceptions.

H2 db for SpringBoot tests

I am using Postgres database and I want to use H2 database for tests. The problem is when I'm creating new object in database, it seems that H2 is not used at all in test.

Test class:

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest
 @AutoConfigureMockMvc
 @WithMockUser(roles = "ADMIN")
 @ActiveProfiles("test")
 public class CompanyTests {

@SpyBean
private CompanyService companyServiceMock;

@Autowired
private MockMvc mockMvc;

@Autowired
EntityManager entityManager;

@Test
@Transactional
public void testaaaa() {
    entityManager.persist(new Company("nnnn", new Address()));
    List<Company> all = companyServiceMock.findAll();
    all.forEach(company -> System.out.println(company.getName()));
}

application.properties:

 spring.datasource.driverClassName=org.postgresql.Driver
 spring.datasource.url=jdbc:postgresql://localhost:5432/EDI
 spring.datasource.username=postgres
 spring.datasource.password=password
 spring.datasource.platform=postgresql
 spring.datasource.initialize=true
 spring.datasource.continue-on-error=true
 spring.jackson.serialization.fail-on-empty-beans=false

 spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
 spring.jpa.generate-ddl=true
 spring.jpa.show-sql=true
 spring.jpa.hibernate.ddl-auto=create

application-test.properties:

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-        
1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

And when I use findAll() in my test, it lists all companies from postgresql and new which is created by entityManager.

Mock child components - React Native + Jest

I've been struggling with this problem for a while.. I have a ListView component with a set of ListItem nested components. I'm trying to mock the ListItem component but it seems it doesn't because the resulting snapshot is always the same.

Can you please tell me what I'm doing wrong here? Here's the code:

ListView

import React, { Component } from 'react';
import { ListView } from 'react-native';
import { connect } from 'react-redux';
import ListItem from './ListItem';

export class LibraryList extends Component {
  componentWillMount() {
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
    });

    this.dataSource = ds.cloneWithRows(this.props.libraries); 
  }

  renderRow(library) {
    return <ListItem library={library} />;
  }

  render() {
    return (
      <ListView
        dataSource={this.dataSource}
        renderRow={this.renderRow}
      />
    ); 
  }
}

const mapStateToProps = state => {
  return {
    libraries: state.libraries,
  };
};

export default connect(mapStateToProps)(LibraryList);

ListItem

import React, { Component } from 'react';
import { 
  Text,
  View,
  TouchableWithoutFeedback,
  LayoutAnimation
} from 'react-native';
import { connect } from 'react-redux';
import { CardSection } from './common'; 
import * as actions from './../actions';

class ListItem extends Component {

  componentWillUpdate() {
    LayoutAnimation.spring();
  }

  renderDescription() {
    const { library, expanded } = this.props;

    if (expanded) {
      return (
        <CardSection>
          <Text style=>
            {library.description}
          </Text>
        </CardSection>
      );
    }
  }

  render() {
    const { titleStyle } = styles;
    const { library, selectLibrary } = this.props;

    return (
      <TouchableWithoutFeedback
        onPress={() => selectLibrary(library.id)}
      >
        <View>
          <CardSection>
            <Text style={titleStyle}>
              {library.title}
            </Text>
          </CardSection>
          {this.renderDescription()}
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15,
  },
};

const mapStateToProps = (state, ownProps) => {
  const expanded = state.selectedLibraryId === ownProps.library.id;

  return {
    expanded,
  };
};

export default connect(mapStateToProps, actions)(ListItem);

LibraryList.test

import React from 'react';
import renderer from 'react-test-renderer';
import configureStore from 'redux-mock-store';
import LibraryList from './../src/components/LibraryList';

describe('Library list component', () => {
  const middlewares = [];
  const mockStore = configureStore(middlewares);

  it('must render a list of libraries', () => {
    jest.mock('../src/components/ListItem', () => 'ListItem');

    const initialState = {
      libraries: [
        {
          id: 0,
          title: 'Webpack',
          description: 'Webpack is a module bundler...',
        },
      ],
    };

    const tree = renderer.create(
      <LibraryList store={mockStore(initialState)} />
    ).toJSON();

    expect(tree).toMatchSnapshot();
  });
});

Is there any javascript/nodejs framework that generates unit tests? [on hold]

As an internship project I am working on a node.js module that generates basic tests using a test runner like mocha for any given js file that contains functions, currently I'm tasked to find frameworks/modules that do the same thing to try and analyse how they work, unfortunatly I can't find any.

Testing branch assignment in Perl for SUPER:: methods

I am about to finish to study the Intermediate Perl book.

In chapter 18 Object Destruction is introduced the following DESTROY method definition:

# lib/Animal.pm
package Animal {
  # ...
  sub DESTROY {
    my $self = shift;
    if ($self->{temp_filename}){
      my $fh = $self->{temp_fh};
      close $fh;
      unlink $self->{temp_filename};
    }
    print '[', $self->name, " has died.]\n";
  }
# ...
}

# lib/Horse.pm
package Horse {
  use parent qw(Animal)
  # ...
  sub DESTROY {
    my $self = shift;
    $self->SUPER::DESTROY if $self->can( 'SUPER::DESTROY' );
    print "[", $self->name, " has gone off to the glue factory.]\n";
  }
# ...
}

After a few unsuccessfully attempt, I wrote this test based on this answer:

# t/Horse.t
#!perl -T

use strict;
use warnings;
use Test::More tests => 6;
use Test::Output;
# some other tests

# test DESTROY() when SUPER::DESTROY is not defined;
{
  my $tv_horse = Horse->named('Mr. Ed');
  stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has died.]\n[Mr. Ed has gone off to the glue factory.]\n",
      'Horse DESTROY() when SUPER::DESTROY is defined');
}

{
  my $tv_horse = Horse->named('Mr. Ed');
  sub Animal::DESTROY { undef }
  stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has gone off to the glue factory.]\n",
      'Horse DESTROY() when SUPER::DESTROY is not defined');
}

I cannot test the output correctly for both cases since the method redefinition sub Animal::DESTROY { undef } is affecting also the test in the previous block.

Do you know any way to ensure the method redefinition to work as expected?

Thanks

Using Jest --testNamePattern=

How to use Facebook Jest --testNamePattern= or -t option in package.json

jest -t /.*flow.spec.js$/ or jest -t='.*flow.spec.js$'

Nothing works!

dimanche 27 août 2017

Run an XCUI test on an already built app in macOS?

I have built a suite of XCUI tests for my macOS application. Currently when I run the tests, it first builds the application, and then runs the UI tests using the newly built .app file. We currently run a nightly build already, which is run through a series of existing XC Tests. Rather than building the app again, I would like to point my XCUI tests to the already built app (created during the nightly build), and then run the UI tests on that app.

Any ideas?

Scala speed- Finding Primes example

I was looking at prime numbers with scala. I used the following code to check if a number n is prime.

(2 until n) forall(d=>n%d!=0)

I checked how fast scala will return true for the prime number 179426549.

(2 until 179426549L.toInt) forall(d=>179426549L%d!=0) res22: Boolean = true

Then I tried an even bigger number 32416190071 to see how long it will take to return true for this larger prime.

(2 until 32416190071L.toInt) forall(d=>32416190071L%d!=0) res23: Boolean = true

To my surprise, a return value of true came back for the larger prime much faster. Why is it that the larger number returned a true so much faster?

Testing masstransit consumer

I am trying to test masstransit consumer my consumer look like this:

public class FilePolicyEvaluationConsumer : IFilePolicyEvaluationConsumer
{
    public readonly IFilePolicyEvaluationCore _filePolicyEvaluationCore;
    public readonly IRepositoryClient _repositoryClient;
    public readonly IFPRepository _fPRepository;

    public FilePolicyEvaluationConsumer()
    {

    }

    public FilePolicyEvaluationConsumer(IFilePolicyEvaluationCore filePolicyEvaluationCore, IRepositoryClient repositoryClient, IFPRepository fPRepository)
    {
        _filePolicyEvaluationCore = filePolicyEvaluationCore;
        _repositoryClient = repositoryClient;
        _fPRepository = fPRepository;
    }

    public  Task Consume(ConsumeContext<InvokePolicyOnFileMessage> context)
    {
        return Task.Run( async () => {
            Guid fileId = context.Message.FileId;
            FileMetadata fileMetaData = await  _repositoryClient.GetFileMetadata(fileId);
            _filePolicyEvaluationCore.Run(fileMetaData, context.Message.CorrelationId);
        });

    }

but when i configure the test like this

_harness = new InMemoryTestHarness();
        FilePolicyEvaluationConsumer filePolicy = new FilePolicyEvaluationConsumer(); 
        _consumer = _harness.Consumer<FilePolicyEvaluationConsumer>();


        await _harness.Start();
        await _harness.InputQueueSendEndpoint.Send(message1);

when i enter in the test to consumer all objects _filePolicyEvaluationCore,_repositoryClient,_fPRepository in the consumer are null, how can i inject to this objects?

How do I handle api testing in a backend project?

I've just learned the basics of express/backend and am attempting to make a backend playground for myself. I'm using an Angular-cli project for my front end and I was wondering how I should handle testing the api calls.

I know I can write karma test in the the front-end project to make http request for testing, although I feel like it seems contradictory to have the backend workflow also require the front-end and mess with their project. My mindset is that we do this to keep their workflow separate although I'm looking for a second opinion to be sure about this.

Can anyone confirm if working on the client side project is the way I should be doing my test or if it really should be handled in the backend project. What is the proper way to test backend api and what resources should I use?

What is the need of uploading CSV file for performance testing in blazemeter?

I am new in Testing world and just started working on performance and load testing, I just want to know that while we record script in Blazemeter and upload a jmx file for test then why we upload a CSV file with it and What data we need to enter in that CSV file. pls help. Thank you

samedi 26 août 2017

How to debug es6 tests with babel-jest and node inspector

I have no idea how to generate the source maps to debug jest tests on the node inspector right now I am using this command but is generating transpiled code:

node --debug-brk ./node_modules/.bin/jest --runInBand

Multiple binomial test fro two tables (success and total)

Multiple binomial test from success and total table.

binom.test(x, n, p = 0.5, alternative = c("two.sided", "less", "greater"), conf.level = 0.95)

I am really a newbie to this list and R. So please let me know if this inappropriate. I am trying to have a large number of binomial tests made in one shot. From raw data I have managed to create two tables (same number of rows and columns): one table (s) with class code and successes (right answer in a students exam) in different questions (one each column), so these are x-values of the binomial test and one table (t) with with class code the totals number of valid attempts for each question, so these are the p-values of the binomial test So basically I have in the same position in the two tables the two input values for the binomial test. I also have a table (one row) with the value of the probability (not 0.5!).

What is a good way to obtain a table with a true (1)/ false (0) value for hypothesis rejection for all these tests? Thanks a lot. Mirko

Table would look like (data just example)

Table s Group1 11 12 13 41 42 23 24 Group2 9 11 11 39 50 29 32 Group3 14 15 18 36 44 32 21

Table t Group1 45 44 45 44 45 43 45 Group2 32 33 31 33 31 33 33 Group3 45 46 48 44 54 43 23

P Vector 0.31 0.42 0.5 0.55 0.45 0.34 0.37

Kotlintest interceptor and lateinit vars

I have some testcases that share a common setup. They all need two fields which can be initialized in the same way. So I thought I can extract them into lateinit var fields and create them in an test-case-interceptor.
But when I try to access them in my testcases they always throw an exception because they are not initialized.
Is there a way to create the fields before every testcase?

Here is my code so far:

class ElasticsearchFieldImplTest : WordSpec() {

    // These 2 are needed for every test
    lateinit var mockDocument: ElasticsearchDocument
    lateinit var mockProperty: KProperty<*>

    override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) {
        // Before Each
        mockDocument = mock()
        mockProperty = mock {
            on {name} doReturn Gen.string().generate()
        }

        // Execute Test
        test()

        // After Each
    }

    init {
        "ElasticsearchFields" should {
            "behave like normal var properties" {
                val target = ElasticsearchFieldImpl<Any>()
                // Here the exception is thrown
                target.getValue(mockDocument, mockProperty) shouldBe null

                val testValue = Gen.string().generate()
                target.setValue(mockDocument, mockProperty, testValue)
                target.getValue(mockDocument, mockProperty) shouldBe testValue
            }
        }
    }
}

When I step through it with a debugger and set a breakpoint in the interceptTestCase methods I see that it is executed before the test and that the properties are initialized. Then I step forward to the test and in it the properties are not initialized anymore.

A way to test javascript methods

Is there any way to compare execution time of two methods?

For example I wonder which method is faster: querySelector() or getElementById(). Theoretically, I guess, time should be the same. But what if i want to check it in practice? Is any way to execute first method and check how much time it took, next doing the same with second method, and then to compare two results?

Jmeter:- want to login one lack users

I have a project and need to test lacks of users in jmeter but the problem I am facing is How to login lacks of users, it will be tedious for me to enter their data manually and the token. Can we remove or bypass the session id/token? So I won't need to input it manually. Is there any simple way to login lacks of user so i can test the load and stress testing. Or is there any other open source tool in which i test this?

Please reply me ASAP.

Thank you in advance.

Django/Testing: How do I populate the initial DB data when functional testing against staging server

I'm trying to run functional test for a Django webapp. The test is for a step in the middle of a process, so it requires the user to already have some data in the DB.

When I'm testing on my local PC, I use LiveServerTestCase to spin up the server and interact with it through Selenium, generating the data in the setUp function using model code from the concerned app.

When I'm testing against the staging server however, and I interact with it through Selenium on my local PC, the setUp code does nothing since it's running on my local PC.

My questions: 1) is it best practice to use model code to initialize a functional test (since it's supposed to be blackbox)? 2) how would I populate the DB when running against the staging server?

Xcode test to check files Target Membership

Let's say that I have an app with two targets: the app itself (1) and a today widget (2).

These two share some files/data (json files, or whatever) stored in the app bundle.

These files/data have to have Target Membership on both the app AND the today widget (to be accessible on both).

How can I create a Xcode XCTest that checks if the two target memberships have been setup?

vendredi 25 août 2017

Delayed dynamic test creation

I have a large CSV file that contains inputs and expected outputs for a complex calculation. I would like to use this file as the basis for tests of my calculator written in Node. However, it seems that frameworks like Mocha and Vows expect tests to be output synchronously, not asynchronously, after a CSV file has been read and parsed.

I could work around this by converting the CSV to JSON and including it in my test file, but I would rather use the authoritative CSV file as is, and anyway I'm just curious how to handle this situation. Thanks.

Basic approach now (using csvtojson):

    const cases = [];
    csv()
        .fromFile('../testdata/test.csv')
        .on('json', (rowObj) => {
           // convert columns to inputs and expected
           cases.push(inputs: inputs, expected: expected);
        })
        .on('end', () => {
           describe('Test cases', function() {
              cases.forEach((test) => {
                 it(`${dynamicCaseName}`, () => {
                   // do our calculation
                   assert.equals(ours, test.theirs);
                 });
              });
            });
        });

How do I verify and assert if an animation is playing after clicking a button in XCUITest?

I can't seem to find any information when it comes to animation testing on XCUITest. The scenario that I am testing is that:

When a button is pressed Then animation will be displayed on the icon

How do I do this?

Wanting to get rid of the Test Hub in TFS and integrate with Test Rail

Just wondering if there is a way to integrate TFS with TestRail to replace(get rid of entirely) the Test Hub within TFS to use TestRail to record Test Plans? My concern with removing the Test Hub, would be if Test Rail can still reference IDs in Bug and Stories within TFS and vice versa?

Systematic Concurrency Testing

Using Visual Studio 2015 (or later) and .Net Framework 4.5 (or later), how does one go about performing systematic concurrency testing?

I also prefer XUnit as my unit testing framework, FWIW.

C# - Program for task tests

im sitting here with a bit problem. I have to create a program to solve tests. There's need to be one basic class, and 4 inheriting from it, all for other kind of tasks (some with 1 answer, some with numeric answer etc.). Also need an task collection, an array of different class objects. Array containts different tasks, then i have to draw 10 tasks from it. Is there any easier way to do the task collection that im doing?

     public class Program
{

    public class Task
    {
        protected string contents;
        protected int nr_pyt;
    };

    public class Task4Answ : Task
    {
        private
            char odp;
        public
        Task4Answ(string contents1, int nr, string odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1[0];
        }
    };

    public class TaskNumber : Task
    {
        private
            int odp;
        public
        TaskNumber(string contents1, int nr, int odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
        }
    };

    public class TaskString : Task
    {
        private
            string odp;
        public
        TaskString(string contents1, int nr, string odp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
        }
    };

    public class TaskFewAnsw : Task
    {
        private
            string odp;
            string odpp;
            string odppp;
        public
        TaskFewAnsw(string contents1, int nr, string odp1,string odpp1, string odppp1)
        {
            contents = contents1;
            nr_pyt = nr;
            odp = odp1;
            odpp = odpp1;
            odppp = odppp1;
        }
    };

    public class TaskCollection
    {
        public Task[] collection;
        public TaskCollection()
        {
            collection = new Task[60];
            collection[0] = new Task4Answ("Ile jest por roku w Polsce? \na) 1 \nb) 2 \nc) 3 \nd) 4", 1, "d");
            collection[1] = new Task4Answ("Kto wygral tegoroczny Roland Garros? \na) Federer \nb) Djokovic \nc) Nadal \nd) Thiem", 1, "c");
            collection[2] = new Task4Answ("Kto jest premierem Polski? \na) Macierewicz \nb) Duda \nc) Kaczynski \nd) Szydlo", 1, "d");
            collection[3] = new Task4Answ("Ktore slowo kluczowe w C++ jest uzywane do deklarowania typu zmiennoprzecinkowego \na) Float \nb) Int \nc) Enum \nd) Struct", 1, "float");
            collection[4] = new Task4Answ("Ktory z podanych modyfikatorow dostepu pozwala na uzywanie zmiennych klasy bazowej w klasach pochodnych, a w innych klasach nie? \na) Domyslny \nb) Public \nc) Private \nd) Protected", 1, "d");
            collection[5] = new Task4Answ("Jakiego slowa kluczowego uzywamy do zwrocenia obiektu z funkcji? \na) Back \nb) Reversion \nc) Return \nd) Void", 1, "c");
            collection[6] = new Task4Answ("Ktory z samochodow nalezy do fabryki Volkswagenta? \na) Mondeo \nb) Passat \nc) Vectra \nd) Yaris", 1, "b");
            collection[7] = new Task4Answ("Ktory czlowiek na swiecie pierwszy stanal na ksiezycu? \na) Gagarin \nb) Lajka \nc) Armstrong \nd) Ahonen", 1, "c");
            collection[8] = new Task4Answ("Ktory z samochodow nalezy do fabryki Opla? \na) Mondeo \nb) Passat \nc) Vectra \nd) Yaris", 1, "c");
            collection[9] = new Task4Answ("Z iloma panstwami graniczy Polska? \na) 5 \nb) 6 \nc) 7 \nd) 8", 1, "c");
            collection[10] = new Task4Answ("Od ktorego roku Polska nalezy do Unii Europejskiej? \na) 2004 \nb) 2006 \nc) 2002 \nd) 2000", 1, "a");
            collection[11] = new Task4Answ("Kto jest obecnym prezesem PZPN? \na) Boniek \nb) Lato \nc) Listkiewicz \nd) Gmoch", 1, "a");
            collection[12] = new Task4Answ("Ktora z planet posiada charakterystyczny pierscien? \na) Neptun \nb) Jowisz \nc) Saturn \nd) Merkury", 1, "c");
            collection[13] = new Task4Answ("Za pomoca jakiego slowa kluczowego definiujemy szablony w C++? \na) Template \nb) Pattern \nc) Stencil \nd) Stereotype", 1, "a");
            collection[14] = new Task4Answ("Ktory z podanych jezykow posiada interfejsy? \na) C++ \nb) C \nc) C# \nd) HTML", 1, "c");
            collection[15] = new TaskNumber("Podaj date Bitwy Pod Grunwaldem", 15, 1410);
            collection[16] = new TaskNumber("Podaj maksymalna predkosc w terenie zabudowanym", 16, 50);
            collection[17] = new TaskNumber("W ktorym roku odbyly sie Mistrzostwa Europy w Pilce w Polsce?", 17, 2012);
            collection[18] = new TaskNumber("Ile bajtow pamieci zajmuje typ long w jezyku C++?", 18, 8);
            collection[19] = new TaskNumber("W ktorym roku w Polsce ogloszono stan wojenny?", 19, 1978);
            collection[20] = new TaskNumber("Po dodaniu dwoch zmiennych typu int, ile bajtow pamieci zajmie zmienna przechowujaca wynik tego dodawania?", 20, 4);
            collection[21] = new TaskNumber("Ile wynosi reszta z dzielenia liczby 60 przez liczbe 7?", 21, 4);
            collection[22] = new TaskNumber("Ile wynosi pierwiastek z liczby 49?", 22, 7);
            collection[23] = new TaskNumber("W ktorym roku rozpoczela sie II Wojna Swiatowa?", 23, 1939);
            collection[24] = new TaskNumber("W ktorym roku mial miejsce chrzest Polski?", 24, 966);
            collection[25] = new TaskNumber("Ile zlotych medali zdobyl Adam Malysz na Igrzyskach Olimpijskich?", 25, 0);
            collection[26] = new TaskNumber("Ile lat trwa kadencja prezydenta w Polscce", 26, 4);
            collection[27] = new TaskNumber("Jezeli na kazde 15 metrow kwadratowych przypada 6 wezy, ile wezy przypadnie na 90 metrow kwadratowych", 27, 36);
            collection[28] = new TaskNumber("W ktorym roku mial miejsce atak terrorystyczny na World Trade Center", 28, 2002);
            collection[29] = new TaskNumber("Jezeli 3 lata temu Ania ktora ma teraz 18lat byla 3 razy starsza od Tomka, to ile lat ma teraz Tomek", 29, 8);
            collection[30] = new TaskString("Podaj wzor chemiczny wody", 30, "H2O");
            collection[31] = new TaskString("Podaj gdzie urodzil sie Kopernik", 31, "Torun");
            collection[32] = new TaskString("Na jakim instrumencie gral Fryderyk Chopin", 32, "Fortepian");
            collection[33] = new TaskString("Podaj slowo kluczowe, ktorego uzywa sie do zwalniania pamieci w C++", 33, "Delete");
            collection[34] = new TaskString("Jak nazywa sie program w C# pelniacy role destruktora?", 34, "Garbage Collector");
            collection[35] = new TaskString("Jakiego slowa kluczowego uzywamy w C# do przyslaniania funkcji klasy bazowej?", 35, "Override");
            collection[36] = new TaskString("Jakie miasto jest stolica Kanady?", 36, "Ottawa");
            collection[37] = new TaskString("Jaka jest najwieksza wyspa na swiecie?", 37, "Grenlandia");
            collection[38] = new TaskString("Skad pochodzi sprinter Usain Bolt?", 38, "Jamajka");
            collection[39] = new TaskString("Jakiego slowa kluczowego uzywamy do deklarowania klas abstrakcyjnych w C#", 30, "Abstact");
            collection[40] = new TaskString("Jakiego slowa kluczowego uzywamy do deklarowania klas wirtualnych w C#", 40, "Virtual");
            collection[41] = new TaskString("Podaj slowo kluczowe, ktorego uzywa sie do deklarowania struktur w C# i C++", 41, "Struct");
            collection[42] = new TaskString("Jak nazywa sie dziedzina nauki, zajmujaca sie m.in kosmosem?", 42, "Astronomia");
            collection[43] = new TaskString("Podaj nazwe jednostki cisnienia", 43, "Pascal");
            collection[44] = new TaskString("Podaj nazwisko angielskiego uczonego, ktory sformuowal zasade zachowania energii", 44, "Newton");
            collection[45] = new TaskFewAnsw("Wymien 3 modyfikatory dostepu w C++", 45, "Public","Private","Protected");
            collection[46] = new TaskFewAnsw("Jakie miasta były stolicami Polski?", 46, "Warszawa","Krakow","Gniezno");
            collection[47] = new TaskFewAnsw("Wymien daty rozpoczecia obu wojen swiatowych", 47, "1939","1914","");
            collection[48] = new TaskFewAnsw("Podaj nazwy dwoch najludniejszych panstw na swiecie?", 49, "Chiny","Indie","");
            collection[49] = new TaskFewAnsw("Podaj nazwy dwoch najwiekszych panstw na swiecie", 49, "Rosja","Kanada","");
        }

Then here i have to draw 10 tasks from this collection, but i can't just copy it from collection cause all are from different classes.

How to Test this kindof Controller using TestRestTemplate in springboot

@ApiRestController public class CityController extends BaseController{

@GetMapping("/cities")

public ResponseEntity<CitiesResponse> getAll(
        @RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
        @RequestParam(value = "pageSize", defaultValue = "100") int pageSize,
        @RequestParam(value = "sortBy", defaultValue = "id", required = false) String sortBy,
        @RequestParam(value = "sortDirection", defaultValue = "asc", required = false) String sortDirection,
        @RequestParam(value = "search", required = false) String search) {
    return new ResponseEntity(cityService.getAll(pageNumber, pageSize, sortBy, sortDirection, search), HttpStatus.OK);
}

}

custom function to select and click a random element in Nightwatch

I'm new to e2e testing (and JS). I use Nightwatch framework.

I'm trying to create a function that selects a random element from a list of elements with the same selector, and clicks on it.

This is what I tried:

const tryRandom = {
  pickOne() {
    this.api.elements('css selector', '.search-card-footer__button-container', function(res) {
       optionsLength = Math.floor((Math.random() * res.value.length) + 1);
    });
    this.api.waitForElementVisible(`.search-cards__item:nth-child(${optionsLength})`);
    this.api.click(`.search-cards__item:nth-child(${optionsLength}) .action-button`);
  }
};

But in this case, optionsLength is not defined.

Math.floor((Math.random() * res.value.length) + 1) returns a number. I want to use this number outside of the function.

I've tried to store the full function in a variable, as in:

const optionsLength = this.api.elements('css selector', '.search-card-footer__button-container', function(res) {
       Math.floor((Math.random() * res.value.length) + 1);
    });

But that way optionsLength logs [object Object] instead a number.

get number of items with the same selector in Nightwatch

I'm new to e2e testing (and JavaScript). I'm using Nightwatch framework and I'm trying to find how many elements are with X selector and click on a random one.

const tryRandom = {
  pickOne() {
    const optionsLength = this.api.elements('css selector', '@addToShortlistBtn div', function(res) {
      console.log(res.value.length)
      return res.value.length;
    });
    const num = Math.floor((Math.random() * optionsLength) + 1);
    this.api.waitForElementVisible(`.search-cards__item:nth-child(${num})`);
    this.api.click(`.search-cards__item:nth-child(${num}) .action-button`);
  }
};


module.exports = {
  url: function getUrl() {
    return `${this.api.launchUrl}/products`;
  },
  commands: [tryRandom],
  elements: {
    addToShortlistBtn: '.search-card-footer__button-container'
  }
};

console.log(res.value.length) doesn't log anything. I've also tried res.value.count.

The const num outputs as NaN. I've also used other selectors and the result is the same.

Testing ICollectionView in WPF ViewModel

I want to write an automated integration test of my ViewModel in a WPF application.

The ViewModel contains an ICollectionView on which a DataGrid is bound in the View. The handling of SelectedItem etc is done with this ICollectionView.

Stripped example of my ViewModel:

public class ViewModel
{
    private List<string> _rows;
    public ICollectionView Collection { get; set; }

    public ViewModel()
    {
        _rows = new List<string> {"1", "2", "3"};
        Collection = CollectionViewSource.GetDefaultView(_rows);
        Collection.MoveCurrentToFirst();
    }

    public string SelectedString => Collection.CurrentItem as string;
}

Problem now is, that in my test, the Collection.MoveCurrentToFirst() method does not result in CurrentItem being set. In the application it does set the CurrentItem. Of course I want to stay as close as possible to the real execution of the application in my tests, so does anyone have an idea how to implement the test in a way, that the CurrentItem is set by the ICollectionView?

Asp.net core 2.0 remote testing and ef core mocking

I am developing web api(s) for an android app client. Now the developer of the client, wants a way to test web api(s) without getting the real data corrupt. So now I am thinking of something like unit testing and database (ef core) mocking in that except the requests are remote and stateless; so every time the client app requests for data or changing it, the database should remember the last things.

From the docs of Microsoft, there are two ways to do this on unit testing:

But the thing is that does are volatile and from on request to another request they will be refreshed. So I think SQLite (normal mode - file mode) will be a good solution. Now there are two questions:

  1. Is this a good idea or there is one better?
  2. If it is good, then how should I implement it?
  3. Is it good to add a header in the request?
  4. On the server-side code where should I tell the ef to use testing database?

Thanks in advance.

TG.

jeudi 24 août 2017

I can't get FormBuilder from TestBed with FormsModule, ReactiveFormsModule imported

TestBed.configureTestingModule({
    imports: [
        FormsModule,
        ReactiveFormsModule,
    ]
});

TestBed.get(FormBuilder);

What do I need to do? Or I should just use new operator to create one?

Selenium client-sided load test max request per second?

I am using Selenium to perform client-sided testing of a specific browser on an AngularJS web application. I want perform a load test by sending many request from concurrent users. For example, 1k request in a second from x amount of users, 2k request, etc.

There is no formal documentation on this topic. Has anyone done this before? Is there an (expected) maximum amount of request Selenium can perform, I know it would be dependant on hardware. I also know there exist tools such as Jmeter, but those do not run client-side JavaScript.

start browser with specicfic user profile using chromedp

i am using selenium with python and i can do all my testing work using it but i am learning Golang and i want to try to test using it i came across chromedp and i like it but i couldn't figure out how to start google chrome with a specific user profile

can any one help please ?

i am using this example :

package main

import ( "context" "fmt" "io/ioutil" "log" "time"

cdp "http://ift.tt/2jtQ7f4"
cdptypes "http://ift.tt/2w8Hxa9"

)

func main() { var err error

// create context
ctxt, cancel := context.WithCancel(context.Background())
defer cancel()

// create chrome instance
c, err := cdp.New(ctxt, cdp.WithLog(log.Printf))
if err != nil {
    log.Fatal(err)
}

// run task list
var site, res string
err = c.Run(ctxt, googleSearch("site:brank.as", "Easy Money Management", &site, &res))
if err != nil {
    log.Fatal(err)
}

// shutdown chrome
err = c.Shutdown(ctxt)
if err != nil {
    log.Fatal(err)
}

// wait for chrome to finish
err = c.Wait()
if err != nil {
    log.Fatal(err)
}

log.Printf("saved screenshot of #testimonials from search result listing `%s` (%s)", res, site)

}

func googleSearch(q, text string, site, res *string) cdp.Tasks { var buf []byte sel := fmt.Sprintf(//a[text()[contains(., '%s')]], text) return cdp.Tasks{ cdp.Navigate(https://www.google.com), cdp.Sleep(2 * time.Second), cdp.WaitVisible(#hplogo, cdp.ByID), cdp.SendKeys(#lst-ib, q+"\n", cdp.ByID), cdp.WaitVisible(#res, cdp.ByID), cdp.Text(sel, res), cdp.Click(sel), cdp.Sleep(2 * time.Second), cdp.WaitVisible(#footer, cdp.ByQuery), cdp.WaitNotVisible(div.v-middle > div.la-ball-clip-rotate, cdp.ByQuery), cdp.Location(site), cdp.Screenshot(#testimonials, &buf, cdp.ByID), cdp.ActionFunc(func(context.Context, cdptypes.Handler) error { return ioutil.WriteFile("testimonials.png", buf, 0644) }), } }

R: How to tell if any tests failed from result of testthat::test_dir

I have a small testing program that uses testthat

library(testthat)
source("src/MyFile.r")
results <- test_dir("tests", reporter="summary")

So, I am running this via Rscript. The problem is that the exit code is always 0 even when there were test failures. So, I want to call stop if there are any failures. But I can't seem to get the right bit of code to do that. Is there a method or field in results that I should be looking at to determine if there were any errors?

How to unit-test rxjs5?

I've read through this "marble-string" docs, but I juts don't get it.

What I want to test is basically a "protocol". I have a "thing" which is connected to an Observable and which emits data. In my backend code with Rx.NET and C# I have written a helper to test protocols so that my tests look like this:

verifier.Send(new AddMaterialPickCommand(commandId, orderId, materialId: Guid.NewGuid(), quantity: 1))
            .FailWhen<CommandFailedEvent>(e => e.CommandId == commandId)
            .ThenExpect<MaterialPickAddedEvent>(e => e.EntityId == orderId)
            .ThenSend(new DeleteOrderCommand(commandId, orderId))
            .FailWhen<CommandFailedEvent>(e => e.CommandId == commandId)
            .ThenExpect<OrderDeletedEvent>(e => e.EntityId == orderId)
            .ExecuteAndWait(Timeout);

In C# its very easy to connect observables to all things and its also very easy to wait. IMO it is a very readable test code.

With Rxjs5, I didn't find any possibility to wait or do anything similar. So atm I'm failing at just checking that a single thing emitted by my observable is the one expected:

sut.setValue("key1", "key2");
sut.getObservable("key1", "key2")
    .subscribe(value => {
       expect(value).toBe("testValue")  // I want either execute this or fail after a timeout
    });

setValue actually calls next() on a BehaviourSubject.

I'm clueless, any ideas?

Is it possible to make a plugin/ fragment depend on another fragment?

I would like to re-use some test classes, which are living in a dedicated fragment. Require-Bundle wont accept a fragment, Import-Package seems not to consider fragment packages.

How to test asynchronous components

I would like to write some tests for the components that work with data fetching. For example, I need to test this logic:

  1. User click on the button "add image".
  2. A modal window appears and sends a request to get user images. When the request is done - the component shows user images.
  3. User selects one image and click the button "select"
  4. Component should return selected image

To test any part of this logic, I need to w8 after the request is done. How can I do this?

I try to use axios-mock-adapter, moxios, sinon-as-promised, sinon.fakeServer but no one works for me. I can attach my current implementation of this thing here if needed.

P.S. I know that I can break up my test and assay each part. But this is what makes my tests very fragile, just because each time when implementation changes all tests should be rewritten. That's why I start writing tests only for UI but not for implementations