lundi 31 octobre 2016

Jest - testing redux actions

I'm trying to test my app's redux actions using Jest. I've looked at the testing site @ redux.js.org and other forums posts but I can't see why I'm getting the error I am, I think I'm not getting how the mocking works.

My action is in index.js:

export const setResponse = (res) => {
    return {
        type: 'RESPONSE_RECEIVED',
        payload: res
    }
};

My test is actions.test.js:

import * as actions from '../src/client/scripts/actions/index'

describe('actions', () => {
  it('should create an action to receive a response', () => {
    const payload = {response: 'solr_json'};
    const expectedAction = {
      type: 'RESPONSE_RECEIVED',
      payload
    }
    expect(actions.setResponse(payload)).toEqual(expectedAction)
  })
});

I got the error 'Expected undefined to equal Object...' soI thought actions.setResponse didn't exist, so I printed out actions.setResponse and it looks like this:

{ [Function: setResponse]
  _isMockFunction: true,
  getMockImplementation: [Function],
  mock: { calls: [], instances: [] },
  mockClear: [Function],
  mockReturnValueOnce: [Function],
  mockReturnValue: [Function],
  mockImplementationOnce: [Function],
  mockImpl: [Function],
  mockImplementation: [Function],
  mockReturnThis: [Function] }

So it seems the function is there, how do I actually call the function inside the Jest test? Even if I change

export const setResponse = (res) =>

to

export function setResponse(res)

(so it's the same format of the redux.js.org tutorial) I get the same error. For reference this is the jest part of my package.json:

"jest": {
    "scriptPreprocessor": "node_modules/babel-jest",
    "testFileExtensions": [
      ".test.js"
    ],
    "testPathDirs": [
      "__tests__"
    ],
    "moduleFileExtensions": [
      "js"
    ],
    "unmockedModulePathPatterns": [
      "node_modules/react",
      "node_modules/react-addons-test-utils",
      "node_modules/react-dom"
    ]
  }

Thanks for any help

Why isn't my database cluttered with artifacts from my Spring DBUnit tests?

I am currently testing my Spring repositories and decided to use a MariaDB server instance instead of an in-memory Derby instance because of some complications in a test that involved a database view.

While the tests eventually did succeed without errors and failures, I noticed that I didn't add a @DatabaseTeardown annotation to my test case. So I decided to check my database for unwanted rows leftover from the test and found that my database was just as empty as before the test.

Could someone here explain why this is happening?

jest unexpected reserved word import

I've seen plenty of other people with this issue and I've tried the fixes for them, but I can't seem to see why mine isn't working. I've followed the redux test page instructions and the babel Jest getting started page.

My app runs perfectly fine, but I get this error when trying to test it with Jest:

/home/ansah/Projects/amrit/webapp/src/server/server.js:6
import express  from 'express';
^^^^^^

SyntaxError: Unexpected reserved word

It seems that it needs transpiling first, which I do with babel when actually running the app. But it doesn't seem to work with testing. I added a .babelrc:

{
  "presets": [
    "es2015",
    "react"
  ]
}

Here's my package.json

{
  "name": "null",
  "version": "1.0.0",
  "description": "null",
  "repository": "none",
  "scripts": {
    "build": "browserify src/client/scripts/*.jsx -d -o src/client/app.js",
    "test": "npm run test-back && npm run test-front",
    "test:watch": "npm test -- --watch",
    "test-front": "jest",
    "test-back": "mocha"
  },
  "browserify": {
    "transform": [
      "babelify"
    ]
  },
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "jest": {
    "scriptPreprocessor": "./node_modules/babel-jest",
    "testFileExtensions": ["es6", "js"],
    "moduleFileExtensions": ["js", "json", "es6"]
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "crypto": "0.0.3",
    "express": "^4.14.0",
    "jquery": "^3.0.0",
    "json-fs-store": "^1.0.0",
    "mkdirp": "^0.5.1",
    "moment": "^2.14.1",
    "path": "^0.12.7",
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-modal": "^1.4.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "request": "^2.72.0",
    "shelljs": "^0.7.0",
    "solr-client": "^0.6.0",
    "winston": "^2.2.0"
  },
  "devDependencies": {
    "babel-jest": "^13.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babelify": "^7.2.0",
    "browserify": "^13.0.0",
    "chai": "^3.5.0",
    "chai-http": "^3.0.0",
    "eslint": "^2.1.0",
    "eslint-plugin-react": "^3.16.1",
    "jake": "^8.0.12",
    "jest": "^16.0.2",
    "jest-cli": "^13.0.0",
    "jsdom": "^9.2.1",
    "json-fs-store": "^1.0.0",
    "mocha": "^2.5.3",
    "mocha-jsdom": "^1.1.0",
    "react-addons-test-utils": "^15.2.0",
    "shortid": "^2.2.6",
    "sinon": "^1.17.4"
  }
}

Which also has the ES2015 presets in it under 'babel'.

My server.js is in this format:

(function() {
    "use strict";

    // Express
    const express = require('express');
    const app = express();
    const path = require('path');
    ...

    app.use('/', express.static(path.join(__dirname, '../client')));
    app.get('/search', require('./routes/search.js'));
    ...

    module.exports = app;

}());

Thanks for any help

How to console.log in Watir?

How can I log to console in watir? Or break in the code. Like Javascripts console.log or debugger statements.

puts doesn't seem to work for me.

How to reliably test OAuth2 login flow with protractor

I've been playing with protractor for the last few hours, the first test I've written is to test login via oauth2.

The problem is, when testing this manually, browser will remember my credentials after the first time and automatically finish the flow for me(by which I mean I don't have to type in username/password again). To go through the flow again, I typically have to clear browser data first.

I can't figure out how to do this with protractor though. With protractor, after the first time, I still have to send username and password, but protractor will automatically click login button for me. So the code below passes, but if I uncomment submitBtn.click();, the test will hang.

describe('login_with_github', function() {
    it('login with github oauth2', function() {
        browser.get('http://localhost:3001');
        element(by.css('.btn-login-with-github')).click();
        var loginField = element(by.id('login_field'));
        var passwordField = element(by.id('password'));
        var submitBtn = element(by.css('input.btn.btn-primary.btn-block'));
        browser.getAllWindowHandles().then(function(handles) {
                // switch to the newly openned window
                let oldWindowHandle = handles[0];
                let newWindowHandle = handles[1];
                browser.switchTo().window(newWindowHandle).then(function() {
                    browser.ignoreSynchronization = true;
                    expect(loginField.waitReady()).to.eventually.be.ok;
                    expect(passwordField.waitReady()).to.eventually.be.ok;
                    expect(submitBtn.waitReady()).to.eventually.be.ok;

                    loginField.sendKeys('username@gmail.com');
                    passwordField.sendKeys(password);
                    //submitBtn.click(); // can't do this after the first time.

                    browser.switchTo().window(oldWindowHandle).then(function() {
                        browser.driver.sleep(2000);

                        expect(element(by.css('.foo')).getText()).to.eventually.contain('bar');
                    });
                })
            })
       })
  })

I'm looking for a solution which can either mimic the manual test process, or resolve the protractor hanging problem, so that every time I run this spec it will fill in username/password, click signin button, wait for redirect and go back to main page.

Any advice is much appreciated!

Can it be considered bad practice to rely on automated tests running in order?

In my acceptance test suites specifically I see a lot of tests designed to run in a particular order (top to bottom) which in some ways makes sense for testing a particular flow, but I've also heard this is bad practice. Can anyone shed some light on the advantages and drawbacks here?

Mock method with generic type

I have a test that find all class that inherited from BaseClass. BaseClass has a property with a method that use generics:

abstract class BaseClass 
{
   public MyTools Tools { get; set;}

   public abstract List<TEntity> GetAll();

   public virtual IList<TEntity> Convert<TEntity, TEntityOther>() 
   {
       //...
   }
}

class MyTools 
{
   T List<T>();    
}

I need to mock the T List<T>() method. The method is used in Create method. For example:

class MyClass: BaseClass<MyEntity>
{
    public override List<MyEntity> GetAll()
    {
        var x = this.MyTools.List<SomeClass>();

        return this.Convert<MyEntity, SomeClass>(x);
    }
}

I don't know what type is used within GetAll to call List method.

This is my test:

var xobjects = this.GetTypeInNamespace(myAssembly, typeof(BaseClass<>));

foreach(var obj in xobjects) 
{
   var myTools  = new Mock<MyTools>();

   //here is my problem
   myTools.Setup(x => x.List< ANY >()).Returns(new List< ANY >());

   var iobj = this.CreateInstance(obj);

   iobj.MyTools = myTools.Object;  

   var result = iobj.GetType().GetMethod("GetAll").Invoke(iobj, null);

   ((ICollection)result).Count.Should().Be(0);
}

Software Reliability Testing

I am developing a Q&A web application and have implemented an expert recommendation algorithm to recommend experts based on the posted questions.

(1) How do i test the reliability of the algorithm?

(2) Which metric should i use to measure reliability of the algorithm ?

Laravel Testing with PHPUnit assert correct order

I have defined a scope which sorty my entities by a published_at timestamp. I wanted to write a test to ensure correct ordering.

However I somehow fail to find a "nice" way to do this.

$novels = Novel::published()->get();

This is my best guess

for($i = 1; $i < count($novels); $i++) 
{
    $this->assertGreaterThanOrEqual(
        $novels->toArray()[$i - 1]['published_at'], 
        $novels->toArray()[$i]['published_at']
    );
}

Can anyone provide a better way ?

Why pip does not check python version?

I'm running django tests on a large application. They require a test database, so I need to create a test database before running tests. But the problem is - because of some dependency problems the migration must be run in the following order: migrate app2, migrate app1, migrate. I know that I'm doing it wrong but I have no will and time to fix hundreds of migrations. The question is: how can I specify custom migration order to create test databases, that I would later use for each test run via --keep-db option?

PHPUnit Laravel InvalidArgumentException: Unable to locate factory with name [default] [App\User]

I have a setup function in a test which does the following

function setUp()
{
    $this->user = factory(User::class)->create();
}

ofcourse I used "use App\User;" at the very top.

This is my model factory

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

When runnning phpunit i get the error

InvalidArgumentException: Unable to locate factory with name [default] [App\User].

HOWEVER: If I go to php artisan tinker an run

factory(User::class)->create();

it works ... I tried App\User::class and other stuff and even putting it inside the test directly instead of the setUp method. The weird part is that another factory within the same file is working.

How to run database fixtures on acceptance tests with Behat, Mink and Zombie.js

I'm starting with acceptance testing using Behat (PHP version of Cucumber). I'm planning to run it using Mink and Zombie.js (for basic JS testing).

As far as I understand, Zombie is a headless browser that will output whatever my URL (localhost) returns, which Mink will use to traverse as a DOM element.

It doesn't really seem like I can pass ENV variables or run it with different kind of parameters, which renders me unable to do things like running fixtures or rolling back database changes before the test; unless I write a script to automatically change the database name in the app configuration before running, and change it back afterwards.

Any help, if possible with examples, will be appreciated.

How can I get IDs, names or x paths for ui elements used in a mobile app (Android/iOS) for mobile automation testing?

I want to know how can I get IDs or names of UI elements used in a mobile application that are used in mobile automation testing like appium, monkey-talk, xamarian etc.

Unit Testing for asp.net & angular2 separately

Please help me, do we have to write separate unit testing for Asp.net(C#) as well as Anguar2 (When you are taking care of both service and client side)

Use of unix and SQL in manual testing

I am new to manual testing and looking for a job. I was lookimg for some good references for UNIX and SQL required for manual testing. Also I would like to know day to day use of these two in real world projects like telecom and banking domains. Sorry, posting a question on stack overflow for the first time.

How to execute gradle with JDK 64bit, but run tests with JDK 32bit

I have a big project. It has more 400 submodules, therefore I really want to build it in parallel. However, build it in parallel with all available cores will require a lots of memory. Ideally, I should do that with a 64bit JDK to allocate maybe up to 16g memory for the building...

But some tests depend on 32bit native library. We need to run them with a 32 bit JRE..

Any idea to build the project with JDK 64 bit, but execute the tests with just 32bitJRE?

Many many thanks.

Interviewfor software tester

I have one year experience in software testing. I want to go to interview in mnc. What are the technical level interview questions for a software tester ? What are the practical questions for a software tester ? What should I learn for preparing for the interview ?

How to test an android app using monkey runner in ubuntu?

I'm new to android, and i am trying to learn monkey runner. Could anyone please guide me how to test an app using monkey runner in Ubuntu. I used android studio for developing my app. Thanks in advance.

How to mock a struct if you directly access its fields

I am writing a program that acts as a client of Github API. I use http://ift.tt/14QceB2 to access the API. I have a function that accepts a github.Client as one of the argumenta and uses it to retrieve commits from a pull request. I want to test this function with some fake data.

In the article here: http://ift.tt/2douGqG I read, that I should create an interface that would be implemented by github client, and then in my tests, create a mock that would also implement it. My problem is, that go-github uses the following semantics to retrieve pull request:

prs, resp, err := client.PullRequests.List("user", "repo", opt)

The interfaces however allow you to specify methods that should be implemented, but not fields. So how can I mock the github.Client object so it can be used in the above semantics?

How to work with the group comparator in mapreduce?

I've read these articles

What is the use of grouping comparator in hadoop map reduce

What is difference between Sort Comparator and Group Comparator in Hadoop?

so I somewhat understand how it works.

The problem is... When testing, without this line

driver.setKeyGroupingComparator(groupComparator);

I get the folowing output in the reducer.

0000000000_44137
902996760100000_44137
9029967602_44137
90299676030000_44137
9029967604_44137
905000_38704
9050000001_38702
9050000001_38704
9050000001_38705
9050000001_38706
9050000001_38714
9050000002_38704
9050000002_38706
9050000011_38704
9050000011_38706
9050000021_38702
9050000031_38704
9050000031_38705
9050000031_38714

With it, I get

0000000000_44137
902996760100000_44137
9029967602_44137
90299676030000_44137
9029967604_44137
905000_38704
9050000001_38702
9050000002_38704
9050000011_38704
9050000021_38702
9050000031_38704

The reducer)

@Override
    public void reduce(CompositeKey key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        System.out.println(key.getFirst() + "_" + key.getSecond());
    }

I understand it should be something along the lines of

0000000000 44137 value1
9050000001 38702 value1 38704 value2 38705 value3 38706 value4 38714 value5

but is

0000000000 44137 value1
9050000001 38702 value1 value2 value3 value4 value5

Where all right halves exept first one are lost. How do I iterate over every right part of the key? Is it possible?

My GroupComparator

public class GroupComparator extends WritableComparator {
    public GroupComparator() {
        super(CompositeKey.class, true);
    }
    @Override
    public int compare(WritableComparable a,
                       WritableComparable b) {
        CompositeKey lhs = (CompositeKey)a;
        CompositeKey rhs = (CompositeKey)b;
        return lhs.getFirst().compareTo(rhs.getFirst());
    }
}

dimanche 30 octobre 2016

Automation Testing Data Driven with Ranorex, Next Case When Validate Return False.

1)When I use feature "manage datasource" of Ranorex to data driven. If all case true, program will return success. But if i have a false case, it will stop program immediately and return error Validation failed. Ex : I have 3 case, case 1 is false. Output will be 1x Failed and 2x Blocked. So, I want to run all case including false case. Output will not be any case blocked. I tried using check variable to call Validate.Fail() but still not be. And i don't want to use normal connections by C# to Excel.

void ITestModule.Run(){
Host.Local.RunApplication("C:\\Users\\FSU1.TEST\\Downloads\\Calculator.exe", "", "C:\\Users\\FSU1.TEST\\Downloads", false);

        //run test Calculator
        Button btnX = "/form[@controlname='Calculator']/button[@controlname='Button"+_btn1+"']";
        btnX.Click();
        MyRepo.Calculator.ButtonTimes.Click();
        Button btnY = "/form[@controlname='Calculator']/button[@controlname='Button"+_btn2+"']";
        btnY.Click();
        MyRepo.Calculator.ButtonEqual.Click();

        //set result
        Text text = "/form[@controlname='Calculator']/?/?/text[@accessiblerole='Text']";

        //Validate result
        Validate.AreEqual(text.TextValue, value, "True");

        MyRepo.Calculator.ButtonClear.Click();
        MyRepo.Calculator.Close.Click();
}

And here is data binding data binding image

And another problem: 2)In which I have a column "result" to write result test. Can I use binding to write it ?

