samedi 30 avril 2016

Add custom http headers to chai requests

I am building an app using node.js and testing with mocha + chai. Is there a way I can add custom headers to my GET and POST chai requests?

For example, I want something like (semi-pseudocode):

chai.request(server)
  .get('/api/car/' + data.car_id)
  .headers({'some_custom_attribute':'some_value'})
  .end(function(err, res) {
    //do something
  });

And likewise with post:

chai.request(server)
  .post('/api/car/')
  .headers({'some_custom_attribute':'some_value'})
  .send({car_id: 'some_car_id'})
  .end(function(err, res) {
    //do something
  });

Can someone help?

Thanks in advance!

Detect Windows Kit 8.0 and Windows Kit 8.1 SDKs

I'm working on a test script for Windows Tablets, Windows Phones and Windows Store apps. The scripts are mostly working for under Visual Studio 2012 and Windows Kit 8.0 SDK. It appears Microsoft changed some things for Visual Studio 2013 and Windows Kit 8.1 SDK, and its causing a failure:

cl.exe /nologo /W4 /D_MBCS /Zi /TP /EHsc /MD /FI winapifamily.h /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1
/DWINAPI_FAMILY=WINAPI_PARTITION_DESKTOP /Yc"pch.h" /Fp"pch.pch" /c pch.cpp
pch.cpp
C:\Program Files (x86)\Windows Kits\8.1\include\shared\winapifamily.h(116) : fatal error C1189:
#error :  Unknown WINAPI_FAMILY value. Was it defined in terms of a WINAPI_PARTITION_* value?
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 12.0
\VC\BIN\x86_ARM\cl.exe"' : return code '0x2'

How can we detect the Windows Kit SDK being used?

Espresso: How to use R.string resources of androidTest folder

I want to put data in xml file of androidTest/res/values/string.xml folder. I have created the file say test.xml with below contents.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="test">hello</string>
</resources>

When i am trying to access the field test via R.string.test. It is not accessible and says "cannot resolve symbol test". Can someone please advice me here.

vendredi 29 avril 2016

Building, seeding and destroying PostgreSQL with Sequelize for testing

I am trying to automate my database being built, seeded and destroyed for each test. I am using PostgreSQL, Mocha and Sequelize.

I found a library: sequelize-fixtures that has got me part way there, but ultimately it's very inconsistent and occasionally will throw constraint errors: Unhandled rejection SequelizeUniqueConstraintError: Validation error even though I do not have any validation on the model.

Here's how I am doing the tests

const sequelize = new Sequelize('test_db', 'db', null, {
  logging: false,
  host: 'localhost',
  port: '5432',
  dialect: 'postgres',
  protocol: 'postgres'
})

describe('/auth/whoami', () => {
  beforeEach((done) => {
    Fixtures.loadFile('test/fixtures/data.json', models)
      .then(function(){
         done()
      })
  })

  afterEach((done) => {
    sequelize.sync({
      force: true
    }).then(() => {
      done()
    })
  })

  it('should connect to the DB', (done) => {
    sequelize.authenticate()
      .then((err) => {
        expect(err).toBe(undefined)
        done()
      })
  })

  it('should test getting a user', (done) => {
    models.User.findAll({
      attributes: ['username'],
    }).then((users) => {
      users.forEach((user) => {
        console.log(user.password)
      })
      done()
    })
  })
})

This worked once, then never again. Is there a more robust way for me to, before every test, start with a completely clean DB for me to fill with test data to operate on?

This is the closest I have come to finding any kind of discussion/answer.


Additionally, if anyone also knows why I still get console.logs() even though I have logging: false on, that would be appreciated.

How to allow QA to test a device for other regions?

I just had a bug occur where people werent able to use my device in one country. Is there any way for me to setup the test apps i send to QA in order to allow them to test the locale of another country?

Espresso RecyclerView inside ViewPager

I am new to android espresso library. Trying to test click on RecyclerView Item inside the ViewPager. I've searched the Internet but found nothing about ViewPager. So my question is: how to access RecyclerView inside a ViewPager using Espresso to perform click?

Mocha Test for NodeJS Function not calling Callback

I have a function that sends a message to a facebook user using a facebook page.

// send text message to an user
function sendTextMessage(sender, text, callback) {
    messageData = {
        text: text
    }
    request({
        url: 'http://ift.tt/1Q7nDgi',
        qs: { access_token: token },
        method: 'POST',
        json: {
            recipient: { id: sender },
            message: messageData,
        }
    }, function (error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
            callback(-1);
        } if (response.body.error) {
              console.log('Error: ', response.body.error);
              return -2;
          } else{
            console.log('Ok: ' + JSON.stringify(body));
            callback(1);
            return response;
        }

    });
}

My problem is, when I run this code on command line, it works fine, however, I'm trying to create a test for this using mocha.

it('Text Message', function(){
    var fb_answer = function(res){
      // first schema to be compared
      var fbTextAnswerSchema = {
        "title": "fb answer schema v1",
        "type": "object",
        "required": ["recipient_id", "message_id"],
        "recipient_id": {
           "type": "string"
        },
        "message_id": {
           "type": "string"
        }
      };
      expect(res).to.be.jsonSchema(fbTextAnswerSchema);
    }
    messenger.sendTextMessage(sender, "[TEST] Testing send text message", fb_answer);
  });

And when I run mocha on command line calling this test, it not only pass, but it also does not print the body of the response.

Basically what is weird here is that, when I run using node the code print the response, and when I run with mocha, it doesn't, which makes me think that the callback of the request is not been called...

I need to pass a test function as callback to this function in order to treat the response.

Why isn't the response been print? And why the callback is not been called? Is there a better way to test this kind of function?

Thanks in advanced.

sbt dependency management issue with hbase-testing-utility

i'm attempting to perform unit testing with scalatest, making use of the hbase testing utility to locally test development code. the setup for hbase testing utility in sbt is the struggle right now. when i compile, i get the following error:

[warn]  module not found: org.apache.hbase#${compat.module};1.2.1
[warn] ==== local: tried
[warn]   /root/.ivy2/local/org.apache.hbase/${compat.module}/1.2.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   http://ift.tt/1NGfV2j
[warn] ==== Akka Repository: tried
[warn]   http://ift.tt/1r2FS1U
[warn] ==== scala-tools: tried
[warn]   http://ift.tt/1NGfV2l
[warn] ==== cloudera-repos: tried
[warn]   http://ift.tt/1r2FUGR
[warn] ==== Sonatype OSS Snapshots: tried
[warn]   http://ift.tt/1NGfV2n
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.hbase#${compat.module};1.2.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn] 
[warn]  Note: Unresolved dependencies path:
[warn]      org.apache.hbase:${compat.module}:1.2.1
[warn]        +- org.apache.hbase:hbase-testing-util:1.2.1 (/workspace/spark/etl/built.sbt#L30-62)

[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.apache.hbase#${compat.module};1.2.1: not found
[error] Total time: 32 s, completed Apr 29, 2016 9:25:27 AM

my build.sbt file is as follows:

val hbaseVersion = "1.2.1"
val sparkVersion = "1.6.1"
val hadoopVersion = "2.7.1"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-streaming" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-streaming-kafka" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion % "provided",
  "org.apache.spark" %% "spark-mllib" % sparkVersion ,
  "org.apache.hbase" % "hbase" % hbaseVersion,
  "org.apache.hbase" % "hbase-server" % hbaseVersion,
  "org.apache.hbase" % "hbase-server" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-client" % hbaseVersion,
  "org.apache.hbase" % "hbase-common" % hbaseVersion,
  "org.apache.hbase" % "hbase-common" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-annotations" % hbaseVersion,
  "org.apache.hbase" % "hbase-testing-util" % hbaseVersion % "test",
  "org.apache.hadoop" % "hadoop-minicluster" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-mapreduce-client-jobclient" % hadoopVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-hdfs" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-hdfs" % hadoopVersion classifier "tests",
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion,
  "org.apache.hbase" % "hbase-hadoop-compat" % hbaseVersion classifier "tests",
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion,
  "org.apache.hbase" % "hbase-hadoop2-compat" % hbaseVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-common" % hadoopVersion,
  "org.apache.hadoop" % "hadoop-common" % hadoopVersion classifier "tests",
  "org.apache.hadoop" % "hadoop-annotations" % hadoopVersion,
  "org.scalatest" %% "scalatest" % "2.2.6" % "test" ,
  //"org.scalacheck" %% "scalacheck" % "1.12.5" % "test",
  "com.cloudera.sparkts" % "sparkts" % "0.3.0",
  "com.ecwid.consul" % "consul-api" % "1.1.9",
  "joda-time" % "joda-time" % "2.7"
)

resolvers ++= Seq(
  "Akka Repository" at "http://ift.tt/OxKGcq",
  "scala-tools" at "http://ift.tt/1OUMRhz",
  "cloudera-repos" at "http://ift.tt/1j3vwUC",
  "Sonatype OSS Snapshots" at "http://ift.tt/IdfDNV"
)

Anyone understand why this failure is occurring?

rails rspec controller/model testing oauth

I'm trying to test oauth in controller, but I got stuck. How can I test my create method properly?

routes.rb

get '/auth/:provider/callback', to: 'socials#create'
resources :socials, only: :create

social.rb

def self.find_or_create_from_auth_hash(auth_hash)
  #checking if the connected account exists (one user can have one acc/provider at the moment)
  social_acc = where(provider: auth_hash.provider).first_or_create
  social_acc.update(
    uid: auth_hash.uid,
    token: auth_hash.credentials.token,
    secret: auth_hash.credentials.secret,
    picture_url: auth_hash.info.image,
    location: auth_hash.info.location,
    description: auth_hash.info.description,
    first_name: auth_hash.info.first_name || nil,
    last_name: auth_hash.info.last_name || nil,
    phone: auth_hash.info.phone || nil,
    page_url:   case social_acc.provider
                when 'twitter' then auth_hash.info.urls.Twitter
                when 'linkedin' then auth_hash.info.urls.public_profile
                end
    )
  social_acc
end

socials_controller

def create
  begin
    @profile = current_user.profile
    @social = @profile.socials.find_or_create_from_auth_hash(auth_hash)
    flash[:success] = "#{@social.provider.camelize} account was successfully updated!"
  rescue
    flash[:alert] = "There was an error while trying to authenticate you!"
  end
  redirect_to request.env['omniauth.origin'] || edit_user_profile_path(current_user)
end

private

  def auth_hash
    request.env['omniauth.auth']
  end

socials_controller_spec.rb

describe "when user is logged in" do
before(:each) do
  login_user
end

describe "POST create" do
  let!(:profile) { create(:profile, user: @user) }
  let!(:social) { create(:social, profile: profile) }
  #Not sure if I have to create auth_hash factory and if so then how.

  it "creates or updates social" do
    post :create
    expect(assigns(:profile)).to eq(profile)
    #########I don't know what I should put here:
    #expect(assigns(:profile)).to eq(receive)
    #expect(@profile).to receive(:find_or_create_from_auth_hash)
  end
end

end

Angular Testing: It's valid testing that an service not to have been called when I test a restricted submit data?

I have this code:

angular
  .module('ExampleApp')
  .service('MyService', Service);

function Service(){
  var self = this;

  self.save = function(_data){
    //save the data in the server
  } 
}


angular
  .module('ExampleApp')
  .controller('MyCtrl', Controller);

Controller.$inject = ['MyService']

function Controller(MyService){
  var vm = this;
  vm.invalidDataExist = false;
  vm.data = {};
  vm.submit = function(){
     //call a function that check if exist data invalid
     vm.invalidDataExist = checkIfExistDataInvalid();
     if(!vm.invalidDataExist){
       MyService.save(vm.data);
     }   
  }
}

My idea is generate a test that simulates that exist data invalid and ensure that the service have not been called:

describe('MyCtrl', describeSpec);

function describeSpec(){
  var MyCtrl, MyService

  beforeEach(module('ExampleApp'));
  beforeEach(inject(eachSpecSetup));

  function eachSpecSetup($controller, _MyService_){
    MyCtrl = $controller('MyCtrl');
    MyService = _MyService_;
  }

  it('Should not called a service if exist data invalid', spec1);

  function spec1(){
    spyOn(MyService, 'save');

    //I create a invalid data here

    MyCtrl.submit();

    expect(MyService.save).notHaveBeenCalled();

  }

}

My questions:

  • This is a valid testing idea?
  • What is the "standard" way to check cases how this?

How to get test history

I have many builds with failed tests. I learn one test and want to find last build, where this test was succesfully.

How I can find this build or how I can get test results history?

AngularJS Karma-jasmine and visual studio 2015

I have an angularJS application and now I would like to start testing it. So I have watched a few tutorials, but none of them shows how to set up testing with visual studio 2015. Does anyone know about a good resource to read or can help me set it up.

The questions I have are:

  1. Do I need to set up separate views for each test?
  2. Apart from installing karma-jasmine and karma-chrome-launcher do I need to install anything else?
  3. How can I view my tests in a browser?

Any help given will be awesome.

Selenium - ERROR: Caught exception [ERROR: Unsupported command [clickAt]

I'm trying to export selenium IDE test to Eclipse with JUnit but I get:

"ERROR: Caught exception [ERROR: Unsupported command [clickAt]"

I now about some limitations in Selenium IDE:

(ERROR: Caught exception [ERROR: Unsupported command [addSelection |])

  • but I hoping that someone can help me with that command "clickAt" because only "click" doesn't work for me :/

I need to dropdown list and choose from it:

<div id="select2-result-label-12" class="select2-result-label" role="option"> <span class="select2-match"></span> THOMSON </div>

ID is changing dynamically, soo I used class to get it and "contain", like this:

    driver.findElement(By.xpath("//div[@class='select2-result-label'[contains(@text, 'THOMSON')]")).click();

How to load a value from . properties file in Cucumber-jvm step class

I have written a cucumber integration tests and it is running ok.

And then i wanted some class variables from the step.java to get their values from .properties values

public class cucumberStepClass { 
    @Value("${value.from.propertiesfile}")
    private String variable
//rest of integration test
}

Does anyone know how can i inject those values so my test can use them?

How to upload file in a test through Open Windows using Selenium with Selenium::Remote::Driver package for Perl

In title important part of my issue.I add u additional clarifications : I can get my "button" with following code :

 $elem = $driver->find_element('//*[@id="file_uploader"]/div/div/div/div[1]/div[1]/div/span');
     $driver->mouse_move_to_location(element => $elem); # xoffset => x, yoffset => y
     $driver->click_ok('LEFT');
     $driver->pause(3000);

But after i can't get anything in Open Windows which appears . How is it possible to upload file also in, test ?

How to upload file in a test through Open Windows using Selenium with Selenium::Remote::Driver package for Perl

Many thanks in advance !!

CasperJs do something before start?

I use JWTs to manage logged-in status, so I need to clear localstorage before running casper.start. How is this possible?

Something like:

casper.then(function() {
  casper.evaluate(function() {
    localStorage.clear()
  })
})

casper.start('http://localhost:3000', function() {
  test.assertUrlMatch('http://localhost:3000')
})

AndroidStudio 2.0 runs unit tests as instrumentation tests

AndroidStudio 2.0 runs unit tests as instrumentation tests. I've disabled an "Enable all test artifacts.." option and set the artifact to unit tests. However, AS still tries to run an emulator and it doesn't see any unit tests at all. Any ideas?

Phonegap, how to testing on phone (ios or android)

i have issue with phonegap, while in browser testing everything work, but when i use build to apk for android or phonegap desktop to test on IOS it not work and i dont have idea how to test it what is wrong on the phone.

for example: i use event "ng-render-.." of angular that call to event when ng-repeat is done. this event not execute on phone, im not even sure if this is the event it self or something was wrong before.

anyway, ill be happy to know how can i test my application on my phone ?

QUnit testing with Skatejs elements

I'm using Skatejs for controlling event lifecycle. However, because of async loading, I'm having trouble with writing tests with QUnit.

setTimeout(function() {
     //assertions here
}, 5000);

I use setTimeout like above but then I got an issue with Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.

What should I do in this case?

Can pytest be used to running occasional production checks?

In our application we need to sometimes check something, for example data consistency in database somewhere. So it's not the unit tests or even functional tests, because they don't test any specific function of the application server. They just check specific aspect isn't wrong right now without have a clue about the reason of the error if it's even there.

And it's not monitoring (we use Zabbix etc for this), because they don't run all the time or periodically. They are occasional.

So what we do is something in the middle. We want assertions from unit tests, because it's beneficial to know information about the error and monitoring solutions mostly can show you very little information like zero or one etc. And we want to email some responsible persons if there are errors. Right we have a small framework for this, but I'm thinking that there should be some solution to that already.

Test Observable subscriber behaviour

I'm writing a test to check the behaviour of my subscriber. I have a method like that:

public void myMethod(){
     myObservable.subscribe(result -> {
         count++;
     })

}

I want to test that myMethod increments count variable when result is emmited, but because count is incremented asynchronously, I need to wait until result is emmited to check count status. How can I do that?

Selendroid Inspector device Screen not appear

When i connect my hybrid app using selendroid server, Inspector tool not displaying device's enter image description herescreen(Broken Image/Empty image appear). And also nothing is appear on Java/HTML source tabs.

I use followings Command to Start the Selendroid Server

java -jar Jar_file -app app_file

and also i have try

java -jar Jar_file -deviceScreenshot -app app_file

Code i used in Java eclipse

SelendroidCapabilities capa = new SelendroidCapabilities();
capa.setAut(get_appid(Get_AppID_From_Status));
driver = new SelendroidDriver(capa);

What should i do to get a device screen in Inspector tool ?

What is full stack testing?

I was trying to understand the meaning of full stack testing in general. I couldn't find a reasonable answer on Google. I could understand bits and traces of full stack integration testing?

Please help!!

jeudi 28 avril 2016

fatal error LNK1104: cannot open file 'bcrypt.lib' when building for Surface RT tablet

I'm working on a test script for Windows Store apps. The script includes testing Surface RT tablet with the ARM processor.

Under the VS2012 ARM Developer Prompt, the library compiles fine during this portion of the testing:

>nmake -f cryptest.nmake
...
cl.exe /nologo /W4 /D_MBCS /Zi /TP /EHsc /MD /FI winapifamily.h /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1 /Yc"pch.h" /Fp"pch.pch" /c pch.cpp
pch.cpp
cl.exe /nologo /W4 /D_MBCS /Zi /TP /EHsc /MD /FI winapifamily.h /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE=1 /c cryptlib.cpp
...
lib.exe /nologo cryptlib.obj cpu.obj ... /out:cryptlib.lib

Then linking the final executable to finish this portion of the testing:

link.exe /nologo /SUBSYSTEM:CONSOLE bench1.obj bench2.obj test.obj validat1.obj
validat2.obj validat3.obj datatest.obj regtest.obj fipsalgt.obj dlltest.obj
fipstest.obj cryptlib.lib  /out:cryptest.exe

LINK : fatal error LNK1104: cannot open file 'bcrypt.lib'
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\BIN\x86_ARM\link.exe"' : return code '0x450'

We are using BCryptOpenAlgorithmProvider, BCryptGenRandom and BCryptCloseAlgorithmProvider. According to the docs, the functions are available for Windows Store apps, and the library to link to is Bcrypt.lib. The library is called out in the source files with:

// Obviously, both evaluate to TRUE
#if defined(_MSC_VER) && defined(USE_MS_CNGAPI)
# pragma comment(lib, "bcrypt.lib")
#endif

I've been through nearly every page of Cryptography API: Next Generation on the Microsoft Dev Center, and Microsoft does not state anything special for this configuration.

What library do I have to link to for the CryptoAPI Next Generation (CNG) when building for Surface RT/ARM tablet?


Here is the environment Microsoft sets up when using the VS2012 ARM Developer Prompt and Nmake. I'm happy to tune it if necessary. However, I don't have this particular problem under other Developer Prompts.

>nmake /P

Microsoft (R) Program Maintenance Utility Version 11.00.61030.0
Copyright (C) Microsoft Corporation.  All rights reserved.


MACROS:

PROCESSOR_IDENTIFIER = Intel64 Family 6 Model 42 Stepping 7, GenuineIntel
      LIBPATH = C:\Windows\Microsoft.NET\Framework64\v4.0.30319;C:\Windows\Micro
soft.NET\Framework64\v3.5;C:\Windows\Microsoft.NET\Framework\v4.0.30319;C:\Windo
ws\Microsoft.NET\Framework\v3.5;C:\Program Files (x86)\Microsoft Visual Studio 1
1.0\VC\LIB\ARM;C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\ATLMFC\LIB
\ARM;C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neut
ral;C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\Microsoft.V
CLibs\11.0\References\CommonConfiguration\neutral;
      INCLUDE = C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\INCLUDE;C
:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\ATLMFC\INCLUDE;C:\Program
Files (x86)\Windows Kits\8.0\include\shared;C:\Program Files (x86)\Windows Kits\
8.0\include\um;C:\Program Files (x86)\Windows Kits\8.0\include\winrt;
COMMONPROGRAMW6432 = C:\Program Files\Common Files
      COMSPEC = C:\Windows\system32\cmd.exe
   _NMAKE_VER = 11.00.61030.0
      PATHEXT = .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
         MAKE = "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\BIN\nmak
e.exe"
COMMANDPROMPTTYPE = Cross
   SYSTEMROOT = C:\Windows
WINDOWSSDKDIR_OLD = C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\
         PATH = C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\
CommonExtensions\Microsoft\TestWindow;C:\Program Files (x86)\Microsoft SDKs\F#\3
.0\Framework\v4.0\;C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\I
DE\;C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\BIN\x86_ARM;C:\Progra
m Files (x86)\Microsoft Visual Studio 11.0\VC\BIN;C:\Program Files (x86)\Microso
ft Visual Studio 11.0\Common7\Tools;C:\Windows\Microsoft.NET\Framework\v4.0.3031
9;C:\Windows\Microsoft.NET\Framework\v3.5;C:\Program Files (x86)\Microsoft Visua
l Studio 11.0\VC\VCPackages;C:\Program Files (x86)\HTML Help Workshop;C:\Program
 Files (x86)\Microsoft Visual Studio 11.0\Team Tools\Performance Tools;C:\Progra
m Files (x86)\Windows Kits\8.0\bin\x86;C:\Program Files (x86)\Microsoft SDKs\Win
dows\v8.0A\bin\NETFX 4.0 Tools;C:\Program Files (x86)\Microsoft SDKs\Windows\v8.
0A\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\WindowsPowerShell\v1.0
\;C:\Program Files\NASM;C:\Strawberry\perl\bin;C:\OpenSSL\bin;C:\curl-7.46.0-win
64\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\Microsoft SQL Ser
ver\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Pro
gram Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Windows Kit
s\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Too
ls\Binn\
NUMBER_OF_PROCESSORS = 2
  PROGRAMDATA = C:\ProgramData
         TEMP = C:\Users\Test\AppData\Local\Temp
FRAMEWORKVERSION32 = v4.0.30319
FRAMEWORK35VERSION = v3.5
 PROGRAMW6432 = C:\Program Files
FRAMEWORKVERSION64 = v4.0.30319
  SESSIONNAME = Console
PROCESSOR_ARCHITEW6432 = AMD64
  USERPROFILE = C:\Users\Test
COMMONPROGRAMFILES = C:\Program Files (x86)\Common Files
  LOGONSERVER = \\WINDOWS-7-X64
     HOMEPATH = \Users\Test    WINDOWS_TRACING_FLAGS = 3
  SYSTEMDRIVE = C:
     USERNAME = Test
     PLATFORM = ARM
 LOCALAPPDATA = C:\Users\Test\AppData\Local
ALLUSERSPROFILE = C:\ProgramData
EXTENSIONSDKDIR = C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSD
Ks
           CC = cl
 PROGRAMFILES = C:\Program Files (x86)
    MAKEFLAGS = P
 FRAMEWORKDIR = C:\Windows\Microsoft.NET\Framework\
PROCESSOR_REVISION = 2a07
 VCINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\
 COMPUTERNAME = WINDOWS-7-X64
           AS = ml
           RC = rc
 PSMODULEPATH = C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PROCESSOR_LEVEL = 6
 VSINSTALLDIR = C:\Program Files (x86)\Microsoft Visual Studio 11.0\
PROCESSOR_ARCHITECTURE = x86
           OS = Windows_NT
    HOMEDRIVE = C:
    DEVENVDIR = C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\

MOZ_PLUGIN_PATH = C:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\
WINDOWSSDKDIR_35 = C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\
FSHARPINSTALLDIR = C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0\
       PUBLIC = C:\Users\Public
       WINDIR = C:\Windows
VISUALSTUDIOVERSION = 11.0
FRAMEWORKVERSION = v4.0.30319
          LIB = C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\LIB\ARM;C
:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\ATLMFC\LIB\ARM;C:\Program
Files (x86)\Windows Kits\8.0\lib\win8\um\ARM;
       PROMPT = $P$G
          CPP = cl
WINDOWSSDKDIR = C:\Program Files (x86)\Windows Kits\8.0\
FP_NO_HOST_CHECK = NO
          TMP = C:\Users\Test\AppData\Local\Temp
FRAMEWORKDIR32 = C:\Windows\Microsoft.NET\Framework\
WINDOWS_TRACING_LOGFILE = C:\BVTBin\Tests\installpackage\csilogfile.log
          CXX = cl
   USERDOMAIN = WINDOWS-7-X64
FRAMEWORKDIR64 = C:\Windows\Microsoft.NET\Framework64
VS100COMNTOOLS = c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Too
ls\
VS110COMNTOOLS = C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Too
ls\
      APPDATA = C:\Users\Test\AppData\Roaming
      MAKEDIR = C:\Users\Test\Desktop\cryptopp


INFERENCE RULES:

.asm.obj::
        commands:       $(AS) $(AFLAGS) /c $<

.asm.exe:
        commands:       $(AS) $(AFLAGS) $<

.c.obj::
        commands:       $(CC) $(CFLAGS) /c $<

.c.exe:
        commands:       $(CC) $(CFLAGS) $<

.cc.obj::
        commands:       $(CC) $(CFLAGS) /c $<

.cc.exe:
        commands:       $(CC) $(CFLAGS) $<

.cpp.obj::
        commands:       $(CPP) $(CPPFLAGS) /c $<

.cpp.exe:
        commands:       $(CPP) $(CPPFLAGS) $<

.cxx.obj::
        commands:       $(CXX) $(CXXFLAGS) /c $<

.cxx.exe:
        commands:       $(CXX) $(CXXFLAGS) $<

.rc.res:
        commands:       $(RC) $(RFLAGS) /r $<

.SUFFIXES: .obj .asm .c .cc .cpp .cxx .f .f90 .for .rc

TARGETS:

Unable to do test transaction using sandbox test account

Ok, I have been trying to fix this issue for a whole week now...

I am trying to test buy my product from my website using the test account in paypal sandbox to make sure that customers are able to buy it.

But something goes wrong when i try to buy my product using the sandbox test account.

here is the process of what i did:

  1. Logged into paypal.com using my real account.

  2. Went to the developer.paypal.com website > Dashboard > under sandbox, clicked accounts.

  3. I created a personal sandbox account with 100,000$ fake dollards in it.

  4. Once the sandbox account has been created, i then log out of developer.paypal.com/

  5. I go to sandbox.paypal.com and log in using my sandbox test account that i just created.

  6. I proceed to my website: http://ift.tt/21ildnd > click on the courses menu tab. (i do not log in to my website)

  7. In the courses page; http://ift.tt/1SUgYxU i click buy now.


(Here is the problem)

  1. I am then redirected to the paypal checkout page, but when i enter my sandbox test account user and password: user: stephanebeaulieu5000-buyer@gmail.com pass: addict123

it dosent work and a message appears saying:"Check your email address and password and try again."

I have followed the exact steps described on the paypal website explaining how to do a test transaction.

plz help me, this is imporatnt since i have to see if everything works great for my clients... i am losing money everyday that this issue stays unresolved...

Thank you! ;)

Tensorflow LSTM model testing

I'm new to LSTM and Tensorflow, and I'm trying to use an LSTM model to learn and then classify some huge data set that I have. (I'm not worried about the accuracy my intention is to learn). I tried to implement the model in a similar way as in the PTB word prediction tutorial that uses LSTM. The code in the tutorial (http://ift.tt/1SUgZSz) uses the below line to run the session using the model

 cost, state, _ = session.run([m.cost, m.final_state, eval_op],
                                 {m.input_data: x,
                                  m.targets: y,
                                  m.initial_state: state})

I modified this for my example as below (to get the logits and work with it):

  cost, state, _,output,logits = session.run([m.cost, m.final_state, eval_op, m.output,m.logits],
                                 {m.input_data: x,
                                  m.targets: y,
                                  m.initial_state: state})

So my questions if someone could help are as below:

  • How can the model built while training be used for testing? What exactly is happening when 3 models are being used by the tutorial one for each test, train and validation?
  • What about the targets while testing(if I don't know them, say in a classification problem). What changes in the run_epoch () can be done in a way to use the model built during training.
  • Just another question: It's difficult to debug tensorflow graphs ( and I found it difficult to understand the tensorboard visualizer too) And I didn't find good resource for learning tensorflow (the website seems to be lacking structure/ documentation) What other resources/ debugging methods are there?

Thanks.

babel-node is not loading presets correctly

I'm trying to run a test written in es6 with babel-node --presets es2015 -- test.js (via an npm script), which gives me the error:

SyntaxError: Unexpected token import

Any ideas as to why import would be an issue? I have babel-preset-es2015 in my package.json dependencies...

Thanks in advance,
Dan

How I can Use Putty to test Custom kernel?

I want to use Putty to test custom kernel and original kernel but I do not know what is the settings of connection .. can you please help me? enter image description here The video here https://www.youtube.com/watch?v=3YyH4q9lIAY at 19:30 explains how to test kernel with out explain the setting of the connection.

thanks

WEKA IP Address arff file error

I have the following ARFF Training file

@relation cowrie

@attribute SourceIP {64.31.57.18,121.34.178.154}
@attribute SourcePort numeric
@attribute Username {nano,root}
@attribute Password {'G0na,.',root}
@attribute Status {failed,succeeded}
@attribute Malicious {No,Yes}

@data

64.31.57.18,42001,nano,'G0na,.',failed,No
64.31.57.18,42131,root,'G0na,.',failed,No
121.34.178.154,43064,root,root,succeeded,Yes

I want the source ip, username and password to remain as train attributes somehow without confusing WEKA so that I am able to test an entry against this train file.

I read that WEKA only sees things as yes/no 1/0 for machine learning but I also read that some attributes can be made to be considered as nominal.

Is there a way to keep the mentioned attributes in the train file and make WEKA work with them?

How to fill an object with data in NUnit

How is it possible to add data to a TestCaseSource object which contains a Dictionary?

I have following code:

static object[] FileInfoCases =
        {
        new object[] { new Dictionary<string, List<BackupFileInfo>>()["source"] = new List<BackupFileInfo>() { .FileName = "", FileLastChanged = new DateTime(), FullPath = "TestPath" } }
        };

BackupFileInfo is my Cutsom object. The values FileName and FileLastChanged and FullPath are Attributes of my custom object. Now I want to fill the List. My custom object is not static. I can not access the attribute names within the list.

Can someone help me please?

how do I use sinon sandboxes when tests run asynchronously?

I've got some code I'm trying to test with a structure like this (per Cleaning up sinon stubs easily):

function test1() {
    // manually create and restore the sandbox
    var sandbox;
    beforeEach(function () {
        sandbox = sinon.sandbox.create();
        sandbox.stub(globalVar, "method", function() { return 1; });
    });

    afterEach(function () {
        sandbox.restore();
    });

    it('tests something', function(done) {
        anAsyncMethod(function() { doSomething(); done(); });
    }
 }

There is then a similar test2() function.

But if I do:

describe('two tests', function() {
    test1();
    test2();
}

I get:

TypeError: Attempted to wrap method which is already wrapped

I've done some logging to figure out the run order and it appears that the the issue is that it runs the test1 beforeEach() hook, then the test2 beforeEach() hook, then the test1 it(), etc. Because it's calling the second beforeEach() before it gets to the afterEach() from the first test, we have a problem.

Is there a better way I should be structuring this?

Jest Test React Component

I'm trying to test an component that I've created, but I have some problems. I was reading and learning jest. So I install jest-cli on my project

Thats my component:

import React from 'react';
import classNames from "classnames";

let PropTypes = React.PropTypes;

class Pagination extends React.Component {
    constructor(props) {
    super(props);
}

render() {
    let totalPages = [];
    for (let x = 1; x <= this.props.totalPages; x++) {
        totalPages.push(x);
    }
    let pages = totalPages.map(function(page) {
        let attr = {
            href: '',
            onClick: this.props.setCurrentPage.bind(this, page)
        }

        let link = React.DOM.a(attr, page);
        let active = false;
        if (page == this.props.page) {
            let active = true;
            link = React.DOM.span({}, page);
        }
        return React.DOM.li({className: classNames({'active': active})}, link);
    }.bind(this));

    let attrBack = {
        href: '',
        className: 'btn',
        onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) - 1))
    };
    let attrNext = {
        href: '',
        className: 'btn',
        onClick: this.props.setCurrentPage.bind(this, (parseInt(this.props.page) + 1))
    };
    let pagination = React.DOM.div({className: 'pagination'}, 
        React.DOM.ul({}, 
            React.DOM.li({}, React.DOM.a(attrBack, React.DOM.i({className: classNames({'fa fa-chevron-left': (this.props.page != 1)})}))),
            pages,
            React.DOM.li({}, React.DOM.a(attrNext, React.DOM.i({className: classNames({'fa fa-chevron-right': (this.props.page != this.props.totalPages)})})))
        )
    );
    return (pagination);
}
}

Pagination.propTypes = {
   setCurrentPage: PropTypes.func.isRequired,
   page: PropTypes.number.isRequired,
   totalPages: PropTypes.number.isRequired,
}

export default Pagination;

and here my Test

jest.dontMock('../../../components/content/elements/pagination');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Pagination from '../../../components/content/elements/pagination';

describe('Pagination', () => {

    let setCurrentPage = jest.genMockFunction();
    Pagination._setCurrentPage = setCurrentPage;

    it('renders without problems', () => {
        const pagination = TestUtils.renderIntoDocument(
            <Pagination setCurrentPage={() => {}} page={1} totalPages={10} />
        );

        const renderedPagination =     TestUtils.findRenderedDOMComponentWithClass(pagination, 'pagination');

        expect(TestUtils.isDOMComponent(renderedPagination)).toBe(true);
    });
});

but when I exec the test, shows me the error:

Error: Did not find exactly one match (found: 0) for class:pagination

What is Use case testing in software testing?

What is Use case testing in software testing? Use case testing is a technique that helps us identify test cases that exercise the whole system on a transaction by transaction basis from start to finish. Am i correct?

You must either use ReInit() or set the JavaCC option STATIC to false

I'm trying to test my project but when I try to do it parts I've have received this error:

Second call to constructor of static parser. You must either use ReInit() or set the JavaCC option STATIC to false during parser generation.

It happens because I need to execute a ReUnit command to update the reference to the new value.

I updated the code, just like it was suggested, with the command ReInit(), but now I have a error (NullPointerException). At this line, Imp1Parser.ReInit(stream), the error happens and stop the execution.

Could someone help me?

FakeItEasy - Retrieve Faked object

Is there any way to retrieve the fake objects which were inserted into a faked class?

E.g.

Let's say I have the following interface + class;

public interface IFakeable
{
    void FakeYou();
}

public class SomeClass
{
    private readonly IFakeable _fake;

    public SomeClass(IFakeable fake)
    {
        _fake = fake;
    }

    public void FakeCall()
    {
        _fake.FakeYou();
    }
}

And wanted to test something like the following:

[TestFixture]
public class SomeClassTests
{
    [Test]
    public void FakeCall_CallsIFakeabl_FakeYou()
    {
        var subject = A.Fake<SomeClass>();

        subject.FakeCall();

        A.CallTo(() => A.Fake<IFakeable>().FakeYou()).MustHaveHappened();
    }
}

Is this possible without exposing the SomeClass._fake field?

Is there somewhere I can specify to use Singletons for Fakes?

ADHOCK testing and exploratory Testing

I want to know the difference between adhock testing,Monkey testing and exploratory testing.. Please help me in understanding these three terms.

Providing package-private methods for testing?

I'm writing the following class:

public class MyClass{

    private final MyAnotherClass[][] anotherClasses;

    public MyClass(//args){
        //initialization
    }

    //...
}

I'd like to test this class, but wouldn't like to provide any methods exposing its iternal state (anotherClasses array in this case). The test is going to test the state of the array, so we have to access it.

Is it considering as a good practice to provide a method, say

MyAnotherClass[][] getAnotherClasses(){
    retun anotherClasses;
}

with package-private visibility to use it only for testing? I'm kind of not sure about that. We introduce some annoying coupling between the class and its test...

Maybe there's a better approach to deal with that?

Why should Selenium be selected as a test tool?

Selenium

is free and open source have a large user base and helping communities have cross Browser compatibility (Firefox, chrome, Internet Explorer, Safari etc.)

Run acceptance tests multiple times to find success ratio (java)

I have a package of JUnit classes that represent my acceptance tests. I am coding a simulation with some randomness and I discovered that for a few of these tests there is a small probability of failure.

What I'd like to do is to run all the tests in the package multiple times and store their success ratio in a csv file.
Each line would be the name of the test and the success ratio.

Is there an automated way to do this with JUnit or Gradle (which I am using for this project)?

What are the benefits of Automation Testing?

I want to know that why we go for automation though it is not reliable.Manual testing is more reliable then automation testing.

Testing uniqueness of unique immutable objects in JUnit

I have a LicenseNumber class which is immutable and is guaranteed unique, in that if a second license number is created with the same Name and year of issue, an arbitrary serial on the end of the number will increment by 1 each time. I'm trying to test the class using JUnit as follows:

public class LicenseNumberTest {

    Name name;
    int year;
    LicenseNumber number;
    LicenseNumber dupe;

    @Before
    public void setUp() {
        name = new Name("Joe", "Bloggs");
        year = 1994;
        number = LicenseNumber.getInstance(name, year);
        dupe = LicenseNumber.getInstance(name, year);
    }

    @Test
    public void getInitialsTest() {
        assertEquals("Initials should be JB", "JB", number.getInitials());
    }

    @Test
    public void getYearTest() {
        assertEquals("Year should be 1994", 1994, number.getYear());
    }

    @Test
    public void getSerialTest() {
        assertEquals("Serial should be 0", 0, number.getSerial());
    }

    @Test
    public void uniquenessTest() {
        assertEquals("Serial should now be 1", 1, dupe.getSerial());
    }

}

Now the problem is the getSerial and uniqueness test methods are not returning what I would expect. Sometimes they pass, but often they fail because the serial is one or two numbers higher than it should be. If I create another class with a main method and do these tests 'manually' so to speak, and print output to the console, everything works just fine. But we are supposed to be using JUnit to test our classes.

Now I'm not experienced with JUnit so I'm assuming I'm doing something wrong or missing something here? I've tried initialising a new LicenseNumber object directly inside each test method, tried adding an @After method to reset all objects to null, but nothing works. I can't seem to find any other questions relating to this either.

I have some logical questions regarding TestComplete

I have some questions regarding testcomplete. Kindly guide me some insight on them.

  1. Which language is better for complex programming and exception handling?

  2. What is the purpose of using aliases when object mapping is already done?

  3. Can I highlight objects when tests are running?

Access a rectangular in svg using selenium java

I want to access a rectangular in a svg using.I should specify i have several svg on the same page. Here is what i want to access:

<svg id="raphael-paper-252" height="239" version="1.1" width="399" xmlns="http://ift.tt/nvqhV5" style="overflow: hidden; -moz-user-select: none; cursor: default; position: relative; left: -0.5px; top: -0.5px; background-color: rgb(255, 255, 255);">
<desc>Scrollable Dual Y-Axis Combination Chart</desc>
<defs>
<g class="raphael-group-253-background">
<g class="raphael-group-260-canvas">
<g class="raphael-group-266-axisbottom">
<g class="raphael-group-266-axisbottom">
<g class="raphael-group-254-dataset" style="" clip-path="url('#0EF0615E-B63E-4B86-BCB3-DA1B99BCD97A')" transform="matrix(1,0,0,1,0,0)">
<g class="raphael-group-267-axistop">
<g class="raphael-group-495-scroll">
<g class="raphael-group-259-datalabels" style="" clip-path="url('#32ADDEF9-19E1-4425-A700-753A4E192433')" transform="matrix(1,0,0,1,0,0)">
<g class="fusioncharts-legend" transform="matrix(1,0,0,1,95,181)" style="">
<g class="raphael-group-255-hot" style="" clip-path="url('#FF53AB95-4DD3-4307-A757-AEC8F0979452')" transform="matrix(1,0,0,1,0,0)">
<g class="raphael-group-316-col-hot">
<rect style="cursor: pointer; stroke: rgb(192, 192, 192); stroke-opacity: 0.000001; fill-opacity: 0.000001; fill: rgb(192, 192, 192);" x="90.5" y="118.5" width="25" height="5" rx="1" ry="1" stroke="#c0c0c0" stroke-opacity="0.000001" stroke-width="1" fill-opacity="0.000001" fill="#c0c0c0"/>

For a smaller path i used this

    WebElement svgElement = OpenBrowser.driver.findElement(By.cssSelector("svg"));  

                 // Get the Buttons with which we want to interact in a list  
                 List<WebElement> gElements = svgElement.findElements(By.cssSelector("g"));  


                 WebElement button = gElements.get(7);
                 Actions actionBuilder = new Actions(OpenBrowser.driver);
                 actionBuilder.click(button).build().perform();  

and it worked but when i try this

WebElement svgElement = svg.findElement(By.cssSelector("svg"));  

 // Get the Buttons with which we want to interact in a list  
 List<WebElement> gElements = svgElement.findElements(By.cssSelector("g"));  

 System.out.println(gElements.size());


List<WebElement> button1 =  gElements.get(9).findElements(By.cssSelector("g"));
System.out.println(button1.size());
List<WebElement> button2 = button1.get(1).findElements(By.cssSelector("rect"));
WebElement button = button2.get(4);

 Actions actionBuilder = new Actions(OpenBrowser.driver);
 actionBuilder.click(button).build().perform();  

for the path above it throws me index out of bounds. I think it takes the first svg not the one i want.i tried accessing the element the svg is in first but it dosent find it :

WebElement svg = OpenBrowser.driver.findElement(By.cssSelector("#box_w3 > div > div.widget-body > div > div"));

I also tried using xpath and absolute still nothing. Any help is appreciated. Thanks in advance :)

bugs when it comes for verification?

What are the factors to set reproduction count for "Sporadic / Once / Frequently" bugs when it comes for verification?

For example: once factor is "blocker ticket", it needs to have more reproduction count.

In tsung how to send message to pidgin emulator

I have written a XML code connected to ejabberd using tsung and using pidgin to test now i want to send message saying hi and it must pop up in to pidgin emulator how can i do that?? please help me

mercredi 27 avril 2016

swifi fault injection command

I'm adding some new module in Minix 3, and I want to check if the new module affect the self repairing property of the minix 3 .

i read that i can use swifi injection tool to fire some failure in drivers.but i guess i'am not able to use it in a correct way,for example when i run command like: "swifi -f /usr/sbin/dp8390 5 Ransom_fault 5 20"

it reurns :

  • fault_injection_returned 0 (0)
  • 0 failure and 0 error

can anyone help me ,how to use swifi or what is wrong with the command i typed.

Javascript Testing With Unique ID's

I am kinda new to testing javascript and I was wondering what is the best way to go about testing something where a unique ID is generated.

EDIT:

I don't really want to test the ID I want to make sure that the action returns the right results when the createQuestion function is called. But the test will fail because the ID will never match since it is generated in the function.

My current code looks like this.

//------- Action Creator --------//

export const createQuestion = function (inputType) {
  const hasOptions = /radio/g.test(inputType);
  return {
    type: types.CREATE_QUESTION,
    question: {
      id: uuid.v1(),
      priority: null,
      title: null,
      tip: null,
      required: false,
      isSaved: false,
      hasOptions: hasOptions,
      input: {
        type: inputType,
        options: []
      }
    }
  };
};


//------- TESTS --------//
test('Question Actions', nest => {

  nest.test('Create Question', function (assert) {
    const msg = 'Questions was Created';

    const question = {
      id: 1,
      priority: null,
      title: null,
      tip: null,
      required: false,
      isSaved: false,
      hasOptions: false,
      input: {
        type: 'text',
        options: []
      }
    };

    const expectedAction = {
      type: types.CREATE_QUESTION,
      question
    };


    const actualAction = actions.createQuestion('text');
    assert.deepEqual(actualAction, expectedAction, msg);
    assert.end();
  });

Since the Unique Id is generated in the Action Creator it is impossible to mock unless I change the ID after the function returns with the action.

With something like this

const changeUUID = obj => {
  const newobj = {...obj};
  newobj.question.id = 1;
  return newobj;
};

Why use JUnit test suites?

I'm going to be implementing some unit tests using JUnit in some upcoming tasks for work. I have slight experience with JUnit from my previous employer, but while I was studying, I came across test suites. I don't have any idea if I'll be using them, but I was particularly interested in why they even exist.

Can someone give me a practical situation where I'd ever want to use a test suite, and also, what are advantages of using test suites as opposed to just using various independent tests?

EDIT: I feel this question isn't a duplicate since other answers to similar questions give a general definition, or a code snippet (as far as I could see) and I'm looking for a more practical use of suites from a design perspective. I'd like to know why bundling tests together may be a good idea, or why it may not be, etc.

Rails failure to load shoulda-matchers 3.1.1 gem, undefined method `allow_value' for #

'shoulda-matchers' gem is not loading when running rspec tests.

Error: NoMethodError: undefined method 'allow_value' for #<RSpec::ExampleGroups::Contact::ActiveModelValidationss:0x007fef1021b310>

versions being used: Ruby 2.2.2 Rails 4.2.1 shoulda-matchers 3.1.1

Gemfile:

source 'https://rubygems.org'

gem 'rails', '4.2.1'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

group :development, :test do
  gem 'byebug'
  gem 'rspec-rails', '~> 3.0'
  gem 'factory_girl_rails'
  gem 'shoulda-matchers', '~> 3.1'
  gem 'web-console', '~> 2.0'
  gem 'spring'
  gem 'rubocop', require: false
end

rails_helper.rb:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!

  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :active_record
      with.library :rails
    end
  end
end

spec_helper.rb:

RSpec.configure do |config|
  require 'factory_girl_rails'
  require 'shoulda/matchers'
  config.include FactoryGirl::Syntax::Methods
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end

contact_spec.rb:

require 'spec_helper'

describe Contact do

  FactoryGirl.define do
    factory :contact do
      first_name "Alice"
      last_name  "Bob"
      email_address "alicebob@example.com"
      phone_number "555-555-5555"
      company_name "ExampleCompany"
    end
  end

  it "has a valid factory" do
    expect(build(:contact)).to be_valid
  end

  describe "ActiveModel validations" do
    it { expect(:contact).to allow_value("alice_bob@example.com").for(:email_address) }
  end
end

Sorry for all the code. Please note I am using shoulda-matchers version 3.1.1 and adding 'require: false` to the gemfile is no longer needed as noted here http://ift.tt/1KKrQGf

I have also tried adding shoulda-matchers to its own test environment in the Gemfile as below but found no change

group :test do
  gem 'shoulda-matchers', '~> 3.1'
end

I've looked online and have found similar problems with solutions that don't work in my case. Any help or advice would be great!

Testing 'DAG' aka acyclic graphs properties in Haskell QuickCheck

module Graph where

import Control.Monad.State
import Data.Maybe
import Data.Set as Set

-- | 'Edge' represents an edge entre two nodes.
data Edge v = Edge {source :: v, target :: v}
              deriving (Show,Eq,Ord)

data Graph v = Graph {nodes :: Set v, edges :: Set (Edge v)}
               deriving Show

-- | 'Eq' for graphs.
instance Ord v => Eq (Graph v) where
    g == g' = nodes g == nodes g' && edges g == edges g'

isValid :: Ord v => Graph v -> Bool
isValid g = (Set.map source (edges g) `Set.union` Set.map target (edges g)) `isSubsetOf` nodes g

-- | 'isDAG' tests if a graph is acyclic
isDAG :: Ord v => Graph v -> Bool
isDAG g = isValid g && all nocycle (nodes g)
    where nocycle v = all (\a -> v `notMember` reachable g a) $ Set.map target (adj g v)

I'm trying to use QuickCheck to test 'isDAG', could you give me an property that 'isDAG' abides?

prop_isDAG :: Graph Int -> Property
prop_isDAG g = 

I believe that's the accurate function declaration, if not, feel free to change it!


Here is another example that I've made for another function, to guide possible helpers on what i'm looking for:

-- | The function 'isSubgraphOf' tests if the first graph is subgraph of the second.
isSubgraphOf :: Ord v => Graph v -> Graph v -> Bool
isSubgraphOf g g' = isSubsetOf (nodes g) (nodes g') && isSubsetOf (edges g) (edges g')

And this is the QuickCheck property that it abides:

-- QuickCheck proprety to test 'isSubgraphOf'
prop_isSubgraphOf :: Graph Int -> Property
prop_isSubgraphOf g = forAll (elements $ elems $ nodes g) $ \v -> adj g v `isSubsetOf` edges g

Is there some tool to test PHP code against SQL injection, out of range values, etc? [duplicate]

This question already has an answer here:

At work we are building a micro-CMS based solely in PHP + MySQL. Even if we try to sanitize every user input data and test every function / method, we can make mistakes. For example, if we sanitize a string with a function, let's say:

$name_surname = sanitize_str($_POST["nameSurname"], "text", 50, null, "utf8");

function sanitize_str($input, $data_type, $length, $range=null, $encoding, ...){
    .... // do things.
    try(){
     ...
    }catch($e){
     ...
    }
    return $sanitized_string
}

let's imagine that I call directly

$name_surname = $_POST["nameSurname"];

I am completely open to SQL injection. Is there some automated tool that will take given URLs and will make tests in order to seek vulnerabilities? For example, detecting forms in the test URLs, autofilling the forms, submitting and finding if a MySQL error is generated.

Angular mock scope function in then

I am trying to test my controller, which creates a promise and acts upon its resolve. Unfortunately, in the then function it takes the function from a different scope than I would like it to. In my test:

it('should do sth', function () {
   $scope.foo=function(){
   return "a";
}
   SomeController.bar();

expect...
})

In my controller:

$scope.foo=function(){
return "b";}
function(){
     //all good here, "a" is returned
     var test=$scope.foo()
     return somePromiseFunction(data)
              .then(function (newData) {
                  //This function returns "b"
                  var item= $scope.foo();
    })
}

I tried adding a spy (with and without callFake and/or callThrough):

spyOn($scope, 'foo')

Browserstack Selenium Automation HUB

I am following browserstack's documentation on using automation and currently getting an error and am abit confused about the URI.

My code looks like the following:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumTest {
  class Program {
    static void Main(string[] args) {
      IWebDriver driver;
      DesiredCapabilities capability = DesiredCapabilities.Firefox();
      capability.SetCapability("browserstack.user", "USERNAME");
      capability.SetCapability("browserstack.key", "ACCESS_KEY");

      driver = new RemoteWebDriver(
        new Uri("http://ift.tt/1eU1sYp"), capability
      );
      driver.Navigate().GoToUrl("http://www.google.com");
      Console.WriteLine(driver.Title);

      IWebElement query = driver.FindElement(By.Name("q"));
      query.SendKeys("Browserstack");
      query.Submit();
      Console.WriteLine(driver.Title);

      driver.Quit();
    }
  }
}

I am confused about the uri http://ift.tt/1eU1sYp

I don't understand what is this URI ?

why is it needed for ?

why does this line of code http://ift.tt/1eU1sYp give me errors such as

"You must be authenticated to access this URL"

Status Code=403

The exact error is below

An exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll but was not handled in user code

Additional information: Unexpected error.

McAfee Web Gateway - Notification - Authentication Required

Authentication Required
<td class="contentData">

  You must be authenticated to access this URL.

</td>

urlprotocol = "http"; statuscode=403; if(statuscode==401 && urlprotocol == "ftp"){
  document.write("<form name=\"ftpform\" method=\"get\" action=\"\">");

  document.write("<table class=\"contentData\">");

  document.write("<tr><td class=\"contentData\" colspan=2>Please enter your credentials in the form below and click \"Access FTP\"

button if your browser doesn't present authentication prompt for FTP sites.");
  document.write("<tr><td class=\"contentData\">Username:</td><td><input type=\"text\"

id=\"ftpUsername\" name=\"ftpUsername\" size=40 />");
  document.write("<tr><td class=\"contentData\">Password:</td><td><input type=\"password\"

id=\"ftpPassword\" name=\"ftpPassword\" size=40 />");
  document.write("<tr><td class=\"contentData\" colspan=2 align=center><input type=\"button\" onclick=\"redirectToFTP();\"

value=\"Access FTP\" />");
  document.write("</table>");

  document.write("</form>");

} function redirectToFTP(){
  var username=unescape(document.getElementById("ftpUsername").value);

  var password=unescape(document.getElementById("ftpPassword").value);

  location.href = "ftp://"+username+":"+password+"@hub.browserstack.com:80/wd/hub/session"

}
<td class="infoData">

  <b>URL: </b><script type="text/javascript">break_line("http://ift.tt/26utpEP");</script><br />

</td>

Proxy: XXXXXXX

Rule: Authenticate: NTLM


I have just replaced the Proxy with XXXXXX

I am also using a real fully licensed Browserstack Account Username/Password, but for the purpose of this question have the examples there. "USERNAME" for username and "ACCESS_KEY" for password.

any feedback is much appreciated, thank you.

Logics Test Urgent

http://ift.tt/236DvY1

I really need help with question 13,14,15,16,17,18,19 and 20.

It used MUMPS programming language and if anyone could please help me with the correct answer. please click on the link and open the pdf file in order to see the questions

Maven test project on TeamCity does not open browser

So the problem is that when I'm running my test scripts on TeamCity server and it physically does not open browser but runs it in background. Is it possible to configure that it will open browser so I can see what's happening there?

Exclude Test from Travis

I'm working on a Maven based Java open source project hosted on Github. We use Travis for continuous integration.

Some of the more complex JUnit tests don't currently pass in the Travis environment though they do pass locally.

Question: Is there a quick and easy way to mark particular test classes or methods as "Do not run on Travis" so we can move forward while I figure out how to fix the Travis environment for these tests?

Attempting to perform Integration Test with Spring Data JPA Repositories returns NullPointerException

I am trying to write integration tests for a Spring 4 MVC project. In the project I am using Spring Data JPA Repositories and Hibernate.

Below are two files, the Integration Test itself and the Configuration for setting up my Persistence configuration.

PersistenceTestConfiguration.java

package <project>.cms.rest.test.configuration;

import <project>.cms.rest.entity.EntityMarker;
import <project>.cms.rest.repository.RepositoryMarker;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.hibernate3.encryptor.HibernatePBEEncryptorRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = {RepositoryMarker.class})
public class PersistenceTestConfiguration {

    @Bean
    public EntityManagerFactory entityManagerFactory() throws NamingException {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setJpaVendorAdapter(vendorAdapter);
        factoryBean.setPackagesToScan(EntityMarker.class.getPackage().getName());
        factoryBean.setDataSource(dataSource());
        factoryBean.afterPropertiesSet();
        return factoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws NamingException {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory());
        return transactionManager;
    }

    @Bean
    public HibernateExceptionTranslator exceptionTranslator() {
        return new HibernateExceptionTranslator();
    }

    @Bean
    public EmbeddedDatabase dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public StandardPBEStringEncryptor stringEncryptor() {
        String encryptionMasterPassword = System.getProperty("jaspyt.password", "testonly-password");

        StandardPBEStringEncryptor stringEncryptor = new StandardPBEStringEncryptor();
        stringEncryptor.setPassword(encryptionMasterPassword);

        HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();

        registry.registerPBEStringEncryptor("STRING_ENCRYPTOR", stringEncryptor);

        return stringEncryptor;
    }
}

ProjectServiceIntegrationTest.java

package <project>.cms.rest.test.service;

import <project>.cms.rest.enumeration.ProjectStatus;
import <project>.cms.rest.resource.CustomerResource;
import <project>.cms.rest.resource.PostalAddressResource;
import <project>.cms.rest.resource.ProjectResource;
import <project>.cms.rest.service.*;
import <project>.cms.rest.service.impl.ContactServiceImpl;
import <project>.cms.rest.service.impl.CustomerServiceImpl;
import <project>.cms.rest.service.impl.PostalAddressServiceImpl;
import <project>.cms.rest.service.impl.ProjectServiceImpl;
import <project>.cms.rest.test.configuration.PersistenceTestConfiguration;

import liquibase.Liquibase;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
import liquibase.resource.FileSystemResourceAccessor;
import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.sql.Connection;

@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfiguration.class })
public class ProjectServiceIntegrationTest {

    @InjectMocks
    private ContactService contactService = new ContactServiceImpl();

    @InjectMocks
    private PostalAddressService postalAddressService = new PostalAddressServiceImpl();

    @InjectMocks
    private ProjectService projectService = new ProjectServiceImpl();

    @InjectMocks
    private CustomerService customerService = new CustomerServiceImpl();

    private CustomerResource dbCustomer;
    private PostalAddressResource dbPostalAddress;

    @Inject
    private EmbeddedDatabase dataSource;

    @Before
    public void setupDB() throws java.sql.SQLException, LiquibaseException {
        MockitoAnnotations.initMocks(this);

        Connection connection = dataSource.getConnection();
        JdbcConnection liquibaseConnection = new JdbcConnection(connection);

        Liquibase liquibase = new Liquibase(
                "src/liquibase/liquibase-master.xml",
                new FileSystemResourceAccessor(),
                liquibaseConnection
        );

        liquibase.update("");

        dbPostalAddress = new PostalAddressResource();
        dbPostalAddress.setBuildingNameOrNumber("1");
        dbPostalAddress.setFirstLine("Test Lane");
        dbPostalAddress.setSecondLine("Testville");
        dbPostalAddress.setCountry("Testshire");
        dbPostalAddress.setPostCode("TE5 7ER");
        dbPostalAddress.setCountry("United Kingdom");

        dbPostalAddress = postalAddressService.createPostalAddress(dbPostalAddress);

        dbCustomer = new CustomerResource();
        dbCustomer.setSiteAddress(dbPostalAddress);
        dbCustomer.setContactAddress(dbPostalAddress);
        dbCustomer.setBillingAddress(dbPostalAddress);
        dbCustomer.setName("Test Customer");

        dbCustomer = customerService.createCustomer(dbCustomer);
    }

    @After
    public void tearDown() throws java.sql.SQLException, LiquibaseException     {
        Connection connection = dataSource.getConnection();
        JdbcConnection liquibaseConnection = new JdbcConnection(connection);

        Liquibase liquibase = new Liquibase(
                "src/liquibase/liquibase-master.xml",
                new FileSystemResourceAccessor(),
                liquibaseConnection
        );

        liquibase.dropAll();
    }

    @Test
    public void testProjectCount() {
        Assert.assertTrue(projectService.countAllProjects() == 0);
    }

    @Test
    public void testAddNullProject() {
        ProjectResource result = projectService.createProject(null);

        Assert.assertNull(result);
    }

    @Test
    public void testAddProjectWithNoCustomer() {
        ProjectResource newProject = new ProjectResource();

        newProject.setOrderNumber("abc123");
        newProject.setQuoteNumber("123/45");
        newProject.setChargeable(true);
        newProject.setGrossValue(12000L);
        newProject.setNetValue(10000L);
        newProject.setStatus(ProjectStatus.PROVISIONAL);
        newProject.setCustomer(null);

        ProjectResource result = projectService.createProject(newProject);

        Assert.assertNull(result);
    }

    @Test
    public void testAddProject() {
        ProjectResource newProject = new ProjectResource();

        newProject.setOrderNumber("abc123");
        newProject.setQuoteNumber("123/45");
        newProject.setChargeable(true);
        newProject.setGrossValue(12000L);
        newProject.setNetValue(10000L);
        newProject.setStatus(ProjectStatus.PROVISIONAL);
        newProject.setCustomer(dbCustomer);

        ProjectResource result = projectService.createProject(newProject);

        Assert.assertNotNull(result);
    }
}

The issue I'm having is that although my PersistenceTestConfiguration class should be instantiating the appropriate Repositories - they are coming through into the service classes as null.

If I manually @Mock the repositories in the Test Class then they are no longer null in the services, but will always return null on for example calling the .save(entity) method.

I suspect I'm doing something obviously stupid but can't seem to figure it out.

Any pointers in the right direction would be kindly appreciated.

run tox on different python patch versions

in short: Is there a way to have tox cycle on patch versions of python ?

long: I want the tests to be run on 2.7.7, 2.7.8, and so on, basically I'm staging on 2.7.6 and want to see if I can get rid of this warning

http://ift.tt/193fQCj

before going into production

( of course I've already tested it "by hand" with pyenv, setting 2.7.x as global building a virtualenv and testing into it, but it would be nice to have continuous integration run every time all the possible combinations )

How to apply Sandwich Testing When no. of layers are more than 3

I was studying sandwich testing. And I found a question asked in many lectures I downloaded. How would you select a target layer, when no of layers is greater than 3?

I have searched a lot for the answer. But couldn't find any satisfactory answer. The only thing i found out is to use heuristic approach. I don't know what it is and how to use it. And secondly, in the figure below, In modified sandwich testing. It test (A,B), (A,C) together but not (B,E) and (B,F). Why? enter image description here

getEntityManager in PHPunit class test

I am in my phpunit test class extending Symfony\Bundle\FrameworkBundle\Test\KernelTestCase

I would like to get the entityManager to get some data in the database.

How can I do that?

It looks like I have to initialize the parent::kernel, but I dont know what 4 arguments I should pass to the constructor.

Thank you

Rails: How to test delegated methods?

After I've reworked my rails app I ran in some errors in my tests which I can not figure out. I thought that through "delegate" Rails magically knows even in testing which test data is to use, to test and that I don't have to declare those delegated data in the fixtures again (since I haven't found anything about it). Since I'm using the scaffolded tests I assumed that they should at least work seamlessly - probably a nooby idea...

Maybe you have an idea? Thanks in advance!

Here the models:

class Box < ActiveRecord::Base
  belongs_to :practice
  delegate :prac_name, to: :practice

  has_many :students

  validates :practice_id, presence: true
  validates :box_name,    presence: true, length: { in: 2..20 }
end

class Practice < ActiveRecord::Base
  has_many  :boxes

  validates :prac_name, presence: true, length: { in: 5..50 }
end

The controller:

# GET /boxes
def index
  @boxes = Box.all.order(box_name: :asc)
end

The view:

<tbody>
  <% @boxes.each do |box| %>
    <tr>
      <td><%= box.box_name %></td>
      <td><%= box.prac_name %></td>
      <td><%= link_to 'Show', box %></td>
      <td><%= link_to 'Edit', edit_box_path(box) %></td>
      <td><%= link_to 'Delete', box, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
</tbody>

The fixtures:

# box
one:
  box_name: MyString
  practice_id: 1

two:
  box_name: MyString
  practice_id: 1

# practice
one:
  prac_name: MyString

two:
  prac_name: MyString

And here the test:

test 'should get index' do
  get :index
  assert_response :success
  assert_not_nil assigns(:boxes)
end

The result is that I get this error message from guard/minitest for "get index" and "show box". Why is practice nil? (ActionView::Template::Error: Box#prac_name delegated to practice.prac_name, but practice is nil) Isn't it declared through the practice fixture? Apparently not but why?

ERROR["test_should_get_index", BoxesControllerTest, 3.196711939992383]
 test_should_get_index#BoxesControllerTest (3.20s)
ActionView::Template::Error:         ActionView::Template::Error: Box#prac_name delegated to practice.prac_name, but practice is nil: #<Box id: 298486374, box_name: "MyString", created_at: "2016-04-27 07:54:37", updated_at: "2016-04-27 07:54:37", practice_id: 1>
            app/models/box.rb:3:in `rescue in prac_name'
            app/models/box.rb:3:in `prac_name'
            app/views/boxes/index.html.erb:17:in `block in _app_views_boxes_index_html_erb__3226877961716035159_70232972217220'
            activerecord (4.2.6) lib/active_record/relation/delegation.rb:46:in `each'
            activerecord (4.2.6) lib/active_record/relation/delegation.rb:46:in `each'
            app/views/boxes/index.html.erb:14:in `_app_views_boxes_index_html_erb__3226877961716035159_70232972217220'
            actionview (4.2.6) lib/action_view/template.rb:145:in `block in render'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'
            activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'
            actionview (4.2.6) lib/action_view/template.rb:333:in `instrument'
            actionview (4.2.6) lib/action_view/template.rb:143:in `render'
            actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
            actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'
            activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'
            actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
            actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
            actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
            actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:52:in `render_template'
            actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:14:in `render'
            actionview (4.2.6) lib/action_view/renderer/renderer.rb:46:in `render_template'
            actionview (4.2.6) lib/action_view/renderer/renderer.rb:27:in `render'
            actionview (4.2.6) lib/action_view/rendering.rb:100:in `_render_template'
            actionpack (4.2.6) lib/action_controller/metal/streaming.rb:217:in `_render_template'
            actionview (4.2.6) lib/action_view/rendering.rb:83:in `render_to_body'
            actionpack (4.2.6) lib/action_controller/metal/rendering.rb:32:in `render_to_body'
            actionpack (4.2.6) lib/action_controller/metal/renderers.rb:37:in `render_to_body'
            actionpack (4.2.6) lib/abstract_controller/rendering.rb:25:in `render'
            actionpack (4.2.6) lib/action_controller/metal/rendering.rb:16:in `render'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
            activesupport (4.2.6) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
            /Users/andy/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
            activesupport (4.2.6) lib/active_support/core_ext/benchmark.rb:12:in `ms'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
            activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:43:in `render'
            actionpack (4.2.6) lib/action_controller/metal/implicit_render.rb:10:in `default_render'
            actionpack (4.2.6) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
            actionpack (4.2.6) lib/abstract_controller/base.rb:198:in `process_action'
            actionpack (4.2.6) lib/action_controller/metal/rendering.rb:10:in `process_action'
            actionpack (4.2.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
            activesupport (4.2.6) lib/active_support/callbacks.rb:117:in `call'
            activesupport (4.2.6) lib/active_support/callbacks.rb:117:in `call'
            activesupport (4.2.6) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
            activesupport (4.2.6) lib/active_support/callbacks.rb:505:in `call'
            activesupport (4.2.6) lib/active_support/callbacks.rb:505:in `call'
            activesupport (4.2.6) lib/active_support/callbacks.rb:92:in `__run_callbacks__'
            activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'
            activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
            actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in `process_action'
            actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:in `process_action'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'
            activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
            activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'
            actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
            actionpack (4.2.6) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
            activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
            actionpack (4.2.6) lib/abstract_controller/base.rb:137:in `process'
            actionview (4.2.6) lib/action_view/rendering.rb:30:in `process'
            actionpack (4.2.6) lib/action_controller/test_case.rb:639:in `process'
            actionpack (4.2.6) lib/action_controller/test_case.rb:67:in `process'
            actionpack (4.2.6) lib/action_controller/test_case.rb:514:in `get'
            test/controllers/boxes_controller_test.rb:9:in `block in <class:BoxesControllerTest>'
            minitest (5.8.4) lib/minitest/test.rb:108:in `block (3 levels) in run'
            minitest (5.8.4) lib/minitest/test.rb:205:in `capture_exceptions'
            minitest (5.8.4) lib/minitest/test.rb:105:in `block (2 levels) in run'
            minitest (5.8.4) lib/minitest/test.rb:256:in `time_it'
            minitest (5.8.4) lib/minitest/test.rb:104:in `block in run'
            minitest (5.8.4) lib/minitest.rb:331:in `on_signal'
            minitest (5.8.4) lib/minitest/test.rb:276:in `with_info_handler'
            minitest (5.8.4) lib/minitest/test.rb:103:in `run'
            minitest-reporters (1.1.8) lib/minitest/reporters.rb:48:in `run_with_hooks'
            minitest (5.8.4) lib/minitest.rb:778:in `run_one_method'
            minitest (5.8.4) lib/minitest.rb:305:in `run_one_method'
            minitest (5.8.4) lib/minitest.rb:293:in `block (2 levels) in run'
            minitest (5.8.4) lib/minitest.rb:292:in `each'
            minitest (5.8.4) lib/minitest.rb:292:in `block in run'
            minitest (5.8.4) lib/minitest.rb:331:in `on_signal'
            minitest (5.8.4) lib/minitest.rb:318:in `with_info_handler'
            minitest (5.8.4) lib/minitest.rb:291:in `run'
            minitest (5.8.4) lib/minitest.rb:152:in `block in __run'
            minitest (5.8.4) lib/minitest.rb:152:in `map'
            minitest (5.8.4) lib/minitest.rb:152:in `__run'
            minitest (5.8.4) lib/minitest.rb:129:in `run'
            minitest (5.8.4) lib/minitest.rb:56:in `block in autorun'
            /Users/andy/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            /Users/andy/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            -e:1:in `<main>'

Thanks!

Automation - Interactive Services Detection

Have a bit of a problem. Im using Jenkins on a VM to run some automation tests.

The goal is to have zero human interaction so I can literally just run the Jenkins job and have all the tests run on there own.

However, I'm having a problem with the Interactive Services Detection which pops up when the tests are run. This means it involves human interaction before the tests can run fully. The tests are for testing a website so I want the browser to open and run as if it was being done by a human as it being run headlessly to me isn't the same and wont provide the same results.

I have disabled it but if I disable it, Jenkins will run headlessly which is not what I want.

Never had an issue like this before so if anyone could shine some light on it would be great.

Thanks in advance.

mardi 26 avril 2016

How to configure selendroid and test mobile application

I was trying to implement Selendroid in my pc. I do as follows 1.Installed JDK 2.Installed eclipse 3.Installed SDk 4.Created Environmental Variables 5.Created a Java Application in eclipse 6.Mapped Selendroid Standalone jar,Selendroid Standalone with dependencies, Selendroid Client and Selenium Client.I used the command in console as follows java -jar selendroid-standalone-0.17.0-with-dependencies -apk myapk.apk And verified status using http://localhost:4444/wd/hub/status.I created android application and was stuck after this,What do after this?

how to perform test to the GridView in onclick position

I write a testing to the Grid View to count the number of items in the grid. i want to perform onclick to the grid view

here is a my mainActivity class

public class MainActivity extends AppCompatActivity {

GridView gridView;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    gridView = (GridView) findViewById(R.id.gridview1);

    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Send intent to SingleViewActivity
            Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);

            // Pass image index
            i.putExtra("id", position);
            startActivity(i);
        }
    });

}
}

SingleViewActivity.Java

public class SingleViewActivity extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_view);

    // Get intent data
    Intent i = getIntent();

    // Selected image id
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);

    ImageView imageView = (ImageView) findViewById(R.id.SingleView);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
}

ImageAdapter.java

public class ImageAdapter extends BaseAdapter {
private Context mContext;

// Constructor
public ImageAdapter(Context c) {
    mContext = c;
}

@Override
public int getCount() {
    return mThumbIds.length;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    }
    else
    {
        imageView = (ImageView) convertView;
    }
    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}


public Integer[] mThumbIds = {
        R.drawable.images, R.drawable.asdawe,
        R.drawable.bokey, R.drawable.assd,
        R.drawable.download, R.drawable.ew,
        R.drawable.lilly, R.drawable.jh,
        R.drawable.rose, R.drawable.we,
        R.drawable.lilly1, R.drawable.images,
        R.drawable.bokey, R.drawable.asdawe,
        R.drawable.download, R.drawable.ew,
        R.drawable.jh, R.drawable.lilly,
        R.drawable.rose, R.drawable.we,
        R.drawable.lilly1, R.drawable.images
};
}

MainActivityTest.java

public class MainActivityTest extends ActivityInstrumentationTestCase<MainActivity> {

private MainActivity mActivity;
private GridView mGridView;
private Instrumentation mInstrumentation;
public MainActivityTest() {
    super("com.android.frameworks.coretests", MainActivity.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();

    mActivity = getActivity();
    mGridView = (GridView) mActivity.findViewById(R.id.gridview1);
    mInstrumentation = getInstrumentation();
}
@MediumTest
public void testPreconditions() {
    assertNotNull(mActivity);
    assertNotNull(mGridView);
}
@LargeTest
public void testSetSelection() {
    mGridView = new GridView(mActivity);
    mGridView.setSelection(0);
    assertEquals(0, mGridView.getSelectedItemPosition());
    mGridView.setSelection(-1);
    assertEquals(-1, mGridView.getSelectedItemPosition());
    mGridView.setSelection(mGridView.getCount());
    assertEquals(mGridView.getCount(), mGridView.getSelectedItemPosition());
}

@Test
public void testSetSelectionone() {
    TouchUtils.dragQuarterScreenDown(this);
    TouchUtils.dragQuarterScreenUp(this);

    // Nothing should be selected
    assertEquals("Selection still available after touch", -1,
            mGridView.getSelectedItemPosition());

    final int targetPosition = mGridView.getAdapter().getCount() ;

    assertEquals(22,targetPosition);
}


}

i want a test for the on click on the Grid View

Protractor: Test failing when values are equal to each other

Below is my protractor test that opens a dialog in an angular application. It adds correctly but the test fails even when the values are equal to each other.

I want to say it might have something to do with the whole ignoringSynchronization but then I run into the whole timeout waiting for the synchronization with the modal dialog that pops up or something.

The message is: Expected 'Potato' to equal 'Potato'. These are all just dummy values but yeah just to get the gist of it.

describe('someTest', function(){
// beforeEach(function(){
//     browser.get("url");

// })

it('Add Test', function(){
    browser.get("url");
    var testEle = element(by.model('ng-model'));
    testEle.$('[value="0"]').click();

    browser.waitForAngular();
    //grabbing first object from the ng-repeat
    testEle = element(by.repeater("ng-repeat").row(0));
    testEle.element(by.tagName('span')).click();

    //A modal dialog pops open with an input box so you can type stuff into it and will show options to auto complete
    //that you can click on

    //need this or else it will timeout waiting for angular to sync
    browser.ignoreSynchronization = true;


    var EC = protractor.ExpectedConditions;
    browser.wait(EC.elementToBeClickable(element(by.id('an_input_tag'))));
    testEle = element(by.id('an_input_tag'));
    testEle.sendKeys("Potat");
    browser.wait(EC.elementToBeClickable(element(by.id('input_auto_completes'))));
    testEle = element(by.id('input_auto_completes'));
    testEle.click();
    browser.wait(EC.elementToBeClickable(element(by.buttonText('Add'))));
    element(by.buttonText('Add')).click();

    browser.wait(EC.textToBePresentInElement(element(by.repeater("ng-repeat").row(0)), 'Potato'));
    testEle = element(by.repeater("ng-repeat").row(0)).element(by.className('className'));
    expect(testEle.getText()).toEqual('Potato');

 })
}

Automation UI Test tool(Like selenium webdriver) for Silverlight webapp

Any pointers to any open source tools for testing Silverlight webapp.

I've gone through the net and so far found Telerik which isn't an opensource and Silvernium(Selenium+Silverlight) project.

But there aren't much people using Silvernium.

Are there any other options on going around with testing the Silverlight application apart from the above two?

How to really use PhoneGap with Xcode

I have been searching whole internet but there are tons of outdated things about this issue

I simply have PhoneGap project. some contents

And its working flawlesly when I use the PhoneGap app for my iPhone. Really perfectly!

So I want to really try it and test it before I maybe purchase dev acc. But I don't know how to test it and upload the contents of PhoneGap project (which is nearly basicaly HTML and CSS website) to my iPhone.

I can do it just for my device to send a project from xcode to my iPhone. But it "god damnned!!!" does not look like from the PhoneGap "emulator" or what so ever. This is not right: http://ift.tt/1Tcti72 and this is far beyond working http://ift.tt/1SqKSYH

I can see that there is really some "Gap" and the know how is maybe "well paid" feature. So please how can I simply test the "contents" - app from PhoneGap. Its kind a template and then HTML website.

I see that there is lots of third party websites doing some mojo and magicaly wrap you HTML5 website, but when I wrap it as one of the tutorials above showed..its not what it supose to be. Xcode

And for example the Onsen.io templates are just broken.. Is there any working tutorial how to put PhoneGap project to iPhone through Xcode? for testing?

Hint: Adobe does not allows me to make an app without signing key..so.I cannot even test it. And even if...its an APK. file and that I cannot run either..useless.

What should I test specifically at cloud storage based mobile applications?

I am developing a sensor based mobile application for iOS and android. The data produced by smart phone sensors will be stored in the cloud. At this point, I am wondering that what I should test about the data transfer and storing. I mean that for example, I should test the scenario as if the connection corrupts while GPS data transfer not finished. I am not looking for the techniques, or testing styles. I am trying to find possible failure points or test scenarios. I hope that I could explain my point.

Thanks in advance. Fatih.

Testing for a Google Drive wrapper library

I recently wrote a library that wraps Google Drive API for Android. I would like to write some automated tests to make it more reliable and consistent during its evolution.

The library exhibits the same methods of the Google Drive API and returns the same objects. The only difference between this library and the APIs is the flow (in case you are asking why I did this).

For instance, I have a method getMetadata(DriveId driveId) that returns an object of class Metadata. This method is the wrapper for getMetadata() described and explained here.

Ignoring for a moment the fake authentication that I probably should provide in order to execute all the tests, in your opinion, what is the better way to test this kind of library?

How to test IOException and IllegalArgument Exception for Properties.load and getResourceasStream

Here is my code:

public class PropertiesRetriever {

private String foo;
private String foo1;
private Properties properties;

/**
 * Injects the properties file Path in the {GuiceModule}
 * Calls {@link PropertiesRetriever#loadPropertiesPath(String) to load the
 * properties file.
 * 
 * @param propertiesPath
 * @throws IOException
 */

@Inject
public PropertiesRetriever(@Named("propertiesPath") String propertiesPath, Properties properties)
    throws IOException {
this.properties = properties;
loadPropertiesPath(propertiesPath);
}

/**
 * Loads the properties file as inputstream.
 * 
 * @param path
 *            path of the properties file
 * @throws IllegalArgumentException
 * @throws NullPointerException
 * @throws IOException
 */
public void loadPropertiesPath(String path) throws IOException {
InputStream in = this.getClass().getResourceAsStream(path);
properties.load(in);

}

/**
 * Gets the value for foo from the properties file based on the
 * foo  as parameter.
 * 
 * @param -
 *            foo 
 * @return - foo value of foo in the properties file.
 * @throws IllegalArgumentException
 */
public String getfoo(String foo) {
Preconditions.checkArgument(StringUtils.isNotBlank(foo),
    ResourceAssistant.getString(PropertiesRetriever.class, "fooNullMessage"));
this.foo = properties.getProperty(foo);
return foo;
}

/**
 * Gets the value for foo1 from the properties file based on the
 * foo1 for repository as parameter.
 * 
 * @param -
 *            foo1
 * @return - foo1 value of foo1 in the properties file.
 * @throws IllegalArgumentException
 */
public String getfoo1(String foo1) {
Preconditions.checkArgument(StringUtils.isNotBlank(foo1),
    ResourceAssistant.getString(PropertiesRetriever.class, "foo1NullMessage"));
this.foo1 = properties.getProperty(foo1);
return foo1;
}

}

Here, two methods:

 properties.load(in)

and

this.getClass().getReqourceAsStream

throws IOException and IllegalArgumentException. I wanted to test these methods in JUnit testing. Is there anyway I can call these methods as this.class() returns the current class and when I tried to use doThrow in properties.load I got error of Overloading by mockito.

Mock python decorator in unit tests

I am trying to test a function that is decorated. Is there a way to mock a decorator and test function in isolation, when decorator is already applied?

import mock


def decorator(func):
    def wrapper(*args, **kwargs):
        return 1
    return wrapper


def mocked(func):
    def wrapper(*args, **kwargs):
        return 2
    return wrapper


@decorator
def f():
    return 0


with mock.patch('test.decorator') as d:
    d.side_effect = mocked
    assert f() == 2  # error