lundi 31 juillet 2017

Empirical Analysis of Merge and Insertion Sort - Difficulties

I'm trying to analyse the run time of my implementation of merge and insertion sort. I'm noticing a weird trend and I wasn't able to find anyone with the same problem through googling, but I'm probably using the wrong terms.

The number of times the sorting algorithms run, seem inversely related to the amount of time taken for the algorithm to complete. Sample shown below for insertion sort.

4213,2104,8195,9441,4823,925,980,964,911,491,470,482,481... (it settles on ~490ms)

And similar behaviour with merge sort, but merge settles on ~95ms.

I have no idea why this is happening, I'm generating a random array every time... even if it wasn't random shouldn't it just take exactly the same time every time (or close)? why does it converge on a smaller value?

Just looking for anyone who might know why this is happening because it seems really strange to me... I'm assuming it's something Java is doing behind the scenes maybe? Any suggestions/tips appreciated!

All the code I am running is posted below. With the test code shown first.

public static void tests(int noTests, int arraySize){
    //set up the running totals of the time taken by insertion and merge
    double insertSum = 0;
    double mergeSum = 0;

    for(int i = 0; i < noTests; i++){
        //generate an array of random integers
        Integer[] randInput = generateRandomArray(arraySize);

        //start the clock for insertion
        final long insertionStart = System.nanoTime();
        //sort it 
        insertionSort(randInput);
        //stop the clock for insertion
        final long insertionFinish = System.nanoTime();
        System.out.println("Time taken for insertion: " + (insertionFinish - insertionStart)/1000 + " ms");
        //add it to the running total 
        insertSum += (insertionFinish - insertionStart)/1000;

        //likewise for merge 
        final long mergeStart = System.nanoTime();
        mergeSort(randInput);
        final long mergeFinish = System.nanoTime();
        System.out.println("Time taken for merge: " + (mergeFinish - mergeStart)/1000 + " ms");
        mergeSum += (mergeFinish - mergeStart)/1000;
    }
    //Get the average by diving by the number of times it ran 
    System.out.println("-------------------------------------------------------");
    System.out.println("Insert average: " + insertSum/noTests);
    System.out.println("Merge average: " + mergeSum/noTests);
}

//Generate an array of random Integers 
public static Integer[] generateRandomArray(int n){
    Integer[] arr = new Integer[n];
    for(int i = 0; i < n; i++){
        arr[i] = (int) Math.floor(Math.random()*100);
    }
    return arr;
}

public static <T extends Comparable<T>> T[] insertionSort(T[] a){
    for(int i = 1; i < a.length; i++){
        int j = i-1;
        T key = a[i];

        while(j >= 0 && a[j].compareTo(key) > 0){
            a[j+1] = a[j];
            j = j-1;
        }
        a[j+1] = key;
    }
    return a;
}

@SuppressWarnings("rawtypes")
public static Comparable[] mergeSort(Comparable[] input){

    if(input.length<=1){
        return input;
    }

    int middle = Math.floorDiv(input.length, 2);

    Comparable a[] = new Comparable[middle];
    for(int i = 0; i < middle; i++){
        a[i] = input[i];
    }

    Comparable b[] = new Comparable[input.length - middle];
    for(int i = middle; i < input.length; i++){
        b[i-middle] = input[i];
    }

    mergeSort(a);
    mergeSort(b);
    merge(input, a, b);

    return input;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void merge(Comparable[] input, Comparable[] a, Comparable[] b){

    int inputIndex = 0;
    int aIndex = 0;
    int bIndex = 0;

    while(aIndex < a.length && bIndex < b.length){

            if(aIndex < a.length & a[aIndex].compareTo(b[bIndex]) < 0){
                input[inputIndex] = a[aIndex];
                aIndex++;
            } else{
                input[inputIndex] = b[bIndex];
                bIndex++;
            }
            inputIndex++;
    }
}

Example output:

Time taken for insertion: 4266 ms
Time taken for merge: 643 ms
Time taken for insertion: 2127 ms
Time taken for merge: 199 ms
Time taken for insertion: 8001 ms
Time taken for merge: 201 ms
Time taken for insertion: 9568 ms
Time taken for merge: 157 ms
Time taken for insertion: 9614 ms
Time taken for merge: 158 ms
Time taken for insertion: 495 ms
Time taken for merge: 125 ms
Time taken for insertion: 485 ms
Time taken for merge: 141 ms
Time taken for insertion: 508 ms
Time taken for merge: 517 ms
Time taken for insertion: 484 ms
Time taken for merge: 804 ms
Time taken for insertion: 484 ms
Time taken for merge: 796 ms
-------------------------------------------------------
Insert average: 3603.2
Merge average: 374.1

Thanks!

How to test that Python and the standard libaries are properly installed?

I'm sometimes sitting in front of a machine where I'm not sure whether Python with the standard libraries is fully installed: Frequent installing and uninstalling of stuff through the package manager (e.g. setup.exe for Cygwin) might have removed things which are necessary for use the of the standard library.

Is there an easily accessible Python script (separately for Python 2 and Python 3) which checks that interpreter and the standard libraries are properly installed?

How do I cause session timeout logouts instantly?

A web application is supposed to timeout a user session & log him out after N minutes. I don't know what N is or how the session timeout logout mechanism is implemented.

I want to test what happens on session timeout by causing timeout instantly. Is there a way to tinker with the front end such that it causes a timeout instantly, OR do I need to change back end to cause an instant timeout ?

Ember testing with click and drag for SVG

For writing acceptance tests for clicking and dragging elements as seen in the link here, I have found this resource github jQuery-ui online. Are there any better options?

ActivePivot how to load avro source to activepivot store

ActivePivot how to load avro source to activepivot store. I want to load the Avro data into Activepivot datastore.

How to mock behavior of a method

I have following scenario

class A {   
    Response response = someFunction()
    response.doStuff()
}

class Response {    
    fun doStuff() {
        //check if response status is OK         
        //some stuff, not to be executed when in test
    }
} 

I need to check if response is OK but not execute rest of the logic. I am looking to achieve something like -

when(response.doStuff())Then(assert response is ok)

Can you please let me know how to do this?

Returning different values from a stubbed out service or function?

I have created a function that will query a service for a true or false status. This function will sleep and retry until the service returns true.

func main() {
    fmt.Println("Hello, playground")

    for {
        query, err := getQueryValue()
        if err != nil {
            return "error"
        }
        // assume new_args gets a value to be used. 
        new_args := someLogicWithLoop()
        if parseMyQuery(query, new_args) {
            return "success"
        }
        time.Sleep(delayTime)
    }
}

What is the best way to test this? I feel like I should have a stubbed service that will return false for the first time and then return true.

I was thinking something like this -

type fakeService struct {
    //some interface
    err error
    want bool
}

func (f *fakeService) doSmth() int {
    if f.want {
        return 1
    }
    return 0
}

func main() {
    a := &fakeService{want: true}   
    fmt.Println(a.doSmth())
}

However, it doesn't seem to be very flexible. What are some alternative / cleaner ways to achieve the above?

trying to extend a struct type but i want nest the embbeded struct

i am trying to write some integration tests for me RESTAPI. I am at the point where i need some testdata. I thought it would be cool to use my Type: User in my Tests from my own package.

type User struct {
    ID        string `db:"id" json:"id"`
    AccountID string `db:"account_id" json:"account_id,omitempty"`
    Email     string `db:"email" json:"email"`
    Password  string `db:"password" json:"password,omitempty"`
}

I have defined a new field called valid in the fixtures/users.json.

[
{
    "AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
    "Email": "mail@domain.tld",
    "Password": "test116",
    "valid": false
},
{
    "AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
    "Email": "mail1@domain.tld",
    "Password": "test147",
    "valid": false
},
{
    "AccountID": "403fd0d1-cca1-4a7b-80fb-1a51c85fbde0",
    "Email": "mail2@domain.tld",
    "Password": "test2617",
    "valid": true
}
]

now i have this little helper method to load the json into a my struct.

func loadJSONtoStruct(target interface{}, filename string) error {

    file, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Printf("Cant read file: %v\n", err)
        return err
    }

    err = json.Unmarshal(file, &target)
    if err != nil {
        fmt.Printf("Cant unmarshal: %v\n", err)
        return err
    }

    return nil
}

package main_test

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    . "http://ift.tt/1ontsJN"
    . "http://ift.tt/1eRuMUy"
    "http://ift.tt/2vfyiXi"
    "http://ift.tt/2tRhy5k"
)

type user struct {
    package_with-types.User
    valid bool
}

var _ = BeforeSuite(func() {
    request = gorequest.New()
    err := loadJSONtoStruct(&users, "fixtures/users.json")
    if err != nil {
        fmt.Printf("%+v", err)
    }

    fmt.Printf("%+v\n", users)
})

but i get this nested struct back

[{
User: {
    ID: AccountID: 
    Email:mail@domain.tld 
    Password:test116
} 
valid:false
},
{
User:  {
    ID: AccountID: 
    Email:mail1@domain.tld 
    Password:test147
} 
valid:false
},
{
User: {
    ID: AccountID: 
    Email:mail2@domain.tld 
    Password:test2617
} 
valid:false
}]

and i want this:

[{
    ID: AccountID: 
    Email:mail@domain.tld 
    Password:test116
    valid:false
},
{
    ID: AccountID: 
    Email:mail1@domain.tld 
    Password:test147
    valid:false
},
{
    ID: AccountID: 
    Email:mail2@domain.tld 
    Password:test2617
    valid:false
}]

what do you think? should i live with it, and use user.user.ID user.valid in my tests?

Thank you Tim

Error loading 'teamcity' file when running `Cucumber ./features`

Currently, I am trying to use Cucumber to run tests in a Ruby on Rails application.

cucumber ./features --tags ~@javascript

Whenever I run this command however, I get the following error related to teamcity

Using the default profile...
cannot load such file -- teamcity/spec/runner/formatter/teamcity/formatter (LoadError)

I've tried using solutions given in other related questions but can't seem to get it to work, unless there's something I'm missing.

Versions

  • Ruby 2.0.0p648 (2015-12-16 revision 53162)

  • Rails 3.2.21

  • Ubuntu 16.04

Full Error

cannot load such file -- teamcity/spec/runner/formatter/teamcity/formatter (LoadError)
/home/d/dev/sareform/features/support/env.rb:22:in `require'
/home/d/dev/sareform/features/support/env.rb:22:in `block in <top (required)>'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/spork-1.0.0rc4/lib/spork.rb:24:in `prefork'
/home/d/dev/sareform/features/support/env.rb:4:in `<top (required)>'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/rb_support/rb_language.rb:129:in `load'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/rb_support/rb_language.rb:129:in `load_code_file'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime/support_code.rb:171:in `load_file'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime/support_code.rb:83:in `block in load_files!'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime/support_code.rb:82:in `each'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime/support_code.rb:82:in `load_files!'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime.rb:175:in `load_step_definitions'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/runtime.rb:40:in `run!'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/cli/main.rb:43:in `execute!'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/lib/cucumber/cli/main.rb:20:in `execute'
/home/d/.rvm/gems/ruby-2.0.0-p648/gems/cucumber-1.2.1/bin/cucumber:14:in `<top (required)>'
/home/d/.rvm/gems/ruby-2.0.0-p648/bin/cucumber:23:in `load'
/home/d/.rvm/gems/ruby-2.0.0-p648/bin/cucumber:23:in `<main>'
/home/d/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `eval'
/home/d/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `<main>'

Gemfile

gem 'rails', '3.2.21'
gem 'rake', '10.4.2' 
....

gem 'jquery-rails'#, "3.1.2" #old version 1.0.19
gem 'jquery-ui-rails'
gem 'rvm'
gem 'rvm-capistrano',  require: false
....
gem 'coffeebeans'
....
gem 'nokogiri', '>= 1.6'
gem 'custom_configuration', '~> 0.0.2'

group :test, :test_ram do
  gem 'cucumber'
  gem 'cucumber-rails', :require => false
  gem 'timecop'
  gem 'guard-zeus'
  gem 'kaminari-rspec'
end

group :cucumber, :test, :test_ram do
  gem 'i18n'
  gem "rack"
  gem 'rack-test'
  gem 'capybara'
  gem 'database_cleaner'
  gem 'rb-inotify'#, '~> 0.9'
  gem 'libnotify'
  gem 'ffi', '>= 1.0.11'
  gem "factory_girl_rails" #was 1.6.0
  gem "guard"#, "~> 1.1.0"#was 0.10.0
  gem "guard-rspec"
  gem "guard-livereload"
  gem "guard-cucumber", "~>1.2.2" #was 0.7.5
  gem "guard-bundler"
  gem 'guard-webrick', "~> 0.1.2" #was 0.1.0
  gem 'guard-test'
  gem 'spork', '> 0.9.0.rc'
  gem 'guard-spork'
  gem 'selenium-client'
  gem "selenium-webdriver", "~> 2.45.0"
  gem 'cucumber_statistics'
end


group :development, :test, :test_ram do
  gem 'email_spec'
#  gem 'mocha'#was 0.10.4
  gem 'webrat'
  gem 'rspec-rails' #was 2.8.0
  gem "rspec-activemodel-mocks"
  gem "launchy", '~> 2.1.0' #previously no version identified
  gem "geordi"
  gem 'rb-fsevent'
  gem "zeus"
  gem "parallel_tests"
  gem 'zeus-parallel_tests'
  gem 'jasmine'
  gem 'jasmine-sinon-rails'
  gem 'jasmine-jquery-rails'
end

Mann - Kendall test on hydrology autocorellated data in R

i have a problem on time series analysis. i want to check if there is a trend in my time series. i am completly new to ts analysis so i have no idea how to do this. i just know that i got to go with Mann - Kendall test. my data is autocorellated and looks like this:

Date          flow
01.11.2005    0,038
02.11.2005    0,045
03.11.2005    0,051
04.11.2005    0,05
05.11.2005    0,05
06.11.2005    0,05
07.11.2005    0,05
08.11.2005    0,05
09.11.2005    0,05
10.11.2005    0,05
11.11.2005    0,038
12.11.2005    0,038
13.11.2005    0,038
14.11.2005    0,038
15.11.2005    0,038
16.11.2005    0,049
17.11.2005    0,049
18.11.2005    0,048
19.11.2005    0,048
20.11.2005    0,048
21.11.2005    0,048
22.11.2005    0,048
23.11.2005    0,037

How to mock function only in tested class and not in unittest case

So i have unit test case class and a class that I want to test. There is a function in this class that has a function that I'm using to run this method that i am testing. To visualize the problem i will write some abstract code below:

import needed_module
from casual_class import CasualClass

class CasualClassTests(unittest.TestCase):

    def setUp(self):
        self.casual_class = CasualClass()

    def _run(self, func):
        result = needed_module.runner(func)
        return result

    @mock.patch('needed_module.runner', return_value='test_run_output')
    def test_get_that_item(self, mocked_runner):
        result = self._run(self.casual_class.get_that_item())

And the tested class:

import needed_module


class CasualClass:

    def get_that_item(self):
        #..some code..
        run_output = needed_module.runner(something)
        return something2

In this code get_that_item code wont even run because the runner is mocked. What i want to achieve is to run needed_module.runner original in test case and mocked one in the tested class. I've searched the internet for too long, to solve this...

Rails 5 Test Case - Getting SQLite3::ConstraintException error when running test on controller that doesn't use model

Im sorry if this might be long but would appreciate your help on this.

I'm getting error when running test on my home controller.

This is my home controller which just basically renders the view.

class HomeController < ApplicationController
    def index
    end
end

And in my test/controllers/home_controller_test.rb

require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
    test "should get index" do
        get home_index_url
        assert_response :success
    end
end

When i run bin/rails test test/controllers/home_controller_test.rb in the terminal, im getting this error as a result

Running via Spring preloader in process 27352
Run options: --seed 1283

# Running:

E

Error:
HomeControllerTest#test_should_get_index:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: NOT NULL
constraint failed: addresses.full_address: INSERT INTO "addresses" 
("created_at", "updated_at", "id") VALUES ('2017-07-31 11:49:24.912600', 
'2017-07-31 11:49:24.912600', 980190962)

bin/rails test test/controllers/home_controller_test.rb:4

Finished in 0.595890s, 1.6782 runs/s, 0.0000 assertions/s.

1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

I have a model called Address but it's not used in the home controller. Here is how my Address migration file looks like

class CreateAddresses < ActiveRecord::Migration[5.0]
  def change
    create_table :addresses do |t|
      t.string :full_address, null: false
      t.string :formatted_address
      t.string :sub_locality
      t.string :city
      t.string :postal_code
      t.string :state
      t.decimal :latitude, precision: 9, scale:6
      t.decimal :longitude, precision: 9, scale:6
      t.references :user
      t.references :order
      t.references :merchant

      t.timestamps
    end
  end
 end

From my understanding, the test result would return success if the http response is 200. In my browser, i can load my home page without any errors in my log.

Im confused as to why i'm getting Address model related error when i'm testing my home controller even though i did not access it in my home controller or view.

Any help on this would be appreciated!

Which software can I use to automate regression tests on a software?

I'm looking for a software which can reproduce my manual tests for regression tests, because it's boring.

These such tests are done on a software, not a webapplication.

Bonus if exists free ones.

Thanks :)

Performance/Load test using selenium webdriver prerecorded steps

I have been using selenium webdriver as my main method to do functional tests. So far its been working greate with our product.

I need to do some performance and/or load tests on the website, I was wondering if there is a tool that would incorporate my selenium tests or a tool which i can use with the recorded tests as the base.

Currently i am using selenium webdriver with C#

Any help is appreciated.

pact-jvm-server Complete returns 400

I've got a pact-jvm-server instance in Docker and when ever I call the /create method it creates a stub server and returns the correct responses. But now when I try to delete the stub server on the selected port with /complete call and port in body of the POST request it always returns 400 even though it deletes the stub service on provided port.

Any help would be appreciated.

dimanche 30 juillet 2017

karma setup giving require is not defined

I'm new at setting up karma and testing here, so I've been going through a bunch of examples out there to set my env up. However, whenever I run karma start, it gives me this:

Uncaught ReferenceError: require is not defined
at test/person-test.js:1

I think I probably didn't set up my karma.conf.js correctly, does anyone have any clue? This is what I have:

module.exports = function(config) {
  config.set({

    basePath: '',
    frameworks: ['jasmine', 'browserify'],
    files: [
      'test/**/*.js'
    ],
    exclude: [],
    preprocessors: {
      'src/**/*.js': ['browserify']
    },
    plugins: [
      'karma-chrome-launcher',
      'karma-jasmine',
      'karma-browserify'
      ],
    browserify: {
      debug: true,
      transform: [ 'brfs', 'browserify-shim' ]
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
}

I have file structure like this:

.
├── src
|   └── person.js
├── test
|   ├── person-test.js
├── karma.conf.js
└── package.json

Where my person.js file is like this:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  upperCaseName() {
    this.name = this.name.upperCaseName();
  }
}

module.exports = Person;

and (so far) my person-test.js is:

const Person = require('../src/person.js')

Where to start for JavaScript as a beginner?

I am tester and I want to learn JavaScript for the purpose to move in automation testing domain. Kindly guide me where to start from.

Website Testing - Do I need to pay attention to minor version difference

Questions keep coming up as I want to achieve a good browser/OS coverage:

  1. Minor browser version change: For instance, most people use Chrome 56, 57 and 58, then do I need to do end-to-end test against each of them?

  2. Minor OS version change: similar topic, for a given browser version, do I need to test against Windows 7, Windows 8 and Windows 10 separately?

Unit test using jasmine controller calls $resource in service

I am new to Jasmine unit testing and i am using angular controller and service where the controller calls service to return $resource get.How to write a function in jasmine for the below controller and service code?

controller code

(function () {

angular

     .module('TestModule')

     .controller('TestController', function (TestService) {

         var vm = this;

         TestService.get().$promise.then(function (data) {

             vm.bookmarks = data;
         });




     });

})();

service code

(function () {

angular

       .module('TestModule')

        .service('TestService', function ($resource) {


            return $resource('http://localhost:60334/api/event/123', {});

        })

})();

How to see results of my unit tests in gradle console?

How to see results of my unit tests in gradle console? I build apk using ./gradlew build and then I must run all my unit tests (Robolectric and Mockito). I write ./gradlew test. It runs some tests, I see they're ok, but do my unit tests runs by it? For now I can run them only from Android Studio.

Cannot make Goose DB Migration working for Go testing

I am currently learning Golang for web programming and now I continue by learning about database,Rest API and testing in Golang.

and now I got an issue with Goose database Migration and Go Testing integration.

I want to integrate goose migration to my Go testing code, my scenario is to up all migrations before test and then reset all database once testing is done.

my problem is I can't find any documentation/sample code to do it with Goose.

I also have tried to execute the goose command using exec.Command() but it always returns exit status 1

this is my existing code to trigger the migration up before testing being executed:

func pretest() {
      var args = []string{
          os.Getenv("DB_SERVER"),
          "\"user=" + os.Getenv("DB_USERNAME") + " dbname=" + os.Getenv("DB_TEST_NAME") + " sslmode=disable\"",
          "up",
      }   

      exe := exec.Command("goose", args...)
      exe.Dir = os.Getenv("DB_MIGRATION")
      /* result, err := exe.Output()*/
      //fmt.Println(string(result))
      /*fmt.Println(err)*/

      output := exe.Run()
      fmt.Println(output)
  }

enter image description here

my question is it possible to trigger migration (up/down/reset) from inside Go Code (in this case is testing code) ?

Why exec.Command() keep returning code status 1 but it work well when I execute another linux command (ls, pwd, mkdir are work well in the same way) ?

mockito doesn't match any(type) method

I test this code:

        PublisherCallbackWithLog publisherCallback = new PublisherCallbackWithLog<String>();

        for (SdkRequest.SdkRequest sdkRequest : SdkRequestsList.getRequestList()) {
            final String s = TextFormat.printToUnicodeString(sdkRequest);
            customPublisher.publish(s, publisherCallback);
        }

in my test I have this line:

    verify(customPublisher, times(1)).publish(argThat(eqWithoutRequestId(sdkRequest)), any(PublisherCallbackWithLog.class));

but I get an error, seems about the 2nd argument.

Argument(s) are different! Wanted:
customPublisher.publish(
    ,
    <any>
);
-> at com.w.sdkService.servlets.SdkPollerServlet_PublishTest.readFromSpreadsheet3Rows_shouldPublish2Times(SdkPollerServlet_PublishTest.java:75)
Actual invocation has different arguments:
customPublisher.publish(
    "partner {
  display_name: "WTest"
  android_pkg_name: "com.example.eliran.myapplication"
  sharing_mode: DATA
}
requestId: "3a7458b6-edc0-4d4e-b52e-d2a3847bef0b"
requestType: REMOVE
",
    com.w.sdkService.services.callback.PublisherCallbackWithLog@56f6d40b
);
-> at com.w.sdkService.servlets.SdkPollerServlet.publishAddPartnersRequests(SdkPollerServlet.java:101)

Comparison Failure:  <Click to see difference>

Argument(s) are different! Wanted:
customPublisher.publish(
    ,
    <any>
);
-> at com.w.sdkService.servlets.SdkPollerServlet_PublishTest.readFromSpreadsheet3Rows_shouldPublish2Times(SdkPollerServlet_PublishTest.java:75)
Actual invocation has different arguments:
customPublisher.publish(
    "partner {
  display_name: "WTest"
  android_pkg_name: "com.example.eliran.myapplication"
  sharing_mode: DATA
}
requestId: "3a7458b6-edc0-4d4e-b52e-d2a3847bef0b"
requestType: REMOVE
",
    com.w.sdkService.services.callback.PublisherCallbackWithLog@56f6d40b
);
-> at com.w.sdkService.servlets.SdkPollerServlet.publishAddPartnersRequests(SdkPollerServlet.java:101)

How should I verify the call otherwise?

Robolectric tests fails when I run them all

I've seen similar questions but I still can't fix it, so sorry for possible duplication.

I wrote some Roboletric tests for my activity. I can pass them all only if I directly run the whole class. But if I run the whole test pack - they fails.

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTest {
private MainActivity activity;

@Before
public void setUp() throws Exception {
    activity = Robolectric.buildActivity(MainActivity.class)
            .create()
            .resume()
            .get();
}

@Test
public void shouldNotBeNull() throws Exception {
    assertNotNull(activity);
}

@Test
public void shouldHaveCorrectAppName() throws Exception {
    String appName = activity.getResources().getString(R.string.app_name);
    assertThat(appName, equalTo("KeylessEntryFSM"));
}

Some examples. I also use Mockito tests, they works correct. I must run them all from a console.

How to upload a file/photo using katalon studio?

I'm trying to upload file using katalon studio for automation testing (web Testing. After clicking on 'Browse' button the windows popup is opened but i can't choose photo or go to specific path. I found a command WebUI.UploadFile() but I think I'm not using it correctly. If anyone had something like this , please share your experience. How could i do this in katalon ?

How to write test cases for ProcessBuilder

In past, I've written JUnit test cases for API, Services, functions.

1st time I'm working on some command line utility that will be run using Java ProcessBuilder.I'm confused how I'll write test cases for that.

For example, I'm working on ghost script to break PDF in multiple tiff files.

So How can I write test cases for this case?

visual studio WPT scripts

We get too many concurrency check issues in our visual studio WPT scripts.

What we have done :

1.Recorded the journey via fiddler due to webtest recorder not recording all the traffic. 2.exported the test .webtest file to visual studio and applied all standard extraction rules

Issue : Script works fine until certain transaction and fail after that due to concurrency check.there are too many concurrency check values and this is taking lot of time to fix this.did someone came across similar issue..??

Error in script :

“Store update, insert, or delete statement affected an unexpected number of rows (0).”

Can't run XML-file as TestNGSuite in Eclipse due java.io.FileNotFoundException

I'm new in Selenium WebDriver. Please help me to resolve a following issue. I created parameterizing tests in Selenium WebDriver with TestNG. Parameters were specified in XML-file. In tag was specified link "http://ift.tt/2uJYpFi". but, when this file was ran, i had caught java.io.FileNotFoundException due this link. Please, tip me whet's wrong with this link and what link i must specify to run my XML-file succesfully? Thanks.

Creating non-writable directory for unit tests

In order to unit-test a component which checks whether a directory is writable I would need to create a directory which isn't.

How can this be achieved since it is not predictable which permission rights the user to run the test has.

Test client for ternary tree

I want to test my ternary tree class, but I don't know why it always throw the emptyTreeException, can anyone help me to find out why? And here are my codes:

public class TernaryTree<T> implements TernaryTreeInterface<T>{
private TernaryNode<T> root;

public TernaryTree(){
    root = null;
}

public TernaryTree(T rootData){
    root = new TernaryNode<>(rootData);
}

public TernaryTree(T rootData, TernaryTree<T> leftTree, TernaryTree<T> middleTree, TernaryTree<T> rightTree){
    privateSetTree(rootData, leftTree, middleTree, rightTree);
}

public void setTree(T rootData){
    root = new TernaryNode<>(rootData);
}

public void setTree(T rootData, TernaryTreeInterface<T> leftTree, TernaryTreeInterface<T> middleTree,
                    TernaryTreeInterface<T> rightTree){
    privateSetTree(rootData, (TernaryTree<T>)leftTree, (TernaryTree<T>)middleTree,
                    (TernaryTree<T>)rightTree);
}

private void privateSetTree(T rootData, TernaryTree<T> leftTree, TernaryTree<T> middleTree,
                            TernaryTree<T> rightTree){
    root = new TernaryNode<>(rootData);
    if((leftTree != null) && !leftTree.isEmpty()){
        root.setLeftChild(leftTree.root);
    }
    if((middleTree != null) && !middleTree.isEmpty()){
        if(middleTree != leftTree && middleTree != rightTree){
            root.setMiddleChild(middleTree.root);
        }
        else if(middleTree == leftTree && middleTree == rightTree){
            root.setMiddleChild(middleTree.root.copy());
        }
    }
    if ((rightTree != null) && !rightTree.isEmpty()){
        if(rightTree != leftTree && rightTree != middleTree){
            root.setRightChild(rightTree.root);
        }
        else if(rightTree == leftTree && rightTree == middleTree){
            root.setRightChild(rightTree.root.copy());
        }
    }

    if ((leftTree != null) && (leftTree != this)) {
        leftTree.clear();
    }

    if ((middleTree != null) && (middleTree != this)){
        middleTree.clear();
    }

    if ((rightTree != null) && (rightTree != this)) {
        rightTree.clear();
    }
}

public T getRootData(){
    if(isEmpty()){
        throw new EmptyTreeException();
    } else{
        return root.getData();
    }
}

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

public void clear(){
    root = null;
}

protected void setRootData(T rootData) {
    root.setData(rootData);
}

protected void setRootNode(TernaryNode<T> rootNode) {
    root = rootNode;
}

protected TernaryNode<T> getRootNode() {
    return root;
}

public int getHeight(){
    int height = 0;
    if(!isEmpty()){
        height = root.getHeight();
    }
    return height;
}

public int getNumberOfNodes(){
    int numberOfNodes = 0;
    if(!isEmpty()){
        numberOfNodes = root.getNumberOfNodes();
    }
    return numberOfNodes;
}

public Iterator<T> getPreorderIterator() {
    return new PreorderIterator();
}

public Iterator<T> getInorderIterator() {
    throw new UnsupportedOperationException();
}

public Iterator<T> getPostorderIterator() {
    return new PostorderIterator();
}

public Iterator<T> getLevelOrderIterator() {
    return new LevelOrderIterator();
}

private class PreorderIterator implements Iterator<T> {
    private StackInterface<TernaryNode<T>> nodeStack;

    public PreorderIterator(){
        nodeStack = new LinkedStack<>();
        if (root != null){
            nodeStack.push(root);
        }
    }

    public boolean hasNext(){
        return !nodeStack.isEmpty();
    }

    public T next(){
        TernaryNode<T> nextNode;

        if(hasNext()){
            nextNode = nodeStack.pop();
            TernaryNode<T> leftChild = nextNode.getLeftChild();
            TernaryNode<T> middleChild = nextNode.getMiddleChild();
            TernaryNode<T> rightChild = nextNode.getRightChild();

            if(rightChild != null){
                nodeStack.push(rightChild);
            }

            if(middleChild != null){
                nodeStack.push(middleChild);
            }

            if (leftChild != null){
                nodeStack.push(leftChild);
            }
        }else{
            throw new NoSuchElementException();
        }

        return nextNode.getData();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

private class PostorderIterator implements Iterator<T> {
    private StackInterface<TernaryNode<T>> nodeStack;
    private TernaryNode<T> currentNode;

    public PostorderIterator(){
        nodeStack = new LinkedStack<>();
        currentNode = root;
    }

    public boolean hasNext(){
        return !nodeStack.isEmpty() || (currentNode != null);
    }

    public T next(){
        boolean foundNext = false;
        TernaryNode<T> leftChild, rightChild, nextNode = null;
        TernaryNode<T> middleChild = null;

        while (currentNode != null){
            nodeStack.push(currentNode);
            leftChild = currentNode.getLeftChild();
            if(leftChild == null && middleChild != null){
                currentNode = currentNode.getMiddleChild();
            }
            else if(leftChild == null && middleChild == null){
                currentNode = currentNode.getRightChild();
            } else{
                currentNode = leftChild;
            }
        }

        if (!nodeStack.isEmpty()) {
            nextNode = nodeStack.pop();

            TernaryNode<T> parent = null;
            if (!nodeStack.isEmpty()) {
                parent = nodeStack.peek();
                if (nextNode == parent.getLeftChild()) {
                    currentNode = parent.getMiddleChild();
                } 
                else if (nextNode == parent.getMiddleChild()){
                    currentNode = parent.getRightChild();
                }
                else{
                    currentNode = null;
                }
            } else {
                currentNode = null;
            }
        } else {
            throw new NoSuchElementException();
        }

        return nextNode.getData();
    }
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

private class LevelOrderIterator implements Iterator<T> {
    private QueueInterface<TernaryNode<T>> nodeQueue;

    public LevelOrderIterator() {
        nodeQueue = new LinkedQueue<>();
        if (root != null) {
            nodeQueue.enqueue(root);
        }
    }

    public boolean hasNext() {
        return !nodeQueue.isEmpty();
    }

    public T next() {
        TernaryNode<T> nextNode;

        if (hasNext()) {
            nextNode = nodeQueue.dequeue();
            TernaryNode<T> leftChild = nextNode.getLeftChild();
            TernaryNode<T> middleChild = nextNode.getMiddleChild();
            TernaryNode<T> rightChild = nextNode.getRightChild();

            // Add to queue in order of recursive calls
            if (leftChild != null) {
                nodeQueue.enqueue(leftChild);
            }

            if (middleChild != null){
                nodeQueue.enqueue(middleChild);
            }

            if (rightChild != null) {
                nodeQueue.enqueue(rightChild);
            }
        } else {
            throw new NoSuchElementException();
        }

        return nextNode.getData();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

}

class TernaryNode<T>{
private T data;
private TernaryNode<T> leftChild;
private TernaryNode<T> middleChild;
private TernaryNode<T> rightChild;

public TernaryNode(){
    this(null);
}

public TernaryNode(T dataPortion){
    this(dataPortion, null, null, null);
}

public TernaryNode(T dataPortion, TernaryNode<T> newLeftChild, TernaryNode<T> newMiddleChild,
                    TernaryNode<T> newRightChild){
    data = dataPortion;
    leftChild = newLeftChild;
    middleChild = newMiddleChild;
    rightChild = newRightChild;
}

public T getData(){
    return data;
}

public void setData(T newData){
    data = newData;
}

public TernaryNode<T> getLeftChild(){
    return leftChild;
}

public void setLeftChild(TernaryNode<T> newLeftChild){
    leftChild = newLeftChild;
}
public boolean hasLeftChild() {
    return leftChild != null;
}

public TernaryNode<T> getRightChild() {
    return rightChild;
}


public void setRightChild(TernaryNode<T> newRightChild) {
    rightChild = newRightChild;
}


public boolean hasRightChild() {
    return rightChild != null;
}

public TernaryNode<T> getMiddleChild(){
    return middleChild;
}

public void setMiddleChild(TernaryNode<T> newMiddleChild){
    middleChild = newMiddleChild;
}

public boolean hasMiddleChild(){
    return middleChild != null;
}


public boolean isLeaf() {
    return (leftChild == null) && (rightChild == null) && (middleChild == null);
}


public int getNumberOfNodes() {
    int leftNumber = 0;
    int rightNumber = 0;
    int middleNumber = 0;

    if (leftChild != null) {
        leftNumber = leftChild.getNumberOfNodes();
    }

    if (rightChild != null) {
        rightNumber = rightChild.getNumberOfNodes();
    }

    if (middleChild != null){
        middleNumber = middleChild.getNumberOfNodes();
    }

    return 1 + leftNumber + rightNumber + middleNumber;
}

/** Computes the height of the subtree rooted at this node.
 *  @return  The height of the subtree rooted at this node. */
public int getHeight() {
    return getHeight(this); // Call private getHeight
}

private int getHeight(TernaryNode<T> node) {
    int height = 0;

    if (node != null)
        height = 1 + Math.max(Math.max(getHeight(node.getLeftChild()), getHeight(node.getRightChild())),getHeight(node.getMiddleChild()));

    return height;
}

/** Copies the subtree rooted at this node.
 *  @return  The root of a copy of the subtree rooted at this node. */
public TernaryNode<T> copy() {
    TernaryNode<T> newRoot = new TernaryNode<>(data);

    if (leftChild != null) {
        newRoot.setLeftChild(leftChild.copy());
    }

    if (rightChild != null) {
        newRoot.setRightChild(rightChild.copy());
    }

    if (middleChild != null){
        newRoot.setMiddleChild(middleChild.copy());
    }

    return newRoot;
}

}

And here is my test method:

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    TernaryTree<String> aTree = new TernaryTree<>("A");
      TernaryTree<String> cTree = new TernaryTree<>("C");
      TernaryTree<String> eTree = new TernaryTree<>("E");
      TernaryTree<String> gTree = new TernaryTree<>("G");
      TernaryTree<String> bTree = new TernaryTree<>("B",aTree,cTree,eTree);
      TernaryTree<String> fTree = new TernaryTree<>("F",eTree,gTree,bTree);
      TernaryTree<String> dTree = new TernaryTree<>("D",bTree,fTree,gTree);


      System.out.println("root: " + bTree.getRootData());
      System.out.println("height: " + bTree.getHeight());
      System.out.println("total number of nodes: " + cTree.getNumberOfNodes());
      aTree.getLevelOrderIterator();
      aTree.getPreorderIterator();
      aTree.getPostorderIterator();
      //aTree.getInorderIterator();
}

}

So, I expect to test my post, pre, and levelorder iterator, and getRootData, getHeight, getNumberOfNodes. Somehow I encountered the emptyTreeException on the testing for getRootData, while I expect to return the root "B" for bTree. Can anyone help me? Thanks

samedi 29 juillet 2017

espresso test for all items recycler view and compare the value

Recyclerview of people, each item has name and age. I need to write the test to make sure that all items shown in the recyclerview have age less than 50.

I need a suggestion to write an espresso test for this scenario.

Unit Testing with Mocha Jade/Javascript

I have a jade file and corresponding javascript file. the Div elements are defined in jade file and i am using getElementById to access those element in javascript file dynamically. How should i write test cases ? In Mocha I am getting error like " Uncaught TypeError: Cannot set property 'innerHTML' of null"

behaviour of `property` of Chai: expect({x: {a: 1}}).to.have.property('x', {a: 1})

I have the following Chai + Mocha code, of which the results are very confusing me:

describe('Have Object Property', () => {
  it('should have the object property', () => {
    expect({x: {a: 1}}).to.have.property('x', {a: 1})
  })
  it('should have the property of an object property', () => {
    expect({x: {a: 1}}).to.have.property('x.a', 1)
  })
  it('should deeply have the object property', () => {
    expect({x: {a: 1}}).to.have.deep.property('x', {a: 1})
  })
  it('should deeply have the property of an object property', () => {
    expect({x: {a: 1}}).to.have.deep.property('x.a', 1)
  })
})

The results are:

Have Object Property
  1) should have the object property
  2) should have the property of an object property
  3) should deeply have the object property
  ✓ should deeply have the property of an object property


2 passing (53ms)
3 failing

  1) Have Object Property should have the object property:
     AssertionError: expected { x: { a: 1 } } to have a property 'x' of { a: 1 }, but got { a: 1 }
      at Context.<anonymous> (test/test.js:7:33)

  2) Have Object Property should have the property of an object property:
     AssertionError: expected { x: { a: 1 } } to have a property 'x.a'
      at Context.<anonymous> (test/test.js:10:33)

  3) Have Object Property should deeply have the object property:
     AssertionError: expected { x: { a: 1 } } to have a deep property 'x' of { a: 1 }, but got { a: 1 }
      at Context.<anonymous> (test/test.js:13:38)

In the four cases:

  1. why I cannot directly put {a: 1} as the value of property x?
  2. ...
  3. even for deep version, I cannot do this as well?
  4. only this is working, but this is really not as convenient and directly as the first case.

drive Karma tests with modules and inheritance

I have set up my project stack with Rollup, Babel and Gulp to code with ES2015 + stage-2

I have several modules exposing some default classes and I want using inheritance (extends)

It compiles OK, but The problem comes with tests : using Karma and Jasmine... How to tell the test runner to include to parent, the super-parent of a given class ?

Everything falls with the message

TypeError: Super expression must either be null or a function, not undefined

this means that parent classes are not loaded by the test runner...

// src/A.js
export default class A {}

// src/B.js
import A from  './A'

export class B extends A {} 

karma.config.js snippet :

 files: [
   'src/**/*.js',
   'test/**/*.js'
 ],

preprocessors: {
  'src/**/*.js': ['babel'],
  'test/**/*.js': ['babel']
},

babelPreprocessor: {
  options: {
  // babelrc: false,
    presets: ['es2015', 'stage-2'],
    sourceMap: 'inline',
    plugins: [
      ["transform-class-properties", { "spec": true }],
      ["transform-es2015-modules-umd"]
    ]
  }   

How to solve this case ?

Fail/Error in cordapp-template FlowTest progressTracker hasn't been started

when I try to run this tests for the flows in the cordapp-template:

@Test
fun flowRecordTransactionInBothVaults() {

    val flow = IOUFlow.Initiator(1,b.info.legalIdentity)
    val future = a.services.startFlow(flow).resultFuture
    net.runNetwork()
    val signedTx = future.getOrThrow()

    for (node in listOf(a,b)) {
        assertEquals(signedTx, node.storage.validatedTransactions.getTransaction(signedTx.id))
    }
}

I get this error: Progress tracker hasn't been started

[INFO ] 15:14:52.144 [Mock network] AbstractNetworkMapService.processRegistrationRequest - Added node CN=Mock Company 3,O=R3,L=New York,C=US to network map

[WARN ] 15:14:52.172 [Mock network] [a11087fc-381d-4547-8736-5265c334c71f].maybeWireUpProgressTracking - ProgressTracker has not been started

[WARN ] 15:14:52.191 [Mock network] [0dcfa270-b1af-40e9-92f1-411334cf0c73].run - Terminated by unexpected exceptionkotlin.NotImplementedError: An operation is not implemented: not implemented
at com.template.flow.IOUFlow$Acceptor$call$1.checkTransaction(TemplateFlow.kt:225) ~[main/:?] 

at net.corda.flows.SignTransactionFlow.call(CollectSignaturesFlow.kt:201) ~[corda-core-0.13.0.jar:?]
at net.corda.flows.SignTransactionFlow.call(CollectSignaturesFlow.kt:177) ~[corda-core-0.13.0.jar:?]

[WARN ] 15:14:52.202 [Mock network] [a11087fc-381d-4547-8736-5265c334c71f].run - Terminated by unexpected exceptionnet.corda.core.flows.FlowSessionException: Counterparty flow on CN=Mock Company 3,O=R3,L=New York,C=US had an internal error and has terminated
at net.corda.node.services.statemachine.FlowStateMachineImpl.erroredEnd(FlowStateMachineImpl.kt:382) ~[corda-node

[WARN ] 15:14:52.203 [Mock network] [a11087fc-381d-4547-8736-5265c334c71f].uncaughtException - Caught exception from flowjava.lang.IllegalStateException: Progress tracker has already ended
at net.corda.core.utilities.ProgressTracker.endWithError

Actually the code is much longer but I think these are the relevant parts. Is it a known thing? How can I fix it?

How to create a Web Application from scratch using BDD?

I want to start a pet project to get confident with creating Web Applications from scratch and I want to use BDD and TDD. I read in "Growing Object-Oriented Software: Guided by Tests" that we should start from the thinnest slice of the system that allows us to have a walking skeleton of the entire application so we have can have a quick feedback and start wondering about the production/deployment procedures.

After writing the acceptance test in BDD I would move to finer granularity tests such as Unit tests.

Imagining that the web application is about finding the superhero who is more similar to you, I would write a BDD scenario such as:

When I insert my information
Then the system should tell that the superhero I'm more similar to is "Batman"

I'm ignoring the authentication on purpose so we can focus on the main functionality of the system. This scenario assumes that there is a working infrastructure behind, so that the scenario above can be replicated automatically, end-to-end.

Assuming that I want to lay out the web application in different layers (Web Server, Application Server and Database), how can I implement this test? Supposing I want to use Selenium WebDriver to simulate the user, what layers must be mocked and what layer is going to be tested first? I also thought about starting from testing the API only, but that wouldn't be a end-to-end test, but we would test the application only partially.

Codewars Snail Test Wrong or Code Wrong?

I think I have a pretty cool solution to this codewars challenge but I am failing the last test because it is adding an extra 1 to the beginning of my array and I don't know why! In IRB my code seems to work fine.

@arr = []

def snail(array)
  array.to_a.empty? ? (return @arr.flatten) : @arr << array.shift
  snail(array.transpose.reverse)
end

When snail([[4, 5, 6], [7, 8, 9]]) expected [1, 2, 3, 6, 9, 8, 7, 4, 5] but got [1, 1, 2, 3, 6, 9, 8, 7, 4, 5]

vendredi 28 juillet 2017

Typescript, tests and debugging in VS Code

I am new to angular2 and typescript and have made a simple application which was generated with the angular CLI. Before I go on, I have to say that there is a gap in my understanding of what happens between seeing typescript code in VS Code and a running app in the browser.

In previous editors, I was used to seeing .js files generated and made sense of my running application as a web page with those generated files. But when one runs ng serve there are no .js files anywhere and the app still runs in the browser. The first thing I want to know is how that happens- I thought typescript was not readable by browsers.

Secondly, I am having trouble debugging unit tests in the Karma test runner using VS Code. I am able to debug the application itself, I am able to attach the debugger to the Karma instance, but when I put a breakpoint in my test I get the error breakpoint ignored because generated code not found (source map problem?). For reference this is my launch.json:

    {
        "type": "chrome",
        "request": "attach",
        "name": "Attach Karma Chrome",
        "address": "127.0.0.1",
        "port": 9333,
        "sourceMaps": true,
        "webRoot": "${workspaceRoot}"
    }

and my karma.conf.js contains

browsers: ['ChromeDebugging'],
customLaunchers : {
  ChromeDebugging: {
    base: 'Chrome',
    flags: ['--remote-debugging-port=9333']
  }
},

Haskell testing user input with Hspec

I have a program that takes a user input from getLine then validates that it is all numbers. If it passes it runs a function of String -> String and prints the result to screen. If not it repeats the getLine.

module Main where

import Control.Monad.Loops (untilJust)
import Data.Char           (isDigit)

main = do
  let validateInput s = if all isDigit s then Just s else Nothing
  putStrLn =<< myFunc <$> untilJust (validateInput <$> (putStr "Number : " >> getLine))

myFunc = id -- to do

How do I test the this main function with something like Hspec to check that it does the right thing with a number input vs other inputs (letters, empty etc)

ie

test1 rejects a non-numeric input of "abc"
test2 returns 123 as 123

NUnit - Running specific test case using testcase attribute through command line

I want to run the below test case through nunit console using command line.`

class ListCities : Test.HelperClasses.Testbase
    {
 [TestCase(Category="smoke",TestName = "TC1", Description = "dessciption")]
        public void SearchCity()
        {
        }
   }`

I tried the command --test=Test.HelperClasses.Testbase.ListCities.TC1. But i want to execute the test using only testname(TC1) attribute and not along with the namespace(Test.HelperClasses.Testbase) and class name(ListCities).

Below is the pyhton code to execute the test case using nunit console os.system("Call "+NunitPath+" "+dllPath+" -- test=Test.HelperClasses.Testbase.ListCities.TC1 --result="+resultPath)

Thanks in advance

error while installing robot framework on ironpython

I'm becoming mad about installing robotframework on IronPython in a Windows machine. Please someone could take a look on this.

I have installed IronPython 2.7.7, added the path system variable for both main and Scripts folder, also I installed the elementtree-1.2.7-20070827-preview.zip as it looks that the library that comes with IronPython is "broken" (this info and instruction comes from IronPython site).

Then I run the

    ipy -X:Frames -m ensurepip 

to be able to use pip.

Everything should be ready now to get the robotframework installed by:

    ipy -X:Frames -m pip install robotframework

The package starts getting downloaded until here:

  Complete output from command python setup.py egg_info:
  Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\setuptools\__init__.py", line 11, in <module>
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\setuptools\extern\__init__.py", line 1, in <module>
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\__init__.py", line 46, in <module>
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\extern\__init__.py", line 42, in load_module
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\_vendor\six.py", line 701, in <module>
  File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\_vendor\six.py", line 692, in exec_
  AttributeError: 'module' object has no attribute '_getframe'

----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in c:\users\***\appdata\local\temp\pip-build-vnlada\robotframework\

I tried another workaround just downloading the robotframework source, uncompressing and placing it in my program folders. From the RF folder I tried to run:

    C:\Program Files (x86)\IronPython 2.7\ipy.exe" setup.py install

and again same error:

     File "setup.py", line 11, in <module>
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-                  packages\setuptools\__init__.py", line 11, in <module>
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\setuptools\extern\__init__.py", line 1, in <module>
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\__init__.py", line 46, in <module>
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\extern\__init__.py", line 42, in load_module
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\_vendor\six.py", line 701, in <module>
       File "C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\pkg_resources\_vendor\six.py", line 692, in exec_
     AttributeError: 'module' object has no attribute '_getframe'

In this website this guy solves the issue using this last workaround, however it didnt work for me. http://ift.tt/1N5mLwV

Thank you in advance.

MongoDB/Mongoose: embedded document update verification

How do I verify/test that on a mongoose, document update call, my embedded documents are not being duplicated?

I'm using Mongoose, sinon, mocha and chai. I have a document that contains an embedded document, and both are created from external data that is pulled at regular intervals.

Format is similar to:

{
  title: testingTitle,
  flag: true,
  color: orange,
  list: [{
      name: testName,
      status: overdue
  },
  {
      name: otherTestName,
      status: due,
  }]
}

I have two separate Schemas. Format similar to this:

let embeddedSchema = new mongoose.Schema({
     name: {type: String, required: true},
     staus: {type: String, required: true}
     createdAt: {type: Date, default: moment}
});

let mainSchema = new mongoose.Schema({
      title: {type: String, required: true},
      flag: {type: String, defualt: null},
      color: {type: Object, defualt: null},
      list: [embeddedSchema]
})

It seems that this works. When I run my logic (which calls update if the main document already exists) it doesn't appear to duplicate any of the sublist items. Unfortunately the way the system is set up it's difficult to fully verify that truth.

  1. Is there anything blatantly wrong with this set up? My main concern is that every item in the list could potentially be duplicated, instead of updated on changes, because there is no uniqueID to connect them to the previously stored items.
  2. How would I go about testing this using sinon?

How to apply TDD with complicated function?

Uncle Bob's three rules of test-driven development state the following:

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.

  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

In real world, for example, I have a task to complete a method which requires some complex algorithms (some advanced math knowledge for example), if I apply 3 above rules, it will be like this:

  • start writing a test case => run and see it fails

  • write lines of code that just enough to make the test pass

  • refactor the code

  • then repeat this loop.

My question is: is this approach quite unrealistic and distracted in such situations? Why don't we write the first test case, then focus on finding the solution then implement it, I mean looking at the big picture, instead of writing just enough code to pass the first test case?

(I am a new with TDD)

Opensource tool for database table comparision

Is there any open source tool which can compare tables from two different databases like mssqlserver and Greenplum, which can be used for testing purpose.

Maven build not failing when gherkin tests fails

I have a maven project which executes some Gherkin files to do some tests, but when some of these tests fails maven doesn't care and succesfully complete the build.

My configuration is like:

public class AppStepDefs extends AppSpringIntegrationTest {

    @Autowired
    ContentServiceMock contentMock;
    @Autowired
    FileStorageServiceMock fileStorageMock;

    @Given("^following stuff are stored in content service$")
    public void given_following_stuff(DataTable dataTable) {
        dataTable.asMaps(String.class, String.class)
            .stream()
            .map(StuffConverter::fromDataTableRow)
            .forEach(stuff -> contentMock.insert(stuff.get("id").toString(), stuff));
    }

    //...all the other steps
}

Then my AppSpringIntegrationTests:

@ContextConfiguration(
    classes = AppFunctionalTestConfiguration.class,
    loader = SpringApplicationContextLoader.class
)
@IntegrationTest
public class AppSpringIntegrationTest {
      @Bean
      public FileStorageService fileStorageClient() {
         return new FileStorageServiceMock();
      }
      //...all the other beans
}

And then the cucumber configuration class:

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/resources/functional/features",
    format = {"pretty", "html:target/cucumber"}
)
public class CucumberTest {
}

All the tests get executed but when they fail:

 Failed scenarios:
 cucumber_conf.feature:12 # Scenario: Test creation with stuff

 22 Scenarios (1 failed, 21 passed)
 65 Steps (1 failed, 64 passed)
 0m12,586s

 Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.866 sec - in TestSuite

 Results :

 Tests run: 10, Failures: 0, Errors: 0, Skipped: 0

 [INFO] ------------------------------------------------------------------------
 [INFO] Reactor Summary:
 [INFO] 
 [INFO] StuffService Parent ............ SUCCESS [  1.012 s]
 [INFO] StuffService ................... SUCCESS [ 22.588 s]
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD SUCCESS
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 32.992 s
 [INFO] Finished at: 2017-07-28T14:46:35+02:00
 [INFO] Final Memory: 60M/419M
 [INFO] ------------------------------------------------------------------------

Maven failure on spring boot test (junit 5)

Is it possible to run spring boot tests with junit 5 using maven? I'm using spring boot 2.0.0.M3, junit 5.0.0-M6, maven 3.5.0. Other junit5 tests (without spring context) works.

There is simple controller:

@Controller
public class HomeController {
    @GetMapping("/")
    String home() {
        return "home";
    }
}

and test:

@ExtendWith(SpringExtension.class)
@WebMvcTest(HomeController.class)
@Import(SecurityConfig.class)
class HomeControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void shouldReturnHomeTemplate() throws Exception {
        this.mvc.perform(get("/").accept(MediaType.TEXT_HTML))
            .andExpect(status().isOk())
            .andExpect(content().string(startsWith("<!DOCTYPE html>")));
    }
}

Everything works when I run it using intellij, but maven build ends with failure:

[WARNING] Corrupted stdin stream in forked JVM 1. See the dump file somePath/target/surefire-reports/2017-07-28T13-50-15_071-jvmRun1.dumpstream

--debug flag shows:

java.lang.OutOfMemoryError: Java heap space

Inside 2017-07-28T13-50-15_071-jvmRun1.dumpstream I can find ~100 same exceptions (one per spring log):

Corrupted stdin stream in forked JVM 1. Stream '13:50:15.914 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]'.
java.lang.IllegalArgumentException: Stream stdin corrupted. Expected comma after third character in command '13:50:15.914 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]'.
at org.apache.maven.plugin.surefire.booterclient.output.ForkClient$OperationalData.<init>(ForkClient.java:469)
at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.processLine(ForkClient.java:191)
at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.consumeLine(ForkClient.java:158)
at org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer$Pumper.run(ThreadedStreamConsumer.java:87)
at java.lang.Thread.run(Thread.java:745)

Testing Service from RestController by calling it multiple times simultaneously(Load Testing i mean for multi user)

I want to test My RestApi for multi user concurrency.Is there any way other than Jmeter,Load Runner? I mean i want to test like Junit not with any tool.I have tried using Multithreading but its not working.I am new to multithreading concept too .I just want to call my service from restController mutliple times simultaneously and check response.

Gradle build fails with "String Index out of range" when Android Tests Fail

I am experiencing a problem when trying to do instrumentation tests with Android. When one of the tests fails, the build fails, but doesn't state that the test failed. Instead I get FAILURE: Build failed with an exception. For the what went wrong section, I get String index out of range: -1.

In my real app, this is causing it to not generate a html report either, and the xml report is sporadically generated. I have put together a simple test case, but it is generating the report, but otherwise giving the same failure message.

Here is the very simple test app

build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.4.0-alpha7'
    }
}

apply plugin: 'com.android.application'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    androidTestCompile "com.android.support.test.espresso:espresso-core:2.2.2"
    androidTestCompile "com.android.support.test.espresso:espresso-intents:2.2.2"
    androidTestCompile "com.android.support.test:runner:0.5"
}

android {
    compileSdkVersion 24
    buildToolsVersion '25.0.2'

    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8 
    }

    buildTypes {        
        release {
            minifyEnabled true
            proguardFile getDefaultProguardFile('proguard-android.txt')
        }
    }
}

src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
      package="com.test.bad"
      android:versionCode="1"
      android:versionName="1">
    <uses-sdk android:minSdkVersion="24" android:targetSdkVersion="24" />     
    <application android:label="bad">
        <activity android:name="BadTestActivity" android:label="bad">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

src/main/java/test/bad/BadTestActivity.java

package com.test.bad;

import android.app.Activity;
import android.os.Bundle;

public class BadTestActivity extends Activity {

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

src/androidTest/java/com/test/bad/BadTest.java

package com.test.bad;

import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.fail;
import android.support.test.runner.AndroidJUnit4;

@RunWith(AndroidJUnit4.class)
public class BadTest {

    @Test
    public void failTest() {
        fail("This test just fails");
    }

}

When I run gradle connectedAndroidTest, I see

:connectedDebugAndroidTest

FAILURE: Build failed with an exception.

* What went wrong:
String index out of range: -1

* Try:
Run with --stacktrace option to get the stack trace.  Run with --info or --debug 
option to get more log output.

I would expect that to give some message about the build failing because of a failed test instead of something strange like that string index. In my real application (which also uses Kotlin and Mockito in tests) the report html is not always generated (there are many more tests, and I think that has something to do with the lack of a report).

Using --info or --debug doesn't seem to show anything useful, but using --stacktrace shows

* Exception is:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput$StateContext.flushLineText(AbstractLineChoppingStyledTextOutput.java:115)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput$2.execute(AbstractLineChoppingStyledTextOutput.java:167)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput$2.execute(AbstractLineChoppingStyledTextOutput.java:160)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput$1.execute(AbstractLineChoppingStyledTextOutput.java:146)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput$1.execute(AbstractLineChoppingStyledTextOutput.java:131)
    at org.gradle.internal.logging.text.AbstractLineChoppingStyledTextOutput.doAppend(AbstractLineChoppingStyledTextOutput.java:41)
    at org.gradle.internal.logging.text.AbstractStyledTextOutput.text(AbstractStyledTextOutput.java:73)
    at org.gradle.internal.logging.text.AbstractStyledTextOutput.println(AbstractStyledTextOutput.java:68)
    at org.gradle.internal.logging.events.LogEvent.render(LogEvent.java:48)
    at org.gradle.internal.logging.console.StyledTextOutputBackedRenderer.onOutput(StyledTextOutputBackedRenderer.java:65)
    at org.gradle.internal.logging.sink.ProgressLogEventGenerator.doOutput(ProgressLogEventGenerator.java:72)
    at org.gradle.internal.logging.sink.ProgressLogEventGenerator.onOutput(ProgressLogEventGenerator.java:62)
    at org.gradle.internal.logging.console.BuildLogLevelFilterRenderer.onOutput(BuildLogLevelFilterRenderer.java:42)
    at org.gradle.internal.logging.sink.OutputEventRenderer$4.onOutput(OutputEventRenderer.java:265)
    at org.gradle.internal.logging.sink.OutputEventRenderer$LazyListener.onOutput(OutputEventRenderer.java:368)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy0.onOutput(Unknown Source)
    at org.gradle.internal.logging.sink.OutputEventRenderer.onOutput(OutputEventRenderer.java:334)
    at org.gradle.launcher.daemon.client.DaemonClient.monitorBuild(DaemonClient.java:216)
    at org.gradle.launcher.daemon.client.DaemonClient.executeBuild(DaemonClient.java:178)
    at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:141)
    at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:92)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:287)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:260)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:33)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:253)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:182)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:60)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:37)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)

I am using Windows 7, with Gradle 4.0 (the problem exists with 3.5 as well) and Java 8.

What is causing this error message? Is this what I should see?

How to include plugin in maven for test build only?

I want to add the plugin in the maven project. I want it to be added to build only when I build the project for testing purpose.

I found that <scope> can be used for dependency as shown below

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback</artifactId>
  <version>0.5</version>
  <scope>test</scope>
</dependency>

As you can see here <scope>test</scope>is used.

I want similar thing for plugin. For example this is my plugin code snipplet

   <build>
        <plugins>
            <plugin>
                <groupId>org.jibx</groupId>
                <artifactId>jibx-maven-plugin</artifactId>
                <version>1.2.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>bind</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

jeudi 27 juillet 2017

How to do automation testing using Python? what are the tools needed for it?

I have learned the python and I'm the tester. So I would like to do automation using Python. So I need a clarification on what are the software need to install

Cannot simulate click on jest test

I'm learning some react + testing with jest, I have a component which has three numeric inputs and a button. It's a simple calculator with the multiply operation only.

Don't worry about the rest of the code, I'm just trying to simulate the click that performs the operation (in this case it will call a mocked function as shown in the test)

This is the test

function setup() {
    const component = shallow(<Multiplier />);

    return {
       component: component,
       button: component.find('#multiplyButton')
    }
}

describe('Given a Multiplier instantiated', () => {
   it('The button perform operation should invoke the click method', () => {
       const { button } = setup();
       const handleClick = jest.fn();
       button.onclick = handleClick;
       button.simulate('onClick');
       expect(handleClick).toBeCalled();
   });
});

I think the button.onclick assignment is wrong, I tried with prototype and ecma6 Object.assign but it was the same result, the test fails.

I mocked the onclick button with jest.fn(), once the button is pressed it should call this method, but it's always telling me:

Given a Multiplier instantiated › The button perform operation should invoke the click method expect(jest.fn()).toBeCalled()

Any ideas on how to solve this?

Selenoid: recording video of a running session

I'm using Selenoid live browser screen functionality to debug my tests. What is the recommended way to capture browser screen video?

Test cases for Binary Search Tree (BST) remove function using linked lists C++

Question: What test cases should I use to test the remove function?

My Thoughts:

case 1: delete when no element is in the system.

case 2: delete when there is only one element in the system.

case 3: delete when the left side of the tree is empty.

case 4: delete when the right side of the tree is empty.

Predefined mock response in Spock

I'm new to Spock and this question refers to the example on page 178 of Java Testing with Spock. The class under test is the Basket class for a shopping application, and the method of this class being tested is canShipCompletely()

public class Basket {
  private WarehouseIneventory warehouseInventory;
  private ShippingCalculator shippingCalculator;
  protected Map<Product, Integer> contents = new HashMap<>();
  ...

  public void addProduct(Product product) {
    addProduct(product, 1);
  }

  public void addProduct(Product product, int times) {
    if (contents.containsKey(product)) {
      int existing = contents.get(product);
      contents.put(product, existing + times);
    } else {
      contents.put(product, times);
    }
  }

  public Boolean canshipCompletely() {
    if(warehouseInventory.isEmpty()) return false;

    try {
      for (Entry<Product, Integer> entry : contents.entrySet()) 
        boolean ok = warehouseInventory.isProductAvailable(
                                  entry.getKey().getName(), 
                                  entry.getValue()
                                  );
        if (!ok) {
          return false;
        }
    }
      return true;
    } catch (Exception e) {
      return false;
    }

  ...
}

This method canShipCompletely() loops over the items in the basket (in Map contents) and for each item, it makes a call to warehouseInventory.isProductAvailable(product, count) to see if there is sufficient stock in the warehouse to fill the order. The Warehouse class is a collaborator of the Basket class that is mocked in the following test

def "Warehouse is queried for each product"() {
    given: "a basket, a TV and a camera"
    Product tv = new Product(name:"bravia",price:1200,weight:18)
    Product camera = new Product(name:"panasonic",price:350,weight:2)
    Basket basket = new Basket()

    and: "a warehouse with limitless stock"
    WarehouseInventory inventory = Mock(WarehouseInventory)
    basket.setWarehouseInventory(inventory)

    when: "user checks out two products"
    basket.addProduct tv
    basket.addProduct camera
    boolean readyToShip = basket.canShipCompletely()

    then: "order can be shipped"
    readyToShip
    2 * inventory.isProductAvailable( _ , _) >> true
    0 * inventory.preload(_ , _)
}

The then: block verifies the boolean readyToShip is true, and that inventory.isProducAvailable() was called twice and inventory.preload() was not called at all. The next to last line is both checking behavior of the mock and telling it to return true for calls to isProductAvailable(). What I don't understand is the test will fail if I move the mock predefined response to the and: block as follows

def "Warehouse is queried for each product"() {
    given: "a basket, a TV and a camera"
    Product tv = new Product(name:"bravia",price:1200,weight:18)
    Product camera = new Product(name:"panasonic",price:350,weight:2)
    Basket basket = new Basket()

    and: "a warehouse with limitless stock"
    WarehouseInventory inventory = Mock(WarehouseInventory)

    // ******** Move mock predefined response here  **********
    inventory.isProductAvailable( _ , _ ) >> true         
    basket.setWarehouseInventory(inventory)

    when: "user checks out two products"
    basket.addProduct tv
    basket.addProduct camera
    boolean readyToShip = basket.canShipCompletely()

    then: "order can be shipped"
    readyToShip
    2 * inventory.isProductAvailable( _ , _)
    0 * inventory.preload(_ , _)
}

The failure I get is too few calls to isProductAvailable():

Too few invocations for:

2 * inventory.isProductAvailable( _ , _) (1 invocation)

Unmatched invocations (ordered by similarity):

1 * inventory.isEmpty()

I don't understand why the predefined behavior for the mock can't be moved to the and: block.

Android Flavor Testing .R-file

I have a problem with the .R-files of an app with 2 flavors: "main" and "flavor1"

In "main" there is the common codebase. In "flavor1" there is some flavor-specific implementation.

and I have 2 test directories: androidTest (package org.myapp.test) androidTestFlavor1 (package org.myapp.flavor1.test)

In androidTest there is the common test codebase including resource files. In androidTestFlavor1 there are only tests specific to this flavor.

Now, I have the problem that when I execute the tests in androidTestFlavor1, Android Studio complains that it cannot find the .R-file of the common test codebase (which is imported and used only in the androidTest-directory) - "cannot resolve symbol R".

Obviously, the file org.myapp.test.R was not generated. Only org.myapp.flavor1.test.R was generated. Why is there only one .R-file generated? I thought the .R-file in the common directory should always be generated?

mvn install test does not execute test

when the command mvn install test is executed it does not execute the test but it hangs saying Listening for transport dt_socket at address: 5005

looking for help on this problem

Does the value of unit tests decrease with the complexity of the unit test?

I'm at the point where I should write a unit test for the complex algorithm that my function does perform. The function takes two mandatory arguments at invocation. Based on the combination of both arguments the function does return something.

function ReturnDesiredParagraphStyle(currParagraphStyle, nextParagraphStyle) 
{
    // logic
}

Now the problem is, to test any combination of inputs and the correctness of the desired output of the function I have to write a complex logic within the unit test, because there are so many possible inputs (approximately 50 for each argument). The complex logic would be a loop with the purpose that I do not have to type each combination of inputs manually in the unit test.

I do understand that most of the time to write this unit-test will provide an layer of safety, but doesen't it lead the concept of unit testing a bit ad absurdum (because the logic in the unit test will be so complex and nothing tests the logic in the unit test)?

What should I do to test React app

currently I already finished my React project, but my supervisor needs to test with this instructions :

Tests are an essential part of our software engineering practices here and we’ll like you to include them as part of your submission.

I do not know what kind of test he want, but after I do some research, I got something related with Jest, and create a simple Jest code to test my react app this is the code : import React from 'react'; i

import ReactDOM from 'react-dom';
import AppDashBoard from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<AppDashBoard />, div);
});

and the result are written in my terminal like this:

> jest

 PASS  src/App.test.js
 PASS  src/test/Link.test.js

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   3 passed, 3 total

. So my questions : 1) Is this code is sufficient for submission as the instructions above ? 2) Which one I should submit to my supervisor ? Is it the code itself, or just a screeshot of the PASS message ? 3) I encounter a problem when I use npm test as Jest, the Jest cannot recognise my App's css file. The message error is pointing to the "." full stop when set the style of a class? Any idea ?

Thank you

What should I name my fixture file for a model with the name Mls

I have an activerecord model Mls in the directory app/models/mls.rb.

I have the corresponding fixture in test/fixtures/mls.rb.

When I run rails test I receive the error:

ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

The error is a little misleading, it is actually caused by the model not being found (http://ift.tt/2uGBwB0).

Naming the fixture mls.yml causes rails to look for the model file named ml.rb.

When I run Mls.name.underscore.pluralize I get "Mls" as the response. When I run "Mls.name.pluralize.singularize" I get "Ml" as the response.

It seems my only choice is rename my model but possibly there is another solution?

Permission denied : While setting classpath to run testng.xml

Friends I am trying to run the testng.xml on my Linux environment , Getting below issues , I have given root access still not working.

[root@ip-172-31-2-246 website ]# sudo java -version openjdk version "1.8.0_131"

OpenJDK Runtime Environment (build 1.8.0_131-b11)

OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

bash: allJarFiles/apache-mime4j-0.6.jar: Permission denied [root@ip-172-31-2-246 website ]# ls -ltr total 230324 drwxrwxrwx 6 jenkins jenkins 4096 Jul 25 13:52 bin

drwxrwxrwx 2 jenkins jenkins 4096 Jul 25 13:52 utility

drwxrwxrwx 7 jenkins jenkins 4096 Jul 25 13:52 src

drwxrwxrwx 2 jenkins jenkins 4096 Jul 25 14:44 allJarFiles

-rw-r--r-- 1 jenkins jenkins 1178 Jul 25 14:44 testng.xml

-rw-r--r-- 1 jenkins jenkins 144 Jul 25 14:44 bash.sh

drwxrwxrwx 2 jenkins jenkins 4096 Jul 26 07:14 inputFiles

[root@ip-172-31-2-246 website ]# set classpath= /var/lib/jenkins/workspace/WebSite/bin;

[root@ip-172-31-2-246 website ]# set classpath= /var/lib/jenkins/workspace/allJarFiles/*;

[root@ip-172-31-2-246 website]# java org.testng.TestNG testng.xml Error: Could not find or load main class org.testng.TestNG

[root@ip-172-31-2-246 website ]# sudo java org.testng.TestNG testng.xml Error: Could not find or load main class org.testng.TestNG

[root@ip-172-31-2-246 website ]# set classpath=/var/lib/jenkins/workspace/allJarFiles/*;

[root@ip-172-31-2-246 website ]# set classpath=/var/lib/jenkins/workspace/bin;

[root@ip-172-31-2-246 website ]# java org.testng.TestNG testng.xml

Error: Could not find or load main class org.testng.TestNG

[root@ip-172-31-2-246 website ]# set classpath=/var/lib/jenkins/workspace/bin;/var/lib/jenkins/workspace/allJarFiles/*;

bash: /var/lib/jenkins/workspace/allJarFiles/apache-mime4j-0.6.jar: Permission denied [root@ip-172-31-2-246 website ]#

PHP: How to test an ORM against multiple database systems

If one is going to build an ORM in PHP by himself, how would one properly test it against multiple database systems?

I know, this question requires a long answer... I ask that because my team will need to implement one by itself and I am very curious.

So I am thinking of an ORM that provides multiple database drivers (like Doctrine):

  1. MySQL
  2. PostgreSQL
  3. Informix
  4. ...

Each driver should provide a querybuilder who generates Queries that are parsable by its underlying database system.

As that is, i think an ORM should always test all capabilities (associations, inheritance, what else, ..) with all possible (or currently implemented) drivers.

I already took a look how Doctrine does that with PHPUnit, but it seems they don't test their ORM like that... see here: phpunit.xml.dist on github

Well, of course they test their ORM against multiple database systems, but apparently not automatically..!?

So how would such an automatic "testsuite" look like, that tests against multiple database systems?


One Example

Using PHPUnit (and DBUnit indeed) I can currently only think of something like this...

phpunit.xml would look this:

<phpunit bootstrap="buildUpDBConnections.php">
....
</phpunit>

So the phpunit.xml does not provide any db settings, but executes a script (buildUpDBConnections.php), that sets up all database connections.

I think this connections then must somehow be publicly available as a collection, which is injected in all tests that should execute queries.

And before running the tests, this script prepares the fixtures for each database.

And then each test runs its queries against all connections. so a test is only successful, if the queries were executed correctly for all database systems.

Is this "concept" actually correct? are there more practical ways?

Can't enable codeception tests for Yii2

I have problems configuring Codeception acceptance tests for my Yii2 website.

Tests are running okay, but I'd like to change the configuration so testing contact form won't send any emails. It should be pretty simple task, but I can't force it to use alternative config.

Following this tutorial: http://ift.tt/2dCMwYZ

/codeception.yml:

actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    memory_limit: 1024M
    colors: true
modules:
    config:
        Yii2:
            configFile: 'config/test.php'

/tests/acceptance.suite.yml

class_name: AcceptanceTester
modules:
    enabled:
        - WebDriver:
            url: http://localhost/mypage
            browser: firefox
        - Yii2:
            part: orm
            entryScript: index.php
            cleanup: false
            configFile: test.php

And again I have no idea which directory this file points to. I tried with /config/test.php, /tests/config/test.php, nothing.

/config/test.php

<?php
$params = require(__DIR__ . '/params.php');
$dbParams = require(__DIR__ . '/test_db.php');

/**
 * Application configuration shared by all test types
 */
return [
    'id' => 'basic-tests',
    'basePath' => dirname(__DIR__),    
    'language' => 'en-US',
    'components' => [
        'db' => $dbParams,
        'mailer' => [
            'useFileTransport' => true, // <--- I'm interested in this setting 
        ],
        'urlManager' => [
            'showScriptName' => true,
        ],
        'user' => [
            'identityClass' => 'app\models\User',
        ],        
        'request' => [
            'cookieValidationKey' => 'test',
            'enableCsrfValidation' => false,
            // but if you absolutely need it set cookie domain to localhost
            /*
            'csrfCookie' => [
                'domain' => 'localhost',
            ],
            */
        ],        
    ],
    'params' => $params,
];

I even thought that this path might be relative to /tests directory, so I created file there as well:

/tests/config/test.php

<?php
// config/test.php
$config =  yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/main.php'),
    require(__DIR__ . '/main-local.php'),
    [
        'id' => 'app-tests',
        'components' => [
            'db' => [
                'dsn' => 'mysql:host=localhost;dbname=yii_app_test',
            ],
            'mailer' => [
                'useFileTransport' => true
            ]
        ]
    ]
);
return $config;

/tests/_bootstrap.php

<?php
define('YII_ENV', 'test');
defined('YII_DEBUG') or define('YII_DEBUG', true);

require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
require __DIR__ .'/../vendor/autoload.php';

part of /config/web.php to check if environment values are passed, but they aren't

if (YII_ENV_TEST || YII_ENV === 'test'){
    die('Testing settings loaded');
}

Launching my tests with ./vendor/bin/codecept run tests/acceptance/ContactCest.php

I'm not publishing tests because they are irrelevant, as they just use clicks on elements to send contact form. At the moment I've wasted 4 hours trying to override that config file. Probably it's some stupid rookie mistake, but I'm about to give up now.

Help me, StackOverflow, you are my only hope! ;)

NoMethodError Ruby MiniTest

I am trying to get started with Minitest. I get the following error:

Please Enter your Weight in lbs: 250
Please Enter your Height in cm: 190
You have a BMI of 31.41 
bmicalc_test.rb:4:in `<main>': private method `test' called for 
MiniTest:Module (NoMethodError)

This is my main code file:

class BmiCalc

    def initialize(weight, height)
        @weight = weight;
        @height = height;
    end

    def bmi
        kgweight = @weight * 0.4535;
        meterheight = @height * 0.01;
        bmivalue = kgweight/(meterheight * meterheight);
        return bmivalue;
    end

end

print "Please Enter your Weight in lbs: ";
weight = gets.to_f;

print "Please Enter your Height in cm: ";
height = gets.to_f;

bmiCalc = BmiCalc.new(weight, height);
answer = bmiCalc.bmi;

printf("You have a BMI of #{'%.2f' % answer} \n");

This is my MiniTest file:

require 'minitest/autorun'
require_relative "bmicalc.rb"

class TestBmi < Minitest::test

    def setup
        @bmicalc = BmiCalc.new(190, 250);
    end

    def test_answers
        assert_equal 31.40581717451523, @bmicalc.bmi;
    end

end

Firstly, I don't understand why it asks for input from me when I call this in the test file. I am instantiation a sample class already so why does it ask for input.

Secondly, I am not sure I understand the error or the nature of it. I am trying to follow this tutorial: http://ift.tt/1APaSmR

How to share setup method across multiple tests

I have a pretty big setup() method that sets up a lot of conditions that I need to test across two of my specs. Instead of copy pasting the same setup method in two different specs, I would like the same setup() method to be shared between the two specs.

I noticed that Spock offers setupSpec() method. However, this isn't working for me. It is giving me error: Method on class [com.somepackage.Keyword] was used outside of a Grails application.

Below is an example of what I have:

@TestFor(MyService)
@TestMixin(DomainClassUnitTestMixin)
@Mock([Keyword])
class MyServiceSpec extends Specification {
  def setup() {
     new Keyword(name: "test").save()
  }
}

The above works, however, if I change to setupSpec() then it fails with error Method on class [com.somepackage.Keyword] was used outside of a Grails application.

@TestFor(MyService)
@TestMixin(DomainClassUnitTestMixin)
@Mock([Keyword])
class MyServiceSpec extends Specification {
  def setupSpec() {
     new Keyword(name: "test").save()
  }
}

Question

How can I share the same setup method in MyServiceSpec across multiple specs. I run the test with grails test-app -echoOut -unit MyService

Karate vs Spock

I've recently found Karate framework for testing Web Services. But there is also Spock framework providing similar (to my mind) functionality. What are the differences between the frameworks? I would like to suggest our testers to take a look at it.

How to test if the data entered through registration page of a web application is stored into database or not with Selenium?

I am new to Selenium. I am testing a user registration form in which i have to verify if the data is inserted into database or not. I am using following code to check. Is there any better option than this?

@Test
public void testVerifyListOfRecords() throws InterruptedException {

  String query = "SELECT ID FROM usermaster WHERE RegistrationNumber = '" + REGNO + "' ";
  String ID = DatabaseConnector.executeSQLQuery("QA", query);

  if(ID == ""){
    STATUS = "FALSE";
    System.out.println("REGISTRATION NUMBER IS NOT INSERTED..!! TEST FAILED..!!");
  } else STATUS = "TRUE";

  String sqlQuery = "SELECT FirstName,LastName,SpecialityCode,QualificationCode FROM usermaster WHERE ID = '" + ID + "' ";
  List<String> listOfDBValues = new ArrayList<String>();
  listOfDBValues = DatabaseConnector.executeSQLQuery_List("QA", sqlQuery);
  List<String> Branch = new ArrayList<>();
  Branch.add(listOfDBValues.get(0));

  List<String> list1 = new ArrayList<>(Arrays.asList("testfirstname testlastname ORP DM"));
  Assert.assertEquals(STATUS, "TRUE");
  System.out.println("STATUS IS " + STATUS);
  Assert.assertEquals(Branch, list1);
}

Testing Urbanairship push notifications on android emulator

I would like to test push notifications sent by Urbanairship on android emulators but I could not find any image/configuration where it would actually working. I installed 1st flight demo app provided by UA and connected with my UA account on all emulators I tried so far.

  1. I tried to use created virtual device by Android Studio, for emulators with google play I was able to install 1st flight app but sent notifications via web weren't displayed.
  2. For created emulators with google API I wasn't able to even install 1st flight app which was marked on google play web as already installed but I could not find on emulator.
  3. For used Android 6 r3 image on Virtualbox I was able to install app but it was working as described in 1st point - notification is marked as sent but nothing was displayed on device.
  4. For used Andy default emulator the same as in 1/3 points.
  5. I added manually play store in Android Studio to Android 6 with google API, but I was not able to successfully log in there.

For real devices I was able to display sent notification on Android 6, for Android 7 it was actually working as for emulators.

I don't know what more specific emulators / images can I use, what else could be changed, added or configured to make it working. Any suggestion is welcome.