Thanks Sargon

How to run another node.js script and then kill it

I want my testing script to be able to run my server and then kill it at the end of testing. In fact I will probably want to do this mulitple times in the testing script. I tired exec with shelljs. But that seems to me from running any commands after I start my server for testing it also seems like it would be hard to find the sever to kill it after starting it (especially on different OSes). How might I do such a thing?

What is meant by test procedure?? Any example stating the same

What is meant by test procedure?? As of my knowledge hirearchy will be as follows Business requrements->highlevel scenerios or test conditions->Test cases-> Test procedure. So my asuption is test procedure is nothing but the test steps in test case. Am i right??

Making a wrapper for `mock.patch`

Some customized patches from mock.patch I want to use over and over without littering my test code with copy-pastes of the patch setup. e.g. this very handy patch of datetime.date, which would fill my code with

with patch('mymodule.date') as mock_date:
    mock_date.today.return_value = date(2010, 10, 8)
    mock_date.side_effect = lambda *args, **kw: date(*args, **kw)

How can I wrap this functionality into a one-line call?

Are there any existing libraries for side-by-side testing of java methods? [on hold]

I'm refactoring an old utility class, and I want to make sure I haven't broken the method contract at all. To that end, I'm trying to call both methods with identical inputs (generated by QuickCheck) and compare both the resulting output, but any side-effects applied to the input, or exceptions thrown.

The code to do this for each method would be quite a bit to copy-paste, and I'm sure it can be done "better" with a reflection-based utility utilising mocks and/or spies.

import java.util.Date;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

...

@Property
public void testDateAdd(
        Date date,
        Integer amount,
        @InRange(minInt = 0, maxInt = 15) Integer field

) throws Exception {

    final Date date1 = new Date(date.getTime());
    final Integer amount1 = new Integer(amount);
    final Integer field1 = new Integer(field1);
    Date result1 = null;
    Exception error1 = null;

    try {
        result1 = DateFunctionsOriginal.dateAdd(date1, amount1, field1);

    } catch (Exception error) {
        error1 = error;
    }

    final Date date2 = new Date(date.getTime());
    final Integer amount2 = new Integer(amount);
    final Integer field2 = new Integer(field1);
    Date result2 = null;
    Exception error2 = null;

    try {
        result2 = DateFunctions.dateAdd(date2, amount2, field2);

    } catch (Exception error) {
        error2 = error;
    }

    assertThat(date1, is(equalTo(date2)));
    assertThat(amount1, is(equalTo(amount2)));
    assertThat(field1, is(equalTo(field2)));
    assertThat(error1, error2 == null ? is(nullValue()) : isA(error2.getClass()));
    assertThat(result1, is(equalTo(result2)));

}

Not perfect, but that's what I'm looking at for all 200 or so methods, and while I love a good challenge, I'd like to avoid 'rolling my own' if I can help it.

org.springframework.web.bind.MissingServletRequestParameterException Spring MVC Mockito test fail

I have a problem with writing a test, to test my controller method. Here is my controller method:

@RequestMapping(value = "/customer/filter", method = RequestMethod.POST)
public String listCustomersSpecifiedByOrderCost(@RequestParam("filterValue") Double filterValue, Model model) {
    model.addAttribute("customers", customerService.listCustomersSpecifiedByOrders(filterValue));
    return "customersfiltered";
}

And there is my test:

@Test
public void testCustomersSpecifiedByOrderCost() throws Exception{
    List<Customer> customers = new ArrayList<>();
    customers.add(new Customer(1, "test1", "test1", "address1", 300.43));
    customers.add(new Customer(2, "test2", "test2", "address2", 340.43));
    customers.add(new Customer(3, "test3", "test3", "address3", 360.43));

    when(customerService.listCustomersSpecifiedByOrders(320.00)).thenReturn((List) customers);

    mockMvc.perform(post("/customer/filter"))
            .andExpect(status().isOk())
            .andExpect(view().name("customersfiltered"))
            .andExpect(model().attribute("customers", hasSize(2)));

}

The error is: org.springframework.web.bind.MissingServletRequestParameterException: Required Double parameter 'filterValue' is not present

The error status is 400

I don't know Mockito very well, how to test it properly?

samedi 29 octobre 2016

How to analyse junit test results in netbeans

I have a set of test cases, for which I need to demonstrate an analysis. Is there a plugin or any other way to analyse test results?

enter image description here

Tools to test website

Is there a tool, that could crawl through website and try submitting forms with any sample or random data and give details about found errors? Testomato.com seems to be something like that, but it doesn't seem to have function to crawl and fill forms automatically. Thanks

Use relative path when writing spec for atom package

I am writing tests for an Atom package and I have to open a text file (test.txt) which is at the same level of my package-spec.coffee file.

I used the following code to open my file:

atom.workspace.open('test.txt')
.then (content) ->
    text = content.buffer.getText()

However when I run the test with apm test the file is not opened because of relative paths. If I write the full path of the test.txt it works. How can I tell my script to use relative path, or how can I get the full path of my file. I cannot hardcode the full path because I want to run the tests with CircleCI, which has not the same paths as my local paths.

Slow starting Scalatest

I noticed that scalatest suddenly became lost slower to start the tests. I removed all the tests and only left one, simply testing true. Here is what I get (using sbt)

MacBook-Pro:simulator nicolas$ sbt
[info] Set current project to Simulator (in build file:/Users/nicolas/Private/simulator/)
> compile
[success] Total time: 1 s, completed 29-Oct-2016 14:30:04
> test
[info] MySpec:
[info] A pip
[info] - should pop
[info] Run completed in 312 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[success] Total time: 31 s, completed 29-Oct-2016 14:30:37

As you can see, the compile is instant (1s) and the tests themselve run in 312 milliseconds. What could be explaining that it actually need 31s to run them?

It was not like this to start with, they were running in a few seconds then suddenly jumped up to 30s (even with only 1 extremely quick test) Happens too after a fresh restart of the computer.

Here is my build.sbt just in case:

lazy val root = (project in file(".")).
  settings(
    name := "Simulator",
    version := "0.1",
    scalaVersion := "2.11.8"
  )

// scala JSON library
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.2"

// ScalaTest dependencies
libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.0"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test"

// QuickLens
libraryDependencies += "com.softwaremill.quicklens" %% "quicklens" % "1.4.8"

Thanks!

Reusing opened browser in Selenium 3

Is it possible to reuse browser? It's really time consuming when selenium is openning new browsers while I'm checking if my tests work.

I'm runinng remotewebdriver on Selenium standalone server. Before the update (without standalone server) I was able to reuse browser by checking if browser is open on specific port:

public void PortSetup()
    {
        DesiredCapabilities firefoxCapabilities = DesiredCapabilities.Firefox();
        try
        {
            var uri = new Uri("http://localhost:7055/hub");
            Driver = new RemoteWebDriver(uri, firefoxCapabilities);
        }
        catch (Exception)
        {
            Driver = new FirefoxDriver(firefoxCapabilities);  
    }

but now browser is opening on different port every time. It would be great if i could specify port, or maybe you have other idea? I have no clue what to do about this so I will appreciate any help.

PHPUnit How to constraint mock stub method input with array subset containing instanceOf?

I want to test pretty specific piece of code, but I can't find a good way to do it. I have such code:

public function foo()
{
    try {
        //...some code
        $this->service->connectUser();
    } catch (\OAuth2Exception $e) {
        $this->logger->error(
            $e->getMessage(),
            ['exception' => $e]
        );
    }
}

And I want to test if the exception was thrown and logged to $this->logger. But I can't find a good way to do it. Here is how I do it currently.

public function testFoo()
{
    $oauthException = new \OAuth2Exception('OAuth2Exception message');

    //This is a $service Mock created with $this->getMockBuilder() in test case injected to AuthManager.
    $this->service->method('connectUser')
        ->will($this->throwException($oauthException));

    //This is a $logger Mock created with $this->getMockBuilder() in test case injected to AuthManager.
    $this->logger->expects($this->once())
        ->method('error')
        ->with(
            $this->isType('string'),
            $this->logicalAnd(
                $this->arrayHasKey('exception'),
                $this->contains($oauthException)
            )
        );

    //AuthManager is the class beeing tested.
    $this->authManager->foo($this->token);
}

This will test if error method was called with certain parameters, but array key 'exception' and exception object can exist in different parts of the array. What I mean is that test will pass for such error method call:

        $this->logger->error(
            $e->getMessage(),
            [
                'exception' => 'someValue',
                'someKey' => $e
            ]
        );

I would like to make sure that error method will always receive such subset ['exception' => $e]. Something like this would be perfect:

     $this->logger->expects($this->once())
        ->method('error')
        ->with(
            $this->isType('string'),
            $this->arrayHasSubset(
                ['exception' => $oauthException)]
            )
        );

Is it possible to achieve with PHPUnit?

Sinon Spy not catching click event

I'm using Mocha and Sinon to test that a click event listener has been added to a button on initialization. The click event is triggered on the button in the test but the spy isn't seeing it.

I can also attach a click event listener inside the test - the spy will catch this but the event is fired twice.

So I'm guessing it's a reference problem - accessing the correct reference to main.myMethod - and spy on that.

Anyone have any idea what I need to do to get this working?

var main = (function() {

    function init() {
      $("#btnGo").on('click', myMethod);
    }

    function myMethod() {
      console.log("myMethod() was called");
      return true;
    }

    init();

    return {
      init: init,
      myMethod: myMethod
    }
  })();


  if (typeof module !== "undefined" && module.exports !== null) {
    module.exports = main;
  }

  /*Test*/

  var expect = require("chai").expect;
  var sinon = require('sinon');
  var jsdom = require("jsdom");
  global.document = jsdom.jsdom('<body></body>');
  global.window = document.defaultView;

  before(() => {
    $ = require("jquery");
    global.$ = $;
  });

  describe("Main.init()", function() {
    it("should attach a click event listener to the button.", function() { 

      $("body").html("<button id='btnGo'>Go</button>");

      var main = require("../src/main.js"), 
        spy = sinon.spy(main, "myMethod");

      $('#btnGo').trigger("click"); 

      sinon.assert.called(spy);  
    });
  });

Tool to optimize website (opensource)

Is there any opensource project to optimize/check website before launch.

I mean tests for source code, meta tags, headings, image/js/css sizes, 404 page, cache headers etc. like Nibbler has.

Looking for tool to check, that page is well done for search engines. Tool i can extend (contribute to) with new tests.

Backlinks counter, search engine positions, Social metrics are not so important.

C# SqlDataReader interface with HasRows, Read() and NextResult()

I am trying to find an interface which is implemented by SqlDataReader and which exposes HasRows, Read() and NextResult(). I need these property and methods because I need to read multiple resultSets returned by stored procedures (as mentioned here). Currently I am using System.Data.IDataReader which exposes Read() and NextResult() but not HasRows property.

I need an interface so that the coupling will be lose and for the sake of code testability.

Any help on such an interface? Or I'll need to write an abstraction layer of interface from scratch?

vendredi 28 octobre 2016

Matching Plug Connection Adapter in Protocol's For

I would like to create a mocked HTTP request for mix test of App.Controller.sign_up/2. How to match %Plug.Conn{adapter: {Plug.Adapters.Test.Conn ... in protocol's for?

Caller

defmodule App.Controller do
  use App.Web, :controller
  def sign_up(conn, params) do
    case App.AppHelper.verify(conn, params) do
      {:ok, _} ->
    ...
    end
...

Protocol and Implementations

defprotocol App.AppRequest do
  @fallback_to_any true
  def request(conn, params)
end

defimpl App.AppRequest, for: [Plug.Adapters.Cowboy.Conn, Any] do
  def request(conn, params) do
    #returns http request result
  end
end

defimpl App.AppRequest, for: [Plug.Adapters.Test.Conn, Any] do
  def request(conn, params) do
    #returns mocked result
  end
end

defmodule App.AppHelper do
  def verify(conn, params) do
    App.AppRequest.request conn, params
  end
end

How to test external url or links in a django website?

Hi I am building a blogging website in django 1.8 with python 3. In the blog users will write blogs and sometimes add external links. I want to crawl all the pages in this blog website and test every external link provided by the users is valid or not.

How can i do this? Should i use something like python scrapy?

Can someone tell me how to properly validate whether a character is a specific letter or not?

So i'm trying to write a test program that will tell me whether or not a sequence of numbers is a magic square. However, I'm i'm trying to figure out how to correctly validate the user input. In short, I want to prompt users for an integer and continue doing so until they enter the letter 'x'. If they accidentally enter a letter instead of x before they are done, I want the program to give them a brief error before allowing the continuation of their input until x is entered. Here's what I have right now:

 import java.util.*;
public class TestSquare
{
   public static void main(String [] args)
   {
      Square numbers = new Square();

      Scanner in = new Scanner(System.in);
      System.out.println("Enter an integer(x to exit): ");
      int i = in.nextInt();
      char c = (char)(i + '0');

      while(Character.isDigit(c))
      {
         numbers.add(i);
         System.out.println("Enter an integer(x to exit): ");
         i = in.nextInt();
         c = (char)(i + '0');
      }
      if( c == 'x')
      {
         numbers.isSquare();
         numbers.isUnique();
         numbers.isMagic();
      }
      else
      {
         System.out.println("***Invalid Data Entry. Please Try Again or enter x to exit.***");
         i = in.nextInt();
         c = (char)(i + '0');
      }
   }
}

This lets me input integers just fine continuously, but the moment I input a letter (including x) the program runs into an error and stops. Can someone tell me how to properly validate this please? Thank you!

Can I push a local HTML file to my phone and have it open in my default browser?

I've been using PushBullet to quickly send websites to my phone. There's a great Chrome extension and pages automatically open up on my phone.

I'd like to get this same functionality for local .html files. My images are already hosted on AWS. I just need to get the code on my phone so that I can preview it. Is there any way to do this?

How do i click this button in capybara (using 'ID' or 'Xpath' selector)

Please help me solve this problem with Capybara

I have a button like this in capybara:

<li id="main-menu-button" data-radium="true" style="flex: 0 0 auto; padding:   0px; box-sizing: border-box; color: rgb(158, 144, 212); display: flex; margin: 5px; border-radius: 5px; width: 50px; height: 50px; flex-flow: row nowrap; justify-content: center; position: relative; transition: background-color 100ms ease-out;"><img src="/assets/images/branding/reachify-r-logo-white.png" alt="Logo" data-radium="true" style="width: 50px; height: 50px; padding: 10px; box-sizing: border-box; border-radius: 4px; background-color: rgba(0, 0, 0, 0.2);"></li>

I tried with: click_button "main-menu-button" and find_button("main-menu-button").click

but it gives error: Unable to find button "chat" (Capybara::ElementNotFound) ./features/step_definitions/login.rb:18:in /^I click Chat button$/' features/login.feature:8:inAnd I click Chat button'

How to run Django tests using Twisted Trial?

I recently discovered Twisted Trial but I can't find a way to run Django tests with it. If I try to run trial djangoapp/tests.py I get an error because it is not making all the setup steps that manage.py test does.

Anyone uses Trial to run Django tests?

Android Appium : Test multiple conditions first before to declare that test is failed

Scenario : I have different types of ads coming . One can be clicked on a button and other can be clicked on the whole ad. I have to test when an ad comes , the first test by clicking on the button , if it doesn't work , click on the other type. In appium , in the first if condition if it doesn't find element it will fail the test. How can I test multiple conditions before it declares it failed.

I am unsure where to sart?

I am 13 years old and now a bit of HTML but want to get into coding software and maybe try algorithm so I am confused and any help where I should start , or which langue I should learn first and how.

Will be thankful for any help

Testing an Angular 2 component with async-populated child components

I am trying to write tests for a compound component, populated with an observable, but as this is one of the first Angular2 tests I am writing.

I have a component named ListContainerComponent which is populated using Observable list$ with children instances of ListItemComponent.

ListContainerComponent's template follows:

<list-item
    *ngFor="let listItem of (list$ | async)" [item]="listItem"></list-item>

Works great in the browser. The tests however break on that the [item] is allegedly not a known property of ListItemComponent which is not exactly true, as it does have @Input() item in it.

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { ListContainerComponent } from './list-container.component';
import { Store, StoreModule } from '@ngrx/store';

import * as fromRoot from '../../../reducers';
import { Observable } from 'rxjs';
import { reducer } from '../../../reducers/list.reducer';

describe('Component: ListContainer', () => {
    let storeStub;
    let component: ListContainerComponent;
    let fixture: ComponentFixture<ListContainerComponent>;
    let element: HTMLElement;

    beforeEach(() => {
        storeStub = {
            items: []
        };

        TestBed.configureTestingModule({
            declarations: [
                ListContainerComponent
            ],
            providers: [
                {provide: Store, useValue: storeStub}
            ],
            imports: [
                StoreModule.provideStore(reducer),
            ]
        })
        .compileComponents();

        fixture = TestBed.createComponent(ListContainerComponent);
        component = fixture.componentInstance;
        element = fixture.nativeElement;
    });

    it('should populate list', async(() => {
        component.list$ = Observable.of([
            {name: 'abc', value: 'content of abc'},
        ]};

        fixture.detectChanges();
        expect(element.querySelectorAll('h4').length).toBeGreaterThan(0);

    }));
});

Sorry I am not providing a working plunker, but I don't know yet how to create tests in plunker. I believe the mistaking I am making is an obvious one, probably showing my wrong approach, and easy to spot by those in the know.

Errors testing toString Java code

I am trying to write some test code for a "Book" class that gets and sets book information from other classes: ISBN (String), Title (String), Author (String), publishDate (SimpleDateFormat "MMM.dd.yyy"), Price (Double), and Summary content (Blob).When I try to run a toString test on all or part of the code (which I have changed the format and String that should be set countless times):

@Test
public void testToString() {
    Book testBook6 = new Book();
    Title testTitle6 = new Title("Title: Moby Dick, ");
    Author testAuthor6 = new Author("Author: Mark Twain, ");
    ISBN testISBN6 = new ISBN("ISBN: 000-00-000-0000-0");
    testBook6.setTitle(testTitle6);
    testBook6.setAuthor(testAuthor6);
    testBook6.setISBN(testISBN6);
    assertEquals("Title: Moby Dick, Author: Mark Twain, ISBN: 000-00-000-0000-0", testBook6.toString());        
}

I receive an error:

org.junit.ComparisonFailure: expected:<[Title: Moby Dick, Author: Mark Twain, ISBN: 000-00-000-0000-0]> but was:<[book.application.Book@48533e64]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at book.application.BookTest.testToString(BookTest.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

and when I try to run the code in my scrapbook:

Book testBook = new Book();
ISBN testISBN = new ISBN("ISBN: 000-00-000-0000-0");
Title testTitle = new Title("Title: Moby Dick, ");
Author testAuthor = new Author("Author: Mark Twain, ");
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("MMMM.dd.yyyy");
Price testPrice = new Price(2.25);
Blob testBlob = new Blob("Blah, Blah, Blah");

testBook.setISBN(testISBN);
testBook.setTitle(testTitle);
testBook.setAuthor(testAuthor);
testBook.setPrice(testPrice);
testBook.setBlob(testBlob);

System.out.println(testBook.toString());

to see what's going on, I can only get a return of "book.application.Book@1794d431", with numbers (such as 1794d431) that change randomly every time I run it. All tests pass for every class that "Book" gets and sets from, and no errors are marked. This is only my second Java project, so I am quite new to this; however, I seem to have hit a wall and could certainly use some help!

Thanks in advance!

What does the command: var a, foo = "foo"; mean? (Jasmin toBeTruthy)

i'm currently learning Jasmine. One of the examples in the intro (http://ift.tt/1vhJfTg), for Included Matchers,

show the following code:

it("The 'toBeTruthy' matcher is for boolean casting testing", function() {
    var a, foo = "foo"; 

    expect(foo).toBeTruthy();
    expect(a).not.toBeTruthy();
  });

What does

     var a, foo = "foo";   

mean?

Is it two definition of variables, a and foo and initializing them as a "foo" string?

a = false and foo = true? Because maybe they were predefined as:

var a = null;
var foo = "foo";

thanks

Jmeter -Understanding Differences between thread groups users and loop count

Ive been asked to carry out some testing to assess the response time under varying load on a api that is being developed in my current job. I’ve got a very basic knowledge of Jmeter so I’m looking at this as my chosen tool to use

Here’s quick Back ground info of what I’m tying to achieve: I want to test the API by simulating a number of unique Json calls each made by different users. Each unique Json call contains a unique user ID and item number.

lets say for example I want to test, 10 different users, all making calls for different Items to the API at once.

I’m a little confused with the terminology and difference between thread groups and users and loop count (which are found inside thread groups) and how best to use them. I couldnt find an answer on the Jmeter site or on here so have come up with what i think may be a possible approach....

From my understanding of how Jmeter works. In order for me to achieve my aim would require me to create 10 separate thread groups within the test plan, each of these having their unique Json body data configured.

For example : Thread group 1 containing request 1, Thread group 2 containing request 2, Thread group 3 containing request 3, Thread group 4 containing request 4, Thread group 5 containing request 5.... and so on. ( note, I would uncheck the option ‘run thread groups consecutively so that all requests get sent at once)

If the number of users and the loop count in each thread group is set to 1 then each call is made only once. Meaning a total of unique 10 calls would be made during a single test run?

I guess, what I’m kind of asking is in my scenario, does the term thread group actually represent unique users, and if so what does the number of threads(users) actually represent

I think ive got this right but it would be good if someone more experienced might be able to add some confirmation or advice to point me in the right direction if ive got this wrong.

Thanks in advance

Test if data will be stored into database

So I have class ExceptionAspect that ensure that all exceptions thrown are always MyExceptions. Application uses Spring.

The question is how to write tests answering:

Does registerMyException() method called in handleException() method for sure saves exceptions data into DB?

Probably You recommend mockito and junit - it would be wonderful if somebody can explain on example step by step what's going on in sample test(s).

If some more information are needed let me know. I'm sorry for not answer immediately - I have to gather thoughts before.

public abstract class ExceptionAspect {

    public void handleException(Throwable t) {
        if (t instanceof MyException) {
            MyException myException = (MyException) t;
            registerMyException(myException);
            throw myException;
        } else {
            MyException myException = new MyException(t);
            registerMyException(myException);
            throw myException;
        }
    }

    private void registerMyException(MyException ce){
        MyError myError = new MyError();
        myError.setCategory(ce.getCategory());
        myError.setType(ce.getType);
    }

   /**
    *  other methods
    */
}

Here's persistence class MyError

@Entity
@Table(name="MyError")

public class MyError implements java.io.Serializable{

private static final long serivalVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name="ID", unique=true, nullable=false, length=50)
    private String id;

    @Column(name="CATEGORY", nullable=true, length=50)
    private String errCategory;

    @Column(name="TYPE", nullable=true, length=50)
    private String errType;

/**
*   getter and setter here
*/
}

And test that meanwhile I wrote - limit of 90min between posts stimulates mind :) So now question is how to test it? What should be checked - any propositions?

public class myExceptionTest{
    @Mock
    ExceptionAspect exceptionAspect;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsMyException(){
        // just to check if it works :) so it works
        thrown.expect(MyException.class);
        Throwable testThrowable = new RuntimeException();
        throw new MyException(testThrowable);
    }

    @Test
    public void doesNotThrowsMyException(){
        // just to check if it fail :) and as I expected it failed
        thrown.expect(MyException.class);
        throw new ArithmeticException();
    }
}

Unusual behavior in testing: node.js/ Mocha

I recently jumped into nodeJS and started building a middleware applicaiton using Express & Wagnor

below is my package.JSON

{
"devDependencies": {
  "gulp": "3.8.11",
  "gulp-mocha": "2.0.1",
  "mocha": "2.2.4",
  "superagent": "1.2.0",
  "wagner-core": "0.1.0"
 },
  "dependencies": {
    "underscore": "1.5.2",
  "mongodb": "2.2.10",
  "express": "",
  "http-status": "0.1.8",
  "mongoose":""
 },
 "scripts": {
 "test": "mocha test.js"
 }
 }

i am stuck in a very peculiar situation and searched for similar incident reports but could not get any relevant. I am sure i am making a silly mistake and need assistance in identifying it.

Here is the scenario, i have a basic middle-ware setup with 6 endpoints, and i am testing using mocha.

I have a test.js file with 6 tests and problem is that when i run it it passes once and fails another time and then passes again without any intervention to env or code or tests. This makes me very concerned that weather my application will behave similarly in production or it is a tests related issue or a known mocha issue (couldn't find any).

Below is my test file

var URL_ROOT = 'http://localhost:3131';
var express = require('express');
var wagner = require('wagner-core');
var assert = require('assert');
var superagent = require('superagent');
var mongoose = require('mongoose');
//mongoose.set('debug', true);

var PRODUCT_ID = '0000000000000000000001';

describe('Store API', function(){
    var server; 
    var Product;
    var Catagory;
    var User;


    before(function() {
        var app = express();

        // Bootstrap sertver
        models = require('./models')(wagner);
        require('./dependencies')(wagner);
        app.use(require('./api')(wagner));
        wagner.invoke(require('./auth'), {app: app});
        server = app.listen(3131);

        //Make Catagory and Product model available in test
        Catagory = models.Catagory;
        Product = models.Product;
        User = models.User;


        app.use( function(req, res, next) {
          User.findOne({}, function(error, user) {
               console.log('Time:', Date.now());
               assert.ifError(error);
               req.user = user;
               next();
           });  //user.findone
       }); //app.use
    }); //before

    after(function(){
        //Shut the server
        server.close();
    }); //after

    beforeEach(function(done) {
        //Make sure Catagories are empty before each test
        Catagory.remove({}, function(error) {
            assert.ifError(error);
            Product.remove({}, function(error) {
                assert.ifError(error);
                User.remove({}, function(error) {
                    assert.ifError(error);
                    //Create Products, Catagories and Users
                    var catagories = [
                        { _id: 'Electronics'},
                        { _id: 'Phones', parent: 'Electronics'},
                        { _id: 'Laptop', parent: 'Electronics'},
                        { _id: 'Meat'}
                    ];

                    // create product data
                    var products = [
                        {
                            _id: '00000000000001',
                            name: 'LG G4',
                            catagory: { _id: 'Phones', ancestors: ['Electronics', 'Phones']},
                            price: {
                                amount: 300,
                                currency: 'USD'
                            }
                        },
                        {
                            _id: '00000000000002',
                            name: 'Asus Zenbook Prime',
                            catagory: { _id: 'Laptop', ancestors: ['Electronics', 'Laptop']},
                            price: {
                                amount: 2000,
                                currency: 'USD'
                            }
                        },
                        {
                            _id: '00000000000003',
                            name: 'MeatOne Goasht Wala',
                            catagory: {_id: 'Meat', ancestors: ['Meat']},
                            price: {
                                amount: 20,
                                currency: 'USD'
                            }
                        }
                    ];

                    var users = [{
                        profile: {
                            username: 'shoaibhb',
                            picture: 'http://ift.tt/2eiq59p'
                        },
                        data: {
                            oauth: 'invalid',
                            cart: []
                        }
                    }];

                    Catagory.create( catagories, function(error) {
                        assert.ifError(error)
                        Product.create(products, function(error) {
                            assert.ifError(error)
                              User.create(users, function(error) {
                                  assert.ifError(error);
                                  User.findOne({}, function(err, user) {

                                  });
                             });
                        });
                    });
                });
                done();
            });
        });
    });

    it('can load a Catagory by id', function(done) {
        // Create a single Catagory
        // Catagory.create({ _id: 'Electronics' }, function(error, doc) {
        //     assert.ifError(error);
            var url = URL_ROOT + '/catagory/id/Electronics';
            //Make and HTTP request to localhost:3131/catagory/id/Electronics
            superagent.get(url, function(error, res) {
                assert.ifError(error);
                var result;
                // and make sure we got { _id: 'Electronics'} back
                assert.doesNotThrow(function() {
                    result = JSON.parse(res.text);
                });
                assert.ok(result.catagory);
                assert.equal(result.catagory._id, 'Electronics');
                done();
            });
        //});// ends here
    });

    it('can load all Catagories that have a certain parent', function(done) {

        // Create 4 catagories was here earlier, moved to beforeEach()

        //Catagory.create(catagories, function(error, catagories) {
            var url = URL_ROOT + '/catagory/parent/Electronics';
            //make HTTP request to /catagory/parent/Electronics
            superagent.get(url, function(error, res) {
                assert.ifError(error);
                var result;
                assert.doesNotThrow(function() {
                    result = JSON.parse(res.text);
                });
                assert.equal(result.catagories.length, 2);
                // should be in assending order by _id
                assert.equal(result.catagories[0]._id, 'Laptop');
                assert.equal(result.catagories[1]._id, 'Phones');
                done();
            });
        //});// create cat ends here
    });

    it('can load a product by id', function(done) {
        //Create a single product


        var oneProduct = {
                name: 'LG G4',
                _id: PRODUCT_ID,
                catagory: { _id: 'Phones', ancestors: ['Electronics', 'Phones']},
                price: {
                    amount: 300,
                    currency: 'USD'
                }
            };

        Product.create(oneProduct, function(error, doc) {
          assert.ifError( error);
            var url = URL_ROOT + '/product/id/' + PRODUCT_ID;
            // Make HTTP request to 
            // localhost:3131/product/id/0000000000000000000001
            superagent.get(url, function(error, res) {
                assert.ifError(error);
                var result = {};
                //And make sure we got LG G4 back

                assert.doesNotThrow(function() {
                    result = JSON.parse(res.text);
                });

                assert.ok(result.product);
                assert.equal(result.product._id, PRODUCT_ID);
                assert.equal(result.product.name, 'LG G4');
                done();
            });     
        });
    });

    it('can load all products in a Catagory with sub-catagories', function(done) {

        // moved to beforeEach function 

                var url = URL_ROOT + '/product/catagory/Electronics';
                //Make HTTP Request to loca:3131
                superagent.get(url, function(error, res) {
                    assert.ifError(error);
                    var result;
                    assert.doesNotThrow(function() {
                        result = JSON.parse(res.text);                
                    });
                    assert.equal(result.product.length, 2);
                    // should be assending order by name
                    assert.equal(result.product[0].name, 'Asus Zenbook Prime');
                    assert.equal(result.product[1].name, 'LG G4');

                    //Sort by price , assending
                    var url = URL_ROOT + '/product/catagory/Electronics?price=1';
                    superagent.get(url, function(error, res) {
                        assert.ifError(error);
                        var result;
                        assert.doesNotThrow(function() {
                            result = JSON.parse(res.text);
                        });
                        assert.equal(result.product[0].name, 'LG G4');
                        assert.equal(result.product[1].name, 'Asus Zenbook Prime');
                    });
                    //console.log(error);
                    assert.ifError(error);
                    done();
            });
    });


    it('can load user cart', function(done) {
        var url = URL_ROOT + '/me/';
        User.findOne({}, function( error, user) {
            console.log("error %j",error);
            //assert.ifError(error);
            user.data.cart = [{ product: PRODUCT_ID, quantity: 1}];
            console.log(user.data.cart);
            user.save(function(error) {
                assert.ifError(error);
                superagent.get(url, function(error, res) {
                    assert.ifError(error);
                    assert.equal(res.status, 200);
                    var result;
                    assert.doesNotThrow(function() {
                        result = JSON.parse(res.text).user;
                    });
                    assert.equal(result.data.cart.length,1);
                    assert.equal(result.data.cart[0].product.name, 'Asus Zenbook Prime');
                    assert.equal(result.data.cart[0].quantity, 1);

                });
            });
        });
        done();
    });



    it('can save user cart', function(done) {
        var url = URL_ROOT + '/me/cart/';

        superagent.put(url).send({
             data: {
                 cart: [{ product: PRODUCT_ID, quantity: 1}]
             }
         }).end(function(error, res) {
             assert.ifError(error);
             assert.equal(res.status, status.OK);
             User.findOne({}, function(error, user) {
                 assert.ifError(error);
                 assert.equal(user.data.cart.length, 1);
                 assert.equal(user.data.cart[0].product, PRODUCT_ID);
                 assert.equal(user.data.cart[0], quantity, 1);
             });
         });
         done();
    });
    enter code here

});

When i run these tests, here is what happens: a) 6 Tests pass b) Some test fail c) there is a blank response

D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js

D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (81ms)
    √ can load all Catagories that have a certain parent
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    1) "before each" hook


  5 passing (752ms)
  1 failing

  1) Store API "before each" hook:
     Uncaught TypeError: Cannot read property 'data' of null
      at test-6passing.js:243:17
      at node_modules\mongoose\lib\query.js:1173:16
      at node_modules\mongoose\node_modules\kareem\index.js:109:16




D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (89ms)
    √ can load all Catagories that have a certain parent (38ms)
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    1) "before each" hook


  5 passing (922ms)
  1 failing

  1) Store API "before each" hook:
     Uncaught TypeError: Cannot read property 'data' of null
      at test-6passing.js:243:17
      at node_modules\mongoose\lib\query.js:1173:16
      at node_modules\mongoose\node_modules\kareem\index.js:109:16




D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (96ms)
    √ can load all Catagories that have a certain parent
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    √ can save user cart


  6 passing (852ms)


D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js

D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (80ms)
    √ can load all Catagories that have a certain parent
    √ can load a product by id
    1) can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    2) "before each" hook


  4 passing (862ms)
  2 failing

  1) Store API can load all products in a Catagory with sub-catagories:

      Uncaught AssertionError: 0 == 2
      + expected - actual

      -0
      +2

      at test-6passing.js:215:28
      at Request.callback (node_modules\superagent\lib\node\index.js:785:12)
      at IncomingMessage.<anonymous> (node_modules\superagent\lib\node\index.js:
990:12)
      at endReadableNT (_stream_readable.js:913:12)

  2) Store API "before each" hook:
     Uncaught TypeError: Cannot read property 'data' of null
      at test-6passing.js:243:17
      at node_modules\mongoose\lib\query.js:1173:16
      at node_modules\mongoose\node_modules\kareem\index.js:109:16




D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (86ms)
    √ can load all Catagories that have a certain parent (38ms)
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    1) "before each" hook


  5 passing (744ms)
  1 failing

  1) Store API "before each" hook:
     Uncaught TypeError: Cannot read property 'data' of null
      at test-6passing.js:243:17
      at node_modules\mongoose\lib\query.js:1173:16
      at node_modules\mongoose\node_modules\kareem\index.js:109:16




D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (97ms)
    √ can load all Catagories that have a certain parent (43ms)
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    √ can save user cart


  6 passing (785ms)


D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (83ms)
    √ can load all Catagories that have a certain parent
    √ can load a product by id (39ms)
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    1) "before each" hook


  5 passing (797ms)
  1 failing

  1) Store API "before each" hook:
     Uncaught TypeError: Cannot read property 'data' of null
      at test-6passing.js:243:17
      at node_modules\mongoose\lib\query.js:1173:16
      at node_modules\mongoose\node_modules\kareem\index.js:109:16




D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js

D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>mocha test-6passing.js


  Store API
express-session deprecated undefined resave option; provide resave option auth.j
s:57:39
express-session deprecated undefined saveUninitialized option; provide saveUnini
tialized option auth.js:57:39
    √ can load a Catagory by id (93ms)
    √ can load all Catagories that have a certain parent (38ms)
    √ can load a product by id
    √ can load all products in a Catagory with sub-catagories
    √ can load user cart
error null
    √ can save user cart


  6 passing (806ms)


D:\Programs_Insalled\nodejs\finalMEAN\edx\retailStore>

So the Question:

  1. Is there a mistake i am doing
  2. Is my approach incorrect
  3. Is there an issue in mocha that i don't know
  4. This is how it is

My environment is MongoDB, Node, Express, Windows

How can I test persistence class in Java?

How should I write test in Junit to test below class?

Will be grateful for sample code or description how to do it.

import javax.persistence.*;

@Entity
@Table(name="TechError")

public class TechError implements java.io.Serializable{
private static final long serivalVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name="ID", unique=true, nullable=false, length=50)
    private String id;

    @Column(name="CATEGORY", nullable=true, length=50)
    private String errCategory;

    @Column(name="TYPE", nullable=true, length=50)
    private String errType;


/**
*   getter and setter here
*/
}

DI for strategy class to make it testable

The name of thread is a little bit strange, but let me explain what problem I have. First of all let's say, that I have MVP architecture and I'm using injections. Also I have some service, which implements strategy pattern. Let's see how it looks like:

public class SettingsService<T> where T : Setting
{
    private ISettingsParser<T> settingsParser;

    public SettingsService(ISettingsParser<T> settingParser)
    {
        this.settingsParser = settingParser;
    }

    public void SaveSetting(T setting)
    {
        settingsParser.SaveSettings(setting);
    }

    public T GetSetting()
    {
        return settingsParser.GetSettings();
    }
}

To use this service you should pass as parameter new object, which is the concrete implementation of any parser, which actually knows how to parse file with concrete settings.

Here is example how we can create settings service to parse Player panel settings:

            var settingsService = new SettingsService<PlayerPanelSettings>(
            new PlayerPanelSettingsParser(fileWorker));

Don't pay attenetion on fileWorker, it's just a wrapper which allows you working with files and any type of parser gets it as parameter.

Now let's talk about presenters. For example we have presenter for Player panel settings which looks like:

public partial class PlayerPanelSettingsPresenter :
         BasePresenter<IPlayerPanelSettingsView, PlayerPanelSettings>
{
    private PlayerPanelSettings playerPanelSettings;

    private IMessageParser messageParser;

    private IFileWorker fileWorker;

    private SettingsService<PlayerPanelSettings> settingsService;

    public PlayerPanelSettingsPresenter(
            IApplicationController controller,
            IPlayerPanelSettingsView playerPanelSettingsView,
            IMessageParser messageParser,
            IFileWorker fileWorker) :
            base(controller, playerPanelSettingsView)
    {
        this.messageParser = messageParser;
        this.fileWorker = fileWorker;
        settingsService = new SettingsService<PlayerPanelSettings>(
            new PlayerPanelSettingsParser(fileWorker));
        SubscribePresenters();
    }

    private void SubscribePresenters()
    {
        View.ChangePlayerPanelSettings += ChangePlayerPanelSettings;
    }

    public void ChangePlayerPanelSettings(
                    PlayerPanelSettings newSettings)
    {
        if (View.ValidateForm())
        {
            SaveSettings(newSettings);
            playerPanelSettings.SetSettings(newSettings);
            View.Close();
        }
        else
        {
            ChallengeMessage message =
                messageParser.GetMessage(MessageType.FtpSettingsInvalid);
            View.ShowMessage(message);
        }
    }
    private void SetPlayerPanelSettings()
    {
        View.SetPlayerPanelSettings(playerPanelSettings);
    }
    private void SaveSettings(PlayerPanelSettings newSettings)
    {
        settingsService.SaveSetting(newSettings);
    }
}

It works pretty simple - we determines event handler for event which we will recieve from our View. Also in constructor of presenter we extend base with services, which our concrete presenter need. In this case it's MessageParser service, FileWorker service and concrete SettingsService (for player panel settings in this case). And as you can see we are using dependency inversion principle for Message parser and File worker. Now in our dependency resolver we should bind abstraction with concrete impelentation, like RegisterService<IMessageParser, MessageParser>().

And let's look how we can test ChangePlayerPanelSettings method in our presenter (I'm using NUnit and NSubstitute):

[TestFixture]
class PlayerPanelSettingsTest : TestCase
{
    private IApplicationController controller;
    private PlayerPanelSettingsPresenter presenter;
    private IPlayerPanelSettingsView view;
    private PlayerPanelSettings mock;
    private PlayerPanelSettings argument;
    private SettingsService<PlayerPanelSettings> settingService;
    private IMessageParser messageParser;

    [SetUp]
    public void SetUp()
    {
        controller = Substitute.For<IApplicationController>();
        view = Substitute.For<IPlayerPanelSettingsView>();
        messageParser = Substitute.For<IMessageParser>();
        IFileWorker fileWorker = Substitute.For<IFileWorker>();
        PlayerPanelSettingsParser parser =
            Substitute.For<PlayerPanelSettingsParser>(fileWorker);
        settingService =
            Substitute.For<SettingsService<PlayerPanelSettings>>(parser);
        presenter = new PlayerPanelSettingsPresenter(
            controller, view, messageParser, fileWorker);
        mock = Substitute.For<PlayerPanelSettings>();
        argument = InitializePlayerPanelSettings();
        presenter.Run(mock);
    }
    [Test]
    public void ChangePlayerPanelSettingsIfFormIsValid()
    {
        // Arrange
        SetFormAsValid(true);
        var returnedMessage = new ChallengeMessage()
        {
            MessageType = MessageType.PlayerPanelSettingsInvalid
        };
        // Act
        presenter.ChangePlayerPanelSettings(argument);
        // Assert
        settingService.DidNotReceive().SaveSetting(argument);
        mock.Received().SetSettings(argument);
        view.Received().Close();
        messageParser.DidNotReceiveWithAnyArgs().GetMessage(MessageType.PlayerPanelSettingsInvalid);
        view.DidNotReceiveWithAnyArgs().ShowMessage(returnedMessage);
    }


    [Test]
    public void ChangePlayerPanelSettingsIfFormIsInvalid()
    {
        // Arrange
        SetFormAsValid(false);
        var returnedMessage = new ChallengeMessage()
        {
            MessageType = MessageType.PlayerPanelSettingsInvalid
        };
        // Act
        presenter.ChangePlayerPanelSettings(argument);
        // Assert
        settingService.DidNotReceiveWithAnyArgs().SaveSetting(argument);
        mock.DidNotReceiveWithAnyArgs().SetSettings(argument);
        view.DidNotReceiveWithAnyArgs().Close();
        messageParser.Received().GetMessage(MessageType.PlayerPanelSettingsInvalid);
        view.Received().ShowMessage(returnedMessage);
    }

    private void SetFormAsValid(bool isValid)
    {
        view.ValidateForm().Returns(isValid);
    }
}

I'm just testing all the methods in my presenter on calls. But as you can note I have useless string in my tests which related with testing settingService. Because I didn't link this settingsService to my presenter. So, we can write anything to this settingsService (Recieved, DidNotRecieved) it will be passed. And what I'm thinking about is modify my constructor in presenter and pass there somehow interface of concrete SettingsService and link it with concrete SettingsService. But it won't work, because our SettingsService demands a parameter in constructor (concrete SettingParser) and our dependecy resolver doesn't know about it.

So, I want make testable my SettingService in presenter. And actually it's my question - how to do it in the best way? I know that theme is pretty large and maybe it's hard to catch what I'm talking about from the first time, but I hope you can help me. Please ask me if I should explain something and thanks for your time!

Enzyme: shallow render inner react-redux components

I have simple react component, that use Card from antd:

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

export class TBD extends Component {

  constructor() {
    super();
  }

  render() {
    return (
      <Card title={this.props.pathname}>
        TODO
      </Card>
    );
  }
}

export let select = (state) => {
  return state.route;
};

export default connect(select)(TBD);

Now I write some simple test and want to check, that my TBD component use

describe('Fully Connected:', function () {
    it('show selected item text', function () {

      const expectedState = {route: {pathname: 'Menu1'}};
      const store = createMockStore(expectedState);
      const ConnectedComponent = connect(select)(TBDConnected);
      const component = shallow(<ConnectedComponent store={store} />).shallow().shallow();
      console.log(component.debug());
      expect(component.equals(<Card/>)).is.equal(true);
    });
  });

And it fail, because 3 shallow return me

<Component title="Menu1">
TODO
</Component>

But I'm expect

<Card title="Menu1">
TODO
</Component>

After one more render I get pure html from rendering . I'm not understand why it render it to instead and how I can get result what I want.

Advice on creating an Ant 'Build.xml' file

  1. I want to create a new Ant build.xml file
  2. The file will need to execute the 'testng.xml' in turn it will execute all my tests/classes nested within the 'pizzas' package.

  3. Would anybody please be able to provide me with an ideal build.xml code structure, which will point to the correct directories listed within my current project structure(Image listed below).

  4. I have searched online but cant seem to get any build.xml file to work.

Many thanks for your help,

enter image description here

Web Service proxy for testing

I would like to find a tool to sniff the messages from a webservice, like tcpgateway but for windows10. Let me explain it better.

I have a server that has to consume a ws from a customer, I want to point my server into my localmachine runing a program and this program will redirect to the customer ws.

Thanks in advance.

Mocking a wrapper time function

I have a created a minor wrapper function for the php time() method in my class

class MyClass
{
    public function myFuncion($unixTimeStamp)
    {
        $pending = $this->isPending($unixTimeStamp)

        // data manipulation

        return $result
    }

    protected function isPending($unixTimeStamp)
    {
        if ($unixTimeStamp > $this->currentTime()) {
            return true;
        }

        return false;
    }

    public function currentTime()
    {
        return time();
    }
}

I want to test the public function myFunction() in this class but I am at a bit of a loss how I can mock the currentTime method without mocking the SUT itself (MyClass)

What is the correct way of doing this? I felt creating a time class with a single method (getCurrentTime) and injecting it into MyClass while correct, was excessive. Is this the best method regardless?

What other options do I have?

Functional test of form Symfony3 mocked session

I'm writing functional tests for my symfony3 application and I have a problem that when I'm trying to test sending forms, by crawling the submit button.

Method what I want to test:

$personalDataForm->handleRequest($request);
if ($personalDataForm->isValid()) {
  return $this->handlePersonalForm($personalDataForm, $request);
}

return $this->render('members/personal-form.html.twig', [
  'personalDataForm' => $personalDataForm->createView(),
]);

Functional test:

    $client = static::createClient();
    $client->getCookieJar()->set($this->cookie);
    $client->followRedirects();

    $container = $client->getContainer();
    $container->set('session', $this->session);

    $crawler = $client->request('GET', '/');

    $form = $crawler->selectButton('Save')->form();
    $client->submit($form);

Declaration of $this->session:

$this->session = new Session(new MockArraySessionStorage(), new AttributeBag(), new FlashBag())

The crawler is correctly sending a request, but I have an error Failed to start the session because headers have already been sent by "phar:///usr/local/bin/phpunit/phpunit/Util/Printer.php" at line 134.

When I'm looking at test result I see that my test didn't pass the $personalDataForm->isValid() condition.

I think the problem is that after submitting form, application is using Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage to store a session instead of mocked session. How can I pass mocked session when I'm submitting form?

Get Build Version with Mockito

My target is to mock Build.Version.SDK_INT with Mockito. Already tried:

final Build.VERSION buildVersion = Mockito.mock(Build.VERSION.class);
doReturn(buildVersion.getClass()).when(buildVersion).getClass();
doReturn(16).when(buildVersion.SDK_INT);

Problem is that: when requires method after mock, and .SDK_INT is not a method.

How to best test a socket API with cmocka?

I have implemented an abstraction layer on top of sockets and would like to properly test it with cmocka. I have functions like request_thingie_from_server() and serve_thingie_for_client() that include "object" serialization so it would be important to test all the layers of the implementation. An implementation for a single function in the API might also include several invocations of send(), recv() et al.

I've previously done this by setting up two threads, one for the server and one for the client, that can then each handle their own side and as the other end always knows what to expect the received data can be compared to some reference result. Using threads for this like that is however quite a heavy weight solution (IMO at least) and I was hoping I could replace this with a lighter single threaded one (and thought cmocka might be a good tool to use for achieving this).

What is the best way to implement tests for this kind of testing with cmocka? Do you wrap the send() and recv() functions or how would you approach this?

jeudi 27 octobre 2016

Testing: spyOn new Object in Class Constructor

I have a React component as such:

class Entity extends React.component{
  constructor(props{
  ...
  const foo = new Bar(...);
  }
  ...
}
module.exports = Entity;

I am now using Jasmine 2.5 to write tests for this module, and I am wondering how to test that the foo object is created.

Testing effects of software editing block devices

I'm writing a program that edits partitions of block devices (/dev/sda and such) on linux. I've got the programs to work fairly well, and I have unit tested my code using mocks (as worked through in a previous question of mine), and now I would like to test my code on actually devices.

The code copies a partition table from one drive to another, possibly shrinking the partition table if needed. Afterwards, it copies the files from one drive to another. So I want to test my drive using drives of various relative sizes. Finally it makes the new drive bootable, essentially cloning the device.Unfortunately, I don't have physical drives in the correct sizes to test this program within a reasonable time limit.

I have been testing using .img (created using dd) files and various tools to mount them, but apparently VirtualBox can't run these in a VM, so I can't really test if they boot. I also tried mounting .vdi files using qemu-nbd, but sgdisk and similar tools can edit partitions on those.

What can I use to make virtual disks of (practically) any size, which I can edit on my Linux system then boot from virtual box?

Note that I'm not trying to unit test. These aren't intended to be automatic tests, so it doesn't have to be something that the computer can easily do by itself.

how to select by text using selenium and c#

I need to select the value (hours) related to an specific date. For example in the html below I need to read the number 24:20 based on the number 6; this is the html:

<div class="day-ofmonth">
<div class="day-ofmonth">
<span class="day-num">6</span>
<span class="available-time">24:20</span>
</div>
<div class="day-ofmonth">
<span class="day-num">7</span>
<span class="available-time">133:50</span>
</div>
<div class="day-ofmonth">
<div class="day-ofmonth">

if I use:

IWebElement t_value = d.FindElement(By.XPath(".//*     [@id='calinfo']/div[9]/span[2]"));
var t_again2 = t_value.GetAttribute("textContent");

i will get 24:20; but i need to get the value 24:20(in this case) based on number 6 (6 refers to day of the month) and not the Xpath (everyday will be a different date). If anyone can point me in the right direction, Thanks

Is there a tool which can be used to simulate a daemon process to occupy a port?

For example, can I use run 'ssh' as a backend daemon which occupies a port? But the real purpose is a test for the connection.

There could be multiple reasons which block the connection, the firewall in the two sides or something between them.

How to do Mocking in Python Unit-testing for the Github API?

I am working on a personal project that uses the Github API. I currently have this function as a member of a class.

 def get_user_data(self):
    url = self.GITHUB_API_URL + self.user_name
    try:
        response = requests.get(url, verify=True)
        if response.status_code != 200:
            raise RuntimeError('Status: ', response.status_code, 'Problem with the request.')
    except RuntimeError as error:
        print(error)


    data = response.json()

    return data

I heard you can use the python library

from unittest.mock import patch

or MagicMock to create the mocks after reading this blog post.

Although this is all confusing to me coming after learning unittesting in Java with Mockito. If anyone can clarify for me how to create mocks within Python unittests in a way I can understand I would appreciate it.

While condition not working in R script but do in console

I have an incomprehensible problem in a R script. I got the following message after a while condition :

Error in while ((date_all[j]$year < (start_date$year + 10))) { : missing value where TRUE/FALSE needed

But the unbelievable thing is it's not working in my script, but if I copy paste exactly the same in the console window, it is working ! whithout any change, even the use of variable j in the condition (because it is previously defined so it has a value)

Here is my R script :

library(readxl)

data <- read_excel("C:/Users/alian/Desktop/EURIA/BE/Stoxx50_data.xlsm", sheet = 1,col_names = TRUE)
price_all = data$`Adj Close`    # adjusted closing value
N = length(price_all)

date_all=as.POSIXlt(data$Date[(1:N)])

j = 1
start_date=date_all[1]
date=.POSIXct(rep(NA,10))
price=rep(0,2520)

while ((date_all[j]$year < (start_date$year + 10) )) {
  date[j]=date_all[j]
  price[j]=price_all[j]
  j=j+1
}

It is working in the console and not in the script. And if I test the value of the condition in the console I do obtain TRUE or FALSE, depending on j value. And what I do in the while is neither the problem as I tested it, and nothing change if I replace it by a simple print to test also.

So, I don't see what's wrong, especially as it works in the console window.

So if you can help me, I would really appreciate ;)

Thanks in advance.

Rails4 - Testing - URLGenerationError: No route matches

I've read a lot of other questions here in SO but none could solve my issue (they all appeared to be parameters related). I hope someone can help me.

Executing my controller's test I get this message:

ActionController::UrlGenerationError: No route matches 
    {:action=>"/login", :controller=>"sessions"}
test/controllers/sessions_controller_test.rb:6:in `block in 
    <class:SessionsControllerTest>'

My rake routes looks like this:

Prefix Verb   URI Pattern       Controller#Action
login  GET    /login(.:format)  sessions#new
       POST   /login(.:format)  sessions#create
logout DELETE /logout(.:format) sessions#destroy

My test itself is this one:

test "should get new" do
    puts 'debug: ' + login_path
    get login_path
    assert_response :success
end

The puts debug line prints: debug: /login

When I go to localhost:3000/login in my web browser it loads the page correctly and debug info sais that it used:

controller: sessions
action: new

Any idea why the test is not being correctly redirected to the new action and instead is looking for an inexistent action /login? Thanks!

How to test methods of heavy data structures using Google Test?

Suppose we have the following class:

class Graph {
 public:

  Graph(int num_vertices, int num_edges, const EdgeList& edge_list)
    : num_vertices_(num_vertices), num_edges_(num_edges), edge_list_(edge_list) { }

  int GetNumberOfComponents() { ... }

 private:
  int num_vertices_;
  int num_edges_;
  EdgeList edge_list;
}

The goal is to check that GetNumberOfComponents() works correctly using Google Test framework.

Please provide below the code how we can test the method in case Graph contains 1000 vertices and 10000 edges for example.

Share testing data between rails application

In our company project, we have 2 Rails projects: A and B share the same database but different models. My boss doesn't allow me extract the models to a gem / rails engine for both projects because I'm new member and it takes many risks for our production. So I have to keep it as currently. I've researched a lot of things but still doesn't have solution at the moment. Let's me summarize:

Project A usually used to create and save data to database so that the models in A always up-to-date. Project B is used to load data so that project B doesn't have all the models as A and some models in B have lack associations. My mission is adding tests for project B. This is my solution:

First of all, I share one database test for both projects.

Secondly, in project A, I setup Factory Girl to create test data.

So the question is that from project B, how can I call or trigger project A to run the A's Factory Girl in order to create test data so that project B could load that data and verify it ?

Testing Internet of things protocols

I want to test several Internet of Things protocols like MQTT, DDS, COAP, AMQP and WebSockets on a communication between a client and a server. Once I developed the two entities and starting sending and receiving packets, can you suggest me tools to test and get informations about network usage, percentage of sent and lost packets, sent and received bytes, and so on?

How do I get detailed logging when I run a single test in Gradle?

I'm trying to find out why a single test is failing in my build, so I know I need to run gradle with the tests flag like so:

./gradlew test --tests com.myname.myproject.mypackage.MyTestClass.myTestMethod

However I wanted to see some trace logs so I had more detailed information on what my test was doing. I know that the options for seeing more detailed logs are --stacktrace, --info, and --debug. So normally, to see more detailed logging on all tests, I'd use the following:

`./gradlew test --debug` or `./gradlew test -d`

In this case, I'd like to only see debug logs for myTestMethod, but none of my attempts are working. I always get debug logs for ALL of the tests; it's running ALL of the tests instead of the single one I specify. I've tried the following combinations, all to no avail:

With --debug

Appended at the end: ./gradlew test --tests com.myname.myproject.mypackage.MyTestClass.myTestMethod --debug

Appended at the end with quotes around the tests param: ./gradlew test --tests "com.myname.myproject.mypackage.MyTestClass.myTestMethod" --debug

Appended before tests flag: ./gradlew test --debug --tests com.myname.myproject.mypackage.MyTestClass.myTestMethod

Appended before tests flag with tests param in quotes: ./gradlew test --debug --tests "com.myname.myproject.mypackage.MyTestClass.myTestMethod"

With -d

Appended at the end: ./gradlew test --tests com.myname.myproject.mypackage.MyTestClass.myTestMethod -d

Appended at the end with quotes around the tests param: ./gradlew test --tests "com.myname.myproject.mypackage.MyTestClass.myTestMethod" -d

Appended before tests flag: ./gradlew test -d --tests com.myname.myproject.mypackage.MyTestClass.myTestMethod

Appended before tests flag with tests param in quotes: ./gradlew test -d --tests "com.myname.myproject.mypackage.MyTestClass.myTestMethod"

Is there something I'm doing wrong?

Gradle version used in wrapper: 2.14.1

Note: I'm also setting up some environment variables before the command, specifically, spring boot profiles. I'm thinking that shouldn't affect anything as it's not part of the gradle command, but I figured I'd state so just in case. So in reality, all of the commands I'm running look more like this: SPRING_PROFILES_ACTIVE=profile1,profile2 ./gradlew test ...

Data-driven unit tests with google test

I am currently writing unit tests for an embedded application using googles unit test framework. Now my boss got upset that the data I test with (i.e. the values with which I call methods of the class under test) is hard wired in the tests. He requests to have this data read-in from a file. His argument is that it would thus be easier to add another test for a corner case that was previously forgotten. I am not that experienced with unit tests but so far that was not how I did it. So I tried to figure out what would be the best way to do it - even if it is a good idea to do it at all. I quickly came across the DDT (data-driven testing) approach.

The google unit test framework has a feature they call "Value-Parameterized Tests". With that my test fixture becomes a template class and I can pass in parameters. However, I see some problems with this:

  • I currently have a fixture per class under test. But I would need a fixture per method under test since each method requires a different set of parameters. This will be a lot of extra work.
  • As I see it I can pass in only a single parameter. Since I need several ones for my tests (all parameters for my method plus the expected results) This would require me to pass in something like a vector or map. Again this construction and retrieval sounds like a lot of work.

I would have imagined that something as mature as the google test framework to make it easier. However, they write

value-parameterized tests come handy [when] you want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it!

Additionally there exists this blogpost TotT: Data Driven Traps, also warning me of (abusing) data-driven unit tests.

So my question comes down to:

  • Is it a good idea to do data driven unit tests?
  • How to do data-driven unit tests with google test framework

I am not really bound to googletest and basically free to choose any framework I'd like, though.

Manual Testing QA report templates on Project Based

Could anyone please share an simple about Manual Testing report on project based for SQA Engineer.

Thanks.

debugging multiThreads in intellij: how can i see the all thrown exceptions?

I have a multithreaded code in java.

I debug with intellij. I know how to switch debug contexts between threads.

Nevertheless the console shows only exception thrown for the main thread.

How can i see the exceptions thrown from any thread?

enter image description here

enter image description here

Get "...kernel_require.rb:120:in `require': cannot load such file" error when I am trying to run my TC

I am trying to set my test env. up on c9.io cloud. I used project that successfully work on Windows. But on this .c9.io cloud (Linux operation system) I get "kernel_require.rb:120:in `require': cannot load such file" error when I am trying to run my TC.

My project is here: http://ift.tt/2eJefFV

HSQL default identity 0 conflicts with jpa entities with identity int id defaulted to 0

I have a JPA entity with:

@Id
@Column(name = "id", columnDefinition = "INT")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

and using EntityManager.merge by default

For testing I'm using HSQL that default its "auto increment" setting to 0

whenever I create a new object, my default int id will be set to 0, and the merge operation, instead of inserting the object as a new record, will update it instead.

any idea how to solve this?

One option I tried without success is to set the default "auto increment" of HSQL to 1 (not altering a specific column using RESTART)

thanks!

Fetching Reporting manager from a tbale

In interview,i got a below question Can we get the immediate reporting manager of an employee

EmpID Emp Name Role 1 Sunil Software Engineer 2 Alwin Lead 3 Pravin Manager 4 Saran Delivery Manager

Just only with the above table