mardi 28 février 2017

golang test exit status -1 and shows nothing

Recently I've been working on a Restful app in golang, strange things happened when I try to write tests in different subdirectories. My project structure is:

├── handlers/
│   ├── defs.go
│   ├── hello_test.go
│   ├── hello.go
├── server/
│   ├── codes.go
│   ├── middlewares_test.go
│   ├── middlewares.go
├── utility/
│   ├── auth.go
│   ├── auth_test.go

All files in handlers/ are declared "package handlers", all files in server/ are declared "package server", and so on. When I run go test in utility/ and handlers/ everything is fine. But if I run go test in server/, it returns me nothing but just:

[likejun@localhost server]$ go test
exit status 1
FAIL    server_golang/server    0.003s

It seems that it exits with a code 1 before even run, could someone tells me why this happened? Thank you, I've been spent the whole afternoon on it.

the code in middleware_test.go

package server

import (
    "io"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHello(t *testing.T) {
    req, err := http.NewRequest(http.MethodGet, "/", nil)
    if err != nil {
        t.Fatal(err)
    }

    rec := httptest.NewRecorder()

    func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        io.WriteString(w, `{"hello": "world"}`)
    }(rec, req)

    if status := rec.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %d want %d", status, http.StatusOK)
    }

    if rec.Header().Get("Content-Type") != "application/json" {
        t.Errorf("handler returned wrong content type header: got %s want %s", rec.Header().Get("Content-Type"), "application/json")
    }

    expected := `{"hello": "world"}`
    if rec.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %s want %s", rec.Body.String(), expected)
    }
}

Looks like I totally don't understand how python nose --match parameter works

By default --match parameter has value '(?:^|[b_./-])[Tt]est' which is fine (wait, no, I don't understand what that means). But if I want to run only test methods which start with a prefix '.*test_post_object_.*' (it is not a correct reg expression?), nose does not find anything and runs zero tests. Suppose I run nose in the same directory, where methods exist, and I know about -w parameter.

ps: And I could not find anything about nose testMatch, which is mentioned in the manual. This is so weird...

iOS UITests - What purpose XCUIElements identifier serves

While woking on iOS UITests, I found XCUIElement has a property, identifier, which was confronted from XCUIElementAttributes. When I debug, I found this is a real-only property and always contains empty string. Can anyone explain what purpose this property serves? I am unable to get any distinguishing property between two XCUIElement

I cannot change the identifier, its immutable.

enter image description here

How to use gmock to mock up a std::function?

The constructor of my class is

A( ...
   std::function<bool(const std::string&, const std::string&)> aCallBack, 
   ... );

I want to use EXPECT_CALL to test it. This callback is from another class B. I created a Mock like

class BMock : public B
{
    MOCK_METHOD2( aCallBack, bool(const std::string&, const std::string&) );
}

Then I tried

B *b = new B();
std::function<bool(const std::string&, const std::string&)> func = 
    std::bind(&B::aCallBack, b, std::PlaceHolders::_1, std::PlaceHolders::_2);

It still does not work. How can I get a function pointer of a gmock object?

Thanks!!

Spring testing plugin without context

I have a plugin for my application which has only one class:

@Configuration public class AppConfig {

@Bean
public Supplier messageSupplier(){
    return () -> "plugin";
}

}

I use it in other application but I want to test this class. I want to test it, but I don't know what is context of this application.

Var is not accessible outside background block on feature test

I'm having the following feature test

RSpec.feature 'Show post', :type => :feature do

  background do
    post = create(:post)
    user = create(:user)
    sign_in_with user # do login
  end

  scenario 'can view a single post' do
    visit root_path
    click_link(href: post_path(post))
    expect(page.current_path).to eq(post_path(1))
  end
end

If I run this test I get the following error

Show post can show idividual post
     Failure/Error: click_link(href: post_path(post))

     NameError:
       undefined local variable or method `post' for #<RSpec::

Which I think is caused because the post variable inside post_path is not accessible from the background, am I right ??

If I move the code from the background to the test scenario, ie

scenario 'can show idividual post' do
    post = create(:post)
    user = create(:user)

    sign_in_with user

    visit root_path

    click_link(href: post_path(post))
    expect(page.current_path).to eq(post_path(1))
  end

the test passes.

The problem I guess in this cases is if I want to add another scenario I have to repeat these steps again and again. How can I solve this and keep my code DRY?

What is a test script?

I was given an assignment:

Consider a list of single digit numbers. For example, [2,2,5]. Consider the successors of such lists. The successor of [2,2,5] is [2,2,6]. The successor of [2,3,9,9] is [2,4,0,0]. The successor of [9,9,9,9] is [1,0,0,0,0]. Write a Java program that takes such a list of numbers as input and returns its successor. You cannot express this list as a decimal number and compute its successor as the number may be so large that an overflow occurs. Make your program as short as possible. Submit code in JAVA along with compilation instructions and test scripts.

I have written the program and compiled and ran it successfully. The program does exactly what the assignment requires. However, I am not sure what the instructor mean by test scripts. Would someone please explain and provide an example to what it is? Thank you.

Note: If you decide to downvote the question, provide a reason so I can edit my question.

How to efficiently generate random tests in Haskell Test.QuickCheck

I'd like to generate some sample tests using Haskell Test.QuickCheck

The goal is to generate data of (Int, [Int]) with the following conditions where the tuple is (x, xs):

  1. x > 0
  2. x not in xs
  3. all xs >0

Scratching my head and stumbling through the manual http://ift.tt/2m4pjDK after some time I can produce random lists meeting these requirements:

import Test.QuickCheck
mygen = arbitrary::Gen (Int, [Int]))
sample (mygen `suchThat` ( \(x, xs)->( (x `notElem` xs) && (x > 0) && (all (>0) xs)&& (xs/=[]))))

Running the last line in the GHCI outputs something like:

(40,[19,35,27,29,45,1,17,28])
(20,[3,9,11,12,15,8])
(43,[76,102,106,71,24,2,29,101,59,48])
(99,[5,87,136,131,22,22,133])
(77,[11,14,55,47,78,15,14])
...

Questions:

  1. How can this be done more efficiently since - I'm guessing- the function mygen creates a large sample set then filters out based on the suchThat criteria

  2. How can I indicate the list xs should be of a certain size. For example if I add && length xs > 50 the program runs for a very long time.

  3. Guarantee that each element of xs is unique. I.e. avoid records like (99,[22,22])

Which capture / replay tools are highly adopted for commercial / production use?

There are a lot of capture / replay (record / replay or record / playback) tools for software testing. Some of them are free and some of them are not. My question is: Which capture / replay tools are highly adopted by companies? Name of them? Is capture / replay tool already prevalent in the commercial community?

Recommendations for junit xml reporting server

I'm looking for an open source solution that can aggregate junit xml files and provide a hosted report of results over time. That would help narrow down consistently failing tests over a week for example.

Any recommendations on solutions to look into?

How to assert if an element exists in angular?

I am writing a spec for a directive. As part of the testing, I need to assert if an element with a class exists inside my root directive component.

I have tried the following.

it('should have a loading div container', function() {
            var loadingDivContainer = element.find('.loading-div');
            expect(loadingDivContainer).to.exist;
        });

But this seems to pass in all the condition. I am using the following tech.

Angular 1.x, mocha, chai,

Multiple Maven Projects, Single JaCoCo Site?

I am working for a company that is using multiple Maven projects/modules to create what will eventually become one product. To help me explain, imagine a file structure similar to below:

- Parent Directory
     - Project_1
           - /src/
           - /target/
           - POM.xml
     - Project_2
           - /src/
           - /target/
           - POM.xml

Along the way we are using JUnit to unit test our code, and it is an important contractual requirement that we achieve above a certain percentage threshold of code coverage with our tests.

We are using JaCoCo to generate coverage reports in the form of a HTML website. JaCoCo itself is proving to be invaluable but one major problem we have is that this creates a single site under the /target/site/jacoco/ directory.

I have done some investigating myself and found that, unless I am mistaken, JaCoCo by default does not support the ability to converge multiple Maven projects into a single JaCoCo report.

So my question is, can anybody suggest an alternative solution - something that will allow us to converge multiple reports onto a single web server?

One option we have is to move all sites into individual folders on a web server and then have an index page linking them together, but it's "clumsy" at best. For example:

- Web Server
     - index.html
     - Project_1
           - (Generated report files)
     - Project_2
           - (Generated report files)

Any better suggestions would be greatly appreciated.

Testing Pagination of Facebook Graph API

I need to test that I can fetch subsequent pages of reviews from facebooks graph API.

The issue I have is that an account can only review a page once, and pagination doesn't kick in til there are over 100 reviews.

Do I really need to create 101 user accounts and have each one of them manually submit a review, just so I can be sure that when real companies use the software I'll be able to fetch the paginated results correctly?

Is there an alternative?

Jenkins stops at first failure if a Qt Test Executable is executed with XML OUTPUT

Hi I'm executing QT test results with Jenkins, If no FAILURES are there then xunit output shows the passed tests. but if I want to generate a graph with 100 or more test failures (compiled with Qt creator, within Qtests in it) the TEMPORARY generated XML file of Jenkins contains only the first failure.It stops immediately after the first failure!.

This is the Execute Shell command: ./test_data_store -o "$WORKSPACE/generatedJUnitFiles/QTestlib/TEST_data_store.xml",xml

This generates the XML file: TEST_data_store.xml",xunitxml, The XML file contains all info needed to generate the report, but

Process xUnit test result report with pattern: generatedJUnitFiles/QTestlib/TEST_*.xml

(and all options are unchecked)

the generated output comes from a temporary XML FILE like: TEST--1573352231.xml, contains only the first failure.

all other +100 failures are skipped.

Why ?

Thanks. Ahmet

Find keyword name (or keyword name stack) in Robot Framework

I've been struggling with the same problem as in this question: Robot Framework location and name of keyword - i need to find a keyword name stack.
Seems like the author has found the solution.
Unfortunately, I cannot apply it because in my version of Robot Framework (3.0.2) object _ExecutionContext has no field or property keywords, so in my case the line EXECUTION_CONTEXTS.current.keywords[-1].name
raises an exception. Thank you for any help!

using enzyme.mount().setProps with a react-redux Provider

I have a test which is setting props, to observe some changes in the component. The only complication is that I'm wrapping the rendered element in a <Provider> because there are some connected components further down the tree.

I'm rendering via

const el = () => <MyComponent prop1={ prop1 } />;
const wrapper = mount(<Provider store={store}>{ el() }</Provider>);

I'm then trying to observe some changes by using the following:

wrapper.setProps({ /* new props */ });
// expect()s etc.

The problem is that setProps() is not setting the props properly on the wrapped component. I assume that this is because <Provider> is not actually passing props through as it's not an HoC. Is there a better way to test this than just changing the locally scoped prop variables and re-rendering?

Is it possible to test static functions by easyMock

I want to check if it returns with same value by using EasyMock's andReturn method. Unfortunately, I come across with "java.lang.IllegalStateException: missing behavior definition for the preceding method call:" when I use EasyMock. I guess it is not possible to test by EasyMock when I try expect method. You will understand question better in the code.

Regards Alper

Menu menu = EasyMock.createMock(Menu.class)
menu.setName("name");
        EasyMock.expect(XmlParseUtility.createLinesToParse(menu).toString()).andReturn(angularLines.toString());

Error Message :

 java.lang.IllegalStateException: missing behavior definition for the preceding     method call:
   Menu.getName()
   Usage is: expect(a.foo()).andXXX()

iOS UITests - Detect if any XCUIElement have ever been tapped on current run

While working on iOS, UITest, how can i detect if specific XCUIElement has already been tapped or not?

For example,

let app = XCUIApplication()
let button1 = app.tabBars.buttons["Home"]
button1.tap()
let button2 = app.tabBars.buttons["Home"].tap()
button2.tap() // Here, I want to detect button2 as already tapped

0 and 1 - Switch Coverage in State Transition Testing?

This question is not programming related but related to one of test case design the technique. State Transition Diagram technique provides Test coverage by identifying test conditions via N-1 switch transitions. I am confused about how to calculate the 0-switch and 1-switch coverage.

Adding screenshot of an example. Can anyone please explain how this can be solved? Thank you in Advance.

Question in attached Image:

Diagram for this Question:

iOS UITests - How to distinguish two different XCUIElement?

While iOS UITesting, how can I distinguish between two different XCUIElement?

For example I have two different UIButton with same label string "Button". How to check they are different? Do XCUIElement provides ID or any distinct property?

iOS UITests - How to get XCUIElement list which exist in current view

I am required to get a list of XCUIElement which are exist in current view. For example,

let app = XCUIApplication()
let allElements = app.otherElements.allElementsBoundByIndex

returns the full list of xcuielements, but i want to get only the elements that are hittable and exists in current view.

Catch a thread's exception in the main thread in Python

Hi I'm new to Python and multithreaded programming. I have a script running through some test steps. Meanwhile this is running I want to create a thread that polls with an interval and reads if any processes have crashed during execution. I have a function which acquires this information. My problem is how I can throw an exception from that thread whenever I get a return value stating that a process has crashed. My current thread looks something like this:

class process_thread(threading.Thread):
  def __init__(self):
  threading.Thread.__init__(self)
  self.run_thread = True

  def run(self):
    while self.run_thread:
      if has_any_processes_crashed() == -1:
        self.run_thread = False
        raise MyStopException("A process has crashed")
      else:
        time.sleep(3)

The problem is however that the exception is only raised in that thread and not in the main thread. I want to throw the same exception there and exit the script. What I do with this thread is that I create an object before I start with all my test steps and set it as a Daemon thread by:

p_thread = process_thread()
p_thread.setDaemon(True)
p_thread.start()
  # Executing all test steps here

And then, when my test steps are done I want to kill this thread before shutting down my test simulation by:

p_thread.run_thread = False
p_thread.join()

I do not think that a Queue is possible in my scenario as I still need to execute my test steps in the main thread.

Any help is appreciated!

Android - testing Google Map info window click

I'm writing tests for my app and I'm stuck with testing GoogleMap. Clicking on Marker was easy using UiAutomator, but it seems that it's impossible to click on info window.

This is how I make test click on Marker:

UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject marker = device.findObject(new UiSelector().descriptionContains(MARKER_TITLE));

I've tried using Android Device Monitor and dumping view hierarchy but it seems like that view (info window) isn't there.

Here is how the screen that I'm trying to test looks like: http://ift.tt/2m6IzRt

Any idea on how to click on info window using Espresso or UiAutomator?

iOS UITests - How to find how many screen are in view stack?

I am working in an iOS app UITests. I have several questions. At any point of a test functions:

  1. How do I know how many screen are in view stack currently?
  2. How can I fire a back event which will go to back screen?
  3. How can I get a list of currently visible xcuielements?

For example,

let app = XCUIApplication()
app.tabBars.buttons["Home"].tap()
app.navigationBars["Home"].buttons["Test Screen"].tap()

After executing this peace of lines, suppose, I am in Test Screen I would like to query all tappable ui elements and after logging I want to fire a back event. How do I do that?

Is there a mobile speed test tool that can process bulk URLs?

I am conducting a mobile speed test benchmarketing survey on a 1000+ websites from multiple regions around the world. Does anyone know of a tool I can use to bulk process multiple URL requests and provide test results from points in North America, Latin America, Europe, India, and East Asia? Many thanks for your help.

Matching a text having line breaks with another String

I am trying to get text from a popup message and then compare it with another string to check whether or not both are same.

Pop-up Screen

enter image description here

Testing Code

var text = element(by.css('.modal.fade.AppLockPopup.in'));
//expect(text.getText()).toEqual("Warning" + "\n" + " You haven't saved your changes.Are "+ "\n" +" you sure you want to discard your changes? "+ "\n" +" Yes No");
expect(text.getText()).toEqual("Warning You haven't saved your changes.Are you sure you want to discard your changes? Yes No");

Current Output (Fails)

enter image description here

How do I compare these strings?

lundi 27 février 2017

Sinon stub instance method declared in mapDispatchToProps

New to testing and React Redux, so I may be conflating a few issues here. I will only present one example, but I have tried many different combinations of mount(), shallow(), instance(), stub, spy and more.

Given a component, where setFooData() updates redux state and Foo.props.data:

const mapDispatchToProps = (dispatch, props) => ({
    setFooData(fooId, data) {
        dispatch(Actions.setFooData(fooId, data));
    },
});

...

return (
        <div fooId={this.props.fooId}>
            <Foo {...fooProps}/>
        </div>
    );

I would like to write some tests around the conditions under which setFooData() is called, namely conditions in lifecycle methods like componentDidMount() and componentWillReceiveProps().

Because setFooData() involves server calls and more, and because these tests merely concern the view layer and how the component renders as a result of Foo.props.data being set eventually by setFooData(), setFooData() seems like a good candidate for stub.

Therefore, Enzyme's shallow(), rather than mount(), seems appropriate, correct? In any case, when I try to stub setFooData():

let wrapper = return shallow(<Foo {...props}/>);
let stub = sinon.stub(wrapper.instance(), 'setFooData');

I receive the error:

Attempted to wrap undefined property setFooData as function

Upon inspection, wrapper.instance() yields an object where setFooData() is indeed not defined, but according to other examples, I would think it should be.

Furthermore, setFooData() does exist on wrapper.instance().selector.props, and while let stub = sinon.stub(wrapper.instance().selector.props, 'setFooData'); avoids the error, when I inspect the object setFooData() =/= stub, and the function is not called as per the test.

When I use mount() instead,

let wrapper = mount(<Provider store={store}><Foo {...props}/></Provider>);

let componentDidMountSpy = sinon.spy(Foo.prototype, 'componentDidMount');
let componentWillReceivePropsSpy = sinon.spy(Foo.prototype, 'componentWillReceiveProps');

expect(componentDidMountSpy.called).to.be.true;         //passes
expect(componentWillReceivePropsSpy.called).to.be.true; //passes
expect(stub.called).to.be.true;                         //fails

I receive a different error that appears related to the body of setFooData(), so setFooData() is called but the function is not actually stubbed to prevent its real body from being executed.

Thanks for any help to clarify my understanding.

Objective C Code

I am new in this platform. I need some help. Already some third party developed the code long back. right now we are testing for that.. so when we are compiling the Xcode in IOS simulator. we are facing some issues. below I mention that.

<<< 2017-02-16 10:27:59.220 iQuestionSurveyApp[3460:907] Hello Console 1
2017-02-16 10:27:59.221 iQuestionSurveyApp[3460:907] foo bar foo bar
2017-02-16 10:27:59.222 iQuestionSurveyApp[3460:907] url http://ift.tt/2lixb0w ddfdf sdfsdfsdf sdf &email_id=xxxxx@gmail.com
2017-02-16 10:27:59.223 iQuestionSurveyApp[3460:907] Hello Console 5
2017-02-16 10:27:59.228 iQuestionSurveyApp[3460:907] error
2017-02-16 10:27:59.727 iQuestionSurveyApp[3460:907] URL Testing:
2017-02-16 10:27:59.727 iQuestionSurveyApp[3460:907] email:xxxx@gmail.com
2017-02-16 10:27:59.728 iQuestionSurveyApp[3460:907] email:{
}
2017-02-16 10:27:59.729 iQuestionSurveyApp[3460:907] URL request: <NSMutableURLRequest http://ift.tt/2mo8h4t;
2017-02-16 10:27:59.729 iQuestionSurveyApp[3460:907] URL queryssss: iquestion1://com.ilinkresearch.iQApp
2017-02-16 10:27:59.730 iQuestionSurveyApp[3460:907] URL scheme:iquestion1
2017-02-16 10:27:59.730 iQuestionSurveyApp[3460:907] URL query: (null)
2017-02-16 10:28:01.149 iQuestionSurveyApp[3460:1103] Error Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0x8da1720 {NSErrorFailingURLKey=http://ift.tt/2modNnS, NSErrorFailingURLStringKey=http://ift.tt/2liF4TL, Thursday, February 16, 2017 10:28 AM

Can I use rack-test for deployment tests?

I've built a simple api in Sinatra, with the purpose of setting up a deployment pipeline using Docker. I'm at a stage where I could easily switch Sinatra for something else and there's currently one reason why I might do so.

I once wrote an api using Express and it was trivial to reuse the tests to test a deployment:

# Testing the code
chai.request(app)
  .get('/')

# Testing a deployment
chai.request('http://localhost:8080')
  .get('/')

Examples from: http://ift.tt/2ls7cVe

Now I am wondering if I can accomplish the same with rack-test and Sinatra. Simply sending a URL, instead of the app, crashes. So is there an easy way to accomplish this? I suppose I could write a testing framework on top of rack-test, but I'm not sure it's worth it, even though I do prefer Ruby over Javascript and Sinatra over Express.

Node.js folder structure: unit tests and e2e tests

Currently, I have the following structure:

/src
/tests/e2e
/specs

Whereas the specs folder I use for unit tests, and the structure inside the specs is the same structure as inside src. (e.g. for /src/user/validator.js there is a /specs/user/validator.spec.js file).

However, it doesn't feel right to me to have two testing folders in the root dir, and I'm wondering if there is any convention in the community about this.

I did go through this thread: Folder structure for a Node.js project. The suggestion there is spec for BDD and tests for unit tests. However, I use BDD (with Jasmine or Mocha) for both: unit tests and e2e tests.

Receiving "ActionController::UrlGenerationError" when using named routes in test

In my config/routes.rb file, special routes for each user are set as follows:

resources :users do
  member do
    get :following, :followers, :teams
  end
end

The users controller contains and defines the respective following, followers and teams actions. The above resources should generate the following named routes:
following_user_path(), followers_user_path() and teams_user_path()

so that a request like get following_user_path(1) is equivalent to get /users/1/following

Since the users controller has a before filter associated to all of these actions that redirect to the login_url when the user is not logged in, I created tests like the test below:

test "should redirect followers when not logged in" do
  get followers_user_path(@user)
  assert_redirected_to login_url
end

However, when I run these tests, I receive the following error:

ERROR["test_should_redirect_followers_when_not_logged_in", UsersControllerTest, 1.2590469539973128]
 test_should_redirect_followers_when_not_logged_in#UsersControllerTest (1.26s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"/users/762146111/followers", :controller=>"users"}
            test/controllers/users_controller_test.rb:77:in `block in <class:UsersControllerTest>'

The test passes when I use instead the following code:

test "should redirect followers when not logged in" do
  get :followers, params: { id: @user }
  assert_redirected_to login_url
end

I previously upgraded my application from Rails 4.2.2 to Rails 5.0.0.1 and I thought of mentioning this change. I know no other reasons why my tests fail when I use the named routes. Not considering this issue, my application works as expected, but I would like my named routes be available also in tests.

Supertest not working with routes that call .render()

Supertest does not work with any route in my app that calls res.render(). The test just times out, it doesn't execute the end or expect callbacks.

Static routes and routes that just call res.send work as expected.

In the browser my app works perfectly for all routes.

I started listening to the res.render callback to make sure there wasn't a rendering error, and the callback is called just fine during tests with the correct rendered template.

What can be causing the test to timeout?

Here is an example route I set, which doesn't work.

 app.get("/test", (req, res) => res.render("dashboard"));

And here is my spec:

it("at least returns something", (done) => {
            request(app)
                .get("/test")
                .expect(200)
                .end(err =>
                  err
                    ? done.fail(err)
                    : done()
                );
        });

How to reduce MSTest execution time in .NET?

In work we have a test suite that takes about 4 hours to run. I have already cut this down to 2 hours using Phantom JS. However I would like to get this down further.

We are using MsTest with Visual Studio 2013. What is the best way to get test execution time further?

I would be interested in getting parallel execution working. Is the best way to do this to upgrade to VS 2015? I have also heard that you can make them run in parallel using a VS 2010 .testsettings file? Advice appreciated.

Integration tests, but how much?

A recent debate within my team made me wonder. The basic topic is that how much and what shall we cover with functional/integration tests (sure, they are not the same but the example is dummy where it doesn't matter).

Let's say you have a "controller" class something like:

public class SomeController {
    @Autowired Validator val;
    @Autowired DataAccess da;
    @Autowired SomeTransformer tr;
    @Autowired Calculator calc;

    public boolean doCheck(Input input) {
        if (val.validate(input)) {
             return false;
        }

        List<Stuff> stuffs = da.loadStuffs(input);
        if (stuffs.isEmpty()) {
             return false;
        }

        BusinessStuff businessStuff = tr.transform(stuffs);
        if (null == businessStuff) {
            return false;
        }

       return calc.check(businessStuff);
    }
}

We need a lot of unit testing for sure (e.g., if validation fails, or no data in DB, ...), that's out of question.

Our main issue and on what we cannot agree is that how much integration tests shall cover it :-)

I'm on the side that we shall aim for less integration tests (test pyramid). What I would cover from this is only a single happy-unhappy path where the execution returns from the last line, just to see if I put these stuff together it won't blow up.

The problem is that it is not that easy to tell why did the test result in false, and that makes some of the guys feeling uneasy about it (e.g., if we simply check only the return value, it is hidden that the test is green because someone changed the validation and it returns false). Sure, yeah, we can cover all cases but that would be a heavy overkill imho.

Does anyone has a good rule of thumb for this kind of issues? Or a recommendation? Reading? Talk? Blog post? Anything on the topic?

Thanks a lot in advance!

PS: Sry for the ugly example but it's quite hard to translate a specific code part to an example. Yeah, one can argue about throwing exceptions/using a different return type/etc. but our hand is more or less bound because of external dependencies.

Django client does not delete in test

Hi I am now using Django REST3.5.3. I can do CRUD perfectly fine with browsable API.

My problem is my test does not pass.

tests.py

import os

from django.test import Client

from apps.price_list_excel_files.models import PriceListExcelFile


def upload_excel(user: str, passwd: str) -> tuple:
    client = Client()
    client.login(username=user, password=passwd)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    with open(dir_path + '/mixed_case.xlsx', 'rb') as fp:
        response = client.post(
            '/api/price-list-excel-files/',
            {'file': fp},
            format='multipart'
        )
    return client, response


def test_mgmt_user_upload_excel(prepare_mgmt_users):
    client, response = upload_excel("John", "johnpassword")
    assert 201 == response.status_code
    assert 1 == PriceListExcelFile.objects.count()


# TODO: Fix this testcase
def test_mgmt_user_remove_excel(prepare_mgmt_users):
    client, response = upload_excel("John", "johnpassword")
    excel_id = response.data.get('id')
    url = '/api/price-list-excel-files/' + str(excel_id) + '/'
    res2 = client.delete(url, data={'format': 'json'})
    import pdb;
    pdb.set_trace()

    assert 0 == PriceListExcelFile.objects.count()

Here is my pdb console:

apps/price_list_excel_files/tests.py .
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /Users/el/Code/siam-sbrand/portal/apps/price_list_excel_files/tests.py(37)test_mgmt_user_remove_excel()
-> assert 0 == PriceListExcelFile.objects.count()
(Pdb) list
 32         url = '/api/price-list-excel-files/' + str(excel_id) + '/'
 33         res2 = client.delete(url, data={'format': 'json'})
 34         import pdb;
 35         pdb.set_trace()
 36
 37  ->     assert 0 == PriceListExcelFile.objects.count()
[EOF]
(Pdb) res2
*** KeyError: 'content-type'
(Pdb) url
'/api/price-list-excel-files/2/'
(Pdb) res3 = client.delete(url)
(Pdb) res3
<Response status_code=404, "application/json">

Am I miss something?

Karma tests undefined promise in redux

I'm writing some tests in Karma for react/redux and I can't seem to fix this bug. Every time a test is ran, it will run through the action, send the correct value to the reducer, but I always seem to get a response return of undefined. We console logged all the values up until updating the state, but once this line executes:

dispatch(duck.addLabRequest(newLab.toJS())).then(() => {

We get a .then of undefined. What could be the root cause of this?

Error

PhantomJS 2.1.1 (Mac OS X 0.0.0) creating a new lab sends the body of the form in the request FAILED
        undefined is not an object (evaluating 'promise.then')

Test

describe('creating a new lab', () => {
  let promise;
  beforeEach(() => {
    let mockAdapter = new MockAdapter(axios);
     mockAdapter.onPost(labsURL).reply(201, {
       lab: newLabWithID,
       message: "Lab created successfully"
     });
     dispatch(duck.addLabRequest(newLab.toJS())).then(() => {
       expect(1).to.equal(2);
     })
  })
})

Action

export function addLabRequest(lab) {
  console.log("lab is: ")
  console.log(JSON.stringify(lab));
  return (dispatch) => {
    axios.post(`${API_URL}/Labs`, lab, {
      headers: {'Content-Type': 'application/json'}
    })
      .then((resData) => {
        console.log("WE GOT HERE");
        console.log(JSON.stringify(resData))
        dispatch(addLab(resData))
      })
      .catch((err) => {
        console.log(err.response.data.message);
      });
  }
}

. . .

Reducer

 case ADD_LAB:

  console.log("ADDING LAB");
  console.log(JSON.stringify(action.payload));
  return state.update(
    'labs',
    (labs) => labs.push(Immutable.fromJS(action.payload))
  );

java linked list queue test

So here are some of the methods that i want to test:

public class LQueueTest {

LQueue q;

public void setup()
{
    q = new LQueue();
}


@Test
public void testIsEmpty() {
    assertTrue(q.isEmpty());


}

@Test
public void testIsEmptyFalse() {
    q.enqueue(5);
    assertTrue(!q.isEmpty());
}

@Test
public void testSize() {

// not sure how }

@Test
public void testEnqueue() {
    q.enqueue(5);
}

@Test(expected = QueueException.class)  
public void testEmptyDequeue() {  
    q.dequeue();
}

@Test
public void testDequeue() {
    q.dequeue();
}

public void testOneDequeue() {
    q.enqueue(5);
    q.dequeue();
    assertTrue(q.isEmpty());

} }

so i have try to implement a simple method to test and it never work , why is the code incorrect?

dimanche 26 février 2017

Form value not updating

I'm new in testing and till now have succedded in setting up Testing using the ng-cli. I am currently testing a simple login form. This is how far I've come up with

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  showError: boolean = false;
  verfiedUser: boolean = true;

  constructor(public fb: FormBuilder, private _router: Router, private _activatedRoute: ActivatedRoute, private auth: AuthService) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });

    this._activatedRoute.params.subscribe(params => this.verfiedUser = (params['verified'] === 'true'));
  }

  loginPassword (value): void {
    // this.auth.login(value.username, value.password).subscribe(response => console.log(response), err => console.log(err));
  }
}

login.spec.ts

import { async, ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';
import {
  ActivatedRoute, ActivatedRouteStub, click, newEvent, Router, RouterStub
} from '../testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AuthService } from '../auth.service';

import {
  HttpModule, Http, XHRBackend, Response, ResponseOptions
} from '@angular/http';

import { AppModule } from '../app.module';

function createEvent(eventType: any): Event {
  const evt: Event = document.createEvent('Event');
  evt.initEvent(eventType, true, true);
  return evt;
}

describe('LoginComponent (templateUrl)', () => {

  let comp:    LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;
  let loginForm: FormGroup;

  // async beforeEach
  beforeEach(async(() => {
    let activatedRoute = new ActivatedRouteStub();

    TestBed.configureTestingModule({
      imports: [AppModule]
    })
    .compileComponents();  // compile template and css
  }));

  // synchronous beforeEach
  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);

    comp = fixture.componentInstance; // BannerComponent test instance
    loginForm = comp.loginForm;
  });

  it('should have a login form which is clean and disabled', () => {
    const loginBtn: DebugElement = fixture.debugElement.query(By.css('.login-form button[type="submit"]'));

    console.log(comp, comp.loginForm, loginForm);
    fixture.detectChanges();

    console.log(comp, comp.loginForm, loginForm);

    expect(comp.loginForm.value).toEqual({
      username: '',
      password: ''
    }, 'does not match');

    expect(loginBtn.nativeElement.disabled).toBe(true);
  });

});

I'm currently stuck with these errors. 1. loginForm is undefined, though comp and comp.loginForm is defined. 2. Even after fixture.detectChanges() the form is not updating.

Any help, in the right direction will help.

Thanks,

QT test adapter ignore data in tests

I would like to use Qt test in Visual Studio using the VS QT Test Adapter Extension.

I have made a data-driven test. When I build the project and run the test from the command line it fails because of second data row (that is OK).

But when I run the test in VS Test Explorer it runs the test with the first row only and it marks the test as pass.

Do you know, how could I fix that?

Thanks.

iOS UITest - Navigate to all available screens

I am using iOS UITest for a Swift application. I use something like,

func testAllScreenNavigation() {

    let app = XCUIApplication()
    app.tabBars.buttons["Home"].tap()
    app.navigationBars["Home"].buttons["More"].tap()
    app.sheets.buttons["Cancel"].tap()
}

etc. to navigate some of the specific, tabs, buttons, etc. and switch to respective screens. But i want to navigate each and every screens of my Application (It can be BFS style navigation or DFS style navigation, no matter). Is there any way iOS provides so i can get all navigable elements and then explore deeper and deeper automatically for my App?

How to test Apache Airflow tasks that uses XCom

I'm trying to figure out a way to test a DAG where I have a couple of tasks communicating using XCom.

Since the console command only allow me to run tasks from a DAG, is there a way to test the communication without having to run the DAG via the UI?

Thanks

Yodlee Get Transactions REST Call Returns Empty Body

I am testing the getTransactions REST API (http://ift.tt/2l0TsVd).

I am getting back 200 status code but the body returned in the response is empty "{}" to be precise. I have 5 user test accounts and neither of these returns any transactions.

I have tried it with and without the '?container=bank' (or creditCard) but no data is comming back.

When I execute getAccounts I get back a couple of accounts for each test user.

Not sure what the problem is. Is it possible that the test accounts were set up without any transactions? Is that likely?

php testing on gitlab ci composer

I'm tryning to do some basic static analysis with my little php code. I want to use: phploc phpcpd phpcs

my project folder structure is as follows:

    .
    |-- ci
    |   `-- docker_install.sh
    |-- css
    |   `-- css.css
    |-- index.php
    |-- js
    |   |-- icons.json
    |   `-- script.js
    `-- process.php

I created shell script docker_install.sh with the following code:

# Install git (the php image doesn't have it) and other tools
apt-get update -yqq
apt-get install git phploc phpcpd phpmd php-pear -yqq

#install composer
curl -s http://ift.tt/SI3ujS | php
mv composer.phar /usr/local/bin/composer  

and my build file:

  image: php:7.0
  before_script:
    #insatll needed packeges
    - bash ci/docker_install.sh > /dev/null
  test:app:
    script:
      #Static analysis
      - phploc .
      #phpmd check coding style
      - phpmd . text naming
      #checking Coding Standards with PHP Code Sniffer
      - phpcpd .
      #Viewing Coding Standards Violations
      - phpcs --standard=PEAR --report=summaryy

The build file with the following error:

  ....
  $ phpcpd .

  Warning: require_once(Symfony/Component/ClassLoader/ClassLoader.php): failed to open stream: No such file or directory in /usr/share/php/SebastianBergmann/PHPCPD/autoload.php on line 2

  Fatal error: require_once(): Failed opening required 'Symfony/Component/ClassLoader/ClassLoader.php' (include_path='.:/usr/local/lib/php') in /usr/share/php/SebastianBergmann/PHPCPD/autoload.php on line 2
  ERROR: Build failed: exit code 1

My questions: How to enhance this, and how to make it works ?

Thanks !

Travis CI not using correct node.js version

I'm writing ES6 code, using class and const, but Travis CI is saying that my build is failing because it is running my test script with node.js version 0.10.48. Here is a link to the failed build: http://ift.tt/2lUxIcP.

How to write tests for active record scopes?

How can I write tests for active record scopes? for example

class Post < ActiveRecord::Base
  scope :recent, -> { order("posts.created_at DESC") }
  scope :published, -> { where("status = 1") }
end

I'm using Rspec for testing

RSpec.feature Post, :type => :model do
  let(:post) { build(:post) }

  describe 'test scopes' do
  end
end

Does Unit Tests still matter if Functional Tests is satisfied?

For a short summary:

  • Unit tests are the smaller ones that expects something to do it right in dev's view.
  • Functional tests are those that expects things are right in user's view

If Functional Tests are already satisfied, do we still need to do Unit Tests?

Most likely (let's use web development as context), this is common by using the browser to see if things are right by letting other users/people try the system/application.

Let us put out other tests like for edge cases.

How to overcome failures while doing UI Automatin for Knockout Web sites

I'm working on knockout based site using selenium web driver + c# to automate. my test methods fail because of elements not found / not able to click as the site is slow / or the binding/ rendering of html is slow after the ajax calls are finished.

below is sample code i used to know the ajax calls have finished and i can proceed to search elements.

public static void waitForAjax(IWebDriver driver, String action)
        {
            try
            {
                TimeSpan tp = TimeSpan.FromSeconds(1000);
                driver.Manage().Timeouts().SetScriptTimeout(tp);
                ((IJavaScriptExecutor)driver).ExecuteAsyncScript(
                "var callback = arguments[arguments.length - 1];" +
                "var xhr = new XMLHttpRequest();" +
                "xhr.open('GET', '/" + action + "', true);" +
                "xhr.onreadystatechange = function() {" +
                "  if (xhr.readyState == 4 && xhr.status == 200) {" +
                "    callback(xhr.responseText);" +
                "  }" +
                "};" +
                "xhr.send();");
            }
            catch
            {
            }
        }

Im calling the above method before going to find the elements

Test Method

try
            {
                IWebDriver _Driver;
                IWebElement ele;
                FirefoxDriverService _Service = FirefoxDriverService.CreateDefaultService(@"D:\CodePlex_C#\SeleniumTestWithHtml\SeleniumTestWithHtml\Drivers");
                _Driver = new FirefoxDriver(_Service);
                _Driver.Navigate().GoToUrl("HomepageURl");
                System.Threading.Thread.Sleep(2000);
                waitForAjax(_Driver,"Call1");
                waitForAjax(_Driver,"Call2");
                System.Threading.Thread.Sleep(2000);
                ele = _Driver.FindElement(By.LinkText("DASHBOARD"));
                ele.Click();
                //System.Threading.Thread.Sleep(2000);
        waitForAjax(_Driver,"Call1");
                waitForAjax(_Driver,"Call2");
                waitForAjax(_Driver,"Call3");
                waitForAjax(_Driver,"Call4");
                System.Threading.Thread.Sleep(2500);
                ele = _Driver.FindElement(By.Id("QuickSearchCnt"));
                ele.Click();
            }

But My Code Fails. I suspect the code to find the calls have finished to execute is not working properly.

I Need help in knowing is my approach right? and need help in fixing the issue.

Is there a way to stop JML runtime from catching its own Errors and Exceptions?

I'm trying to use JML and even though it seems somewhat obsolete (am I wrong?) it works decently. However, I want to run a series of tests from within a program of my own and to analyze the result, I want to catch the Errors and Exceptions sent by the JML Runtime Checker myself. It seems the JML Runtime catches the errors itself and prints information to the screen and then allows execution to go on. For example:

>java -cp .;openjml.jar L2
[1, 2, 5, 8, 10, 13, 15, 18, 21, 22, 28, 30]
1
[1, 3, 4, 6, 3, 2, 4, 5, 6, 9, 787, 6, 4, 3, 2, 3, 45, 4, 3, 2, 3, 4, 5, 54, 0]
MergeSort.java:15: JML postcondition is false
    private static void mergeSort(int[] arr, int offset, int length, int[] buf) {

... (more JML Runtime output along with actual program output)

Anyone knows how to achieve my desired behaviour? I have attempted to put tryand catchblocks outside method calls but it seems like every JML checked method is in some sort of wrapper that catches errors and exceptions before if reaches any try and catchblock in the caller.

I compile with:

java -jar opemjml.jar -rac <FILES>

And I run it with:

java -cp .;openjml.jar <FILE>

samedi 25 février 2017

Uncaught Exception at appium run (appium-14.1.16)

I am runninh appium 14.1.16 at Ubuntu. After Starting appium server using

appium &

I am getting following uncaught Exception:

error: uncaughtException: Cannot find module 'internal/fs' date=Sun Feb 26 2017 13:08:48 GMT+0600 (BDT), pid=18190, uid=1000, gid=1000, cwd=/home/pc/.linuxbrew/lib/node_modules/appium, execPath=/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, version=v7.5.0, argv=[/home/pc/.linuxbrew/Cellar/node/7.5.0/bin/node, /home/pc/.linuxbrew/bin/appium], rss=99041280, heapTotal=79945728, heapUsed=46807408, external=204307, loadavg=[0.67529296875, 0.73681640625, 0.74658203125], uptime=3424, trace=[column=15, file=module.js, function=Function.Module._resolveFilename, line=470, method=Module._resolveFilename, native=false, column=25, file=module.js, function=Function.Module._load, line=418, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=20, file=evalmachine., function=null, line=18, method=null, native=false, column=1, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js, function=, line=11, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=27, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js, function=, line=3, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=10, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js, function=, line=4, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false, column=3, file=module.js, function=Function.Module._load, line=439, method=Module._load, native=false, column=17, file=module.js, function=Module.require, line=498, method=require, native=false, column=19, file=internal/module.js, function=require, line=20, method=null, native=false, column=18, file=/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js, function=, line=2, method=null, native=false, column=32, file=module.js, function=Module._compile, line=571, method=_compile, native=false, column=10, file=module.js, function=Object.Module._extensions..js, line=580, method=Module._extensions..js, native=false, column=32, file=module.js, function=Module.load, line=488, method=load, native=false, column=12, file=module.js, function=tryModuleLoad, line=447, method=null, native=false], stack=[Error: Cannot find module 'internal/fs', at Function.Module._resolveFilename (module.js:470:15), at Function.Module._load (module.js:418:25), at Module.require (module.js:498:17), at require (internal/module.js:20:19), at evalmachine.:18:20, at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/fs.js:11:1), at Module._compile (module.js:571:32), at Object.Module._extensions..js (module.js:580:10), at Module.load (module.js:488:32), at tryModuleLoad (module.js:447:12), at Function.Module._load (module.js:439:3), at Module.require (module.js:498:17), at require (internal/module.js:20:19), at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js:3:27), at Module._compile (module.js:571:32), at Object.Module._extensions..js (module.js:580:10), at Module.load (module.js:488:32), at tryModuleLoad (module.js:447:12), at Function.Module._load (module.js:439:3), at Module.require (module.js:498:17), at require (internal/module.js:20:19), at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/lib/reader.js:4:10), at Module._compile (module.js:571:32), at Object.Module._extensions..js (module.js:580:10), at Module.load (module.js:488:32), at tryModuleLoad (module.js:447:12), at Function.Module._load (module.js:439:3), at Module.require (module.js:498:17), at require (internal/module.js:20:19), at Object. (/home/pc/.linuxbrew/lib/node_modules/appium/node_modules/md5calculator/node_modules/unzip/node_modules/fstream/fstream.js:2:18), at Module._compile (module.js:571:32), at Object.Module._extensions..js (module.js:580:10), at Module.load (module.js:488:32), at tryModuleLoad (module.js:447:12)]

how to use Test Users for Functional Testing

For Testers.. For Testers.. For Testers..

When you do testing for applications "Web Applications", How can you define the test Users just for testing purpose and NOT Real Active users so that will enable you to login to the system and do all kinds of testing e.g. Functional Testing ? specially when you have many different Users Category (e.g. Normal Users, Super Users, super admin ...etc. ) for one system and you to go through all these categories to make sure the test Passes all Cases ?

This is really matters for me, so i would be grateful if you share it with your colleagues to help me out with this.

Thank you all.

Software testing, Manual testing

Hi i have been asked to write some test plan for lunchvox by an inteeviewer. I did write some not many tho. So help me in this.

What are some test plans/scenarios for Lunchbox?

Mocking logout throws an error

Hi i have the below to methods one for logging out and the other is internally called to clear cookies. I first started with mocking the second method to delete cookie. I am getting an exception and I am not sure how to mock the first method. I referred this code from DZone.

public class Service
{
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public String logout(HttpServletRequest request,HttpServletResponse response) {
        HttpSession session = request.getSession(true);
    session.setAttribute("sessionid","id");
    Cookie first=new Cookie("name","Mycookie");
    response.addCookie(first);
        if (request.isRequestedSessionIdValid() && session != null) {
        session.invalidate();
        }
        HttpServletResponse sessionRes=handle(request,response);
    return sessionRes;
        }


    public HttpServletResponse handle(HttpServletRequest request, HttpServletResponse response)
    {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null || cookies.length!=0)
        {
            for(Cookie cookie:cookies)
            {
                cookie.setMaxAge(0);
                cookie.setValue(null);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            response.addHeader("message", "No cookies found");
        }
        return response;
    }
}

Here is my test case for handle method. It returns me Null Pointer exception. I don't know where i went wrong. And please do help me writing mockito test case for logout function also.

@RunWith(MockitoJUnitRunner.class)
public class LogoutTest {
    @InjectMocks
    Service service;

    @Mock
    Cookie cookie;
    @Mock
    HttpServletRequest request;
    @Mock
    HttpServletResponse response;

    @Test
    public void TestHandle()
    {
        cookie=new Cookie("fname","ram");
        response.addCookie(cookie);
        when(service.handle(request,response)).thenReturn(response);
        assertEquals("No cookies found",response);
    }

}

Rspec integration signing in with Devise LDAP

So I'm trying to create integration tests for my rails 4.0 application, and I'm unsure how to authorize users (the application uses devise_ldap_authenticatable.

Initally, I attempted:

  setup do
    sign_in User.find_by_login('john.smith')
  end

  teardown do
    sign_out
  end


  test "can see index page" do
    get "/"
    assert_select "table[id=?]", "main_table"
  end

Which I can do inside normal rails code. However, this doesn't work. I then found this question, which provided answers for both controller and integration testing.

However, the problem is that the integration testing example:

post_via_redirect Rails.application.routes.url_helpers.user_session_path, 'user[email]' => user.email, 'user[password]' => user.password

Is for basic Devise, and doesn't take into account the use of an LDAP server (which therefore means I do not store passwords).

Does anyone know how to do integration tests when an LDAP server is involved, and login are required?

Can you install multiple Visual Studio 2015 Test Agents on a single computer?

I think I know the answer to this question but I haven't found anything particularly definitive.

TFS 2015

I have many very simple tests that need to be run in a distributed fashion. However from my understanding, I can either go parallel at the assembly level (which is ridiculous) or I can set multiple test agents in the runsettings file and distribute tests that way. I'd prefer not to have to spin up 10 tiny VMs but rather a one or two respectable sized VMs instead with multiple instances of the VSTA.

Thanks for any responses.

Can't start Appium on Windows 10

A few days ago I've faced an unexpected problem with starting an Appium application. Every time when I undertake another attempt to launch Appium here what's happens:

1) I click Appium.exe 2) Appium seems to try to start but fails at once 3) I open Event Viewer -> Windows Logs -> Application 4) And every time I try to start the Appium I see three records there:

  1. Event 1026, .Net Runtime:

    Application: Appium.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.IO.DirectoryNotFoundException at System.IO.__Error.WinIOError(Int32, System.String) at System.IO.FileStream.Init(System.String, System.IO.FileMode, System.IO.FileAccess, Int32, Boolean, System.IO.FileShare, Int32, System.IO.FileOptions, SECURITY_ATTRIBUTES, System.String, Boolean, Boolean, Boolean) at System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) at System.IO.File.Open(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) at MS.Internal.AppModel.ContentFilePart.CriticalOpenFile(System.String) at MS.Internal.AppModel.ContentFilePart.GetStreamCore(System.IO.FileMode, System.IO.FileAccess) at System.IO.Packaging.PackagePart.GetStream(System.IO.FileMode, System.IO.FileAccess) at System.IO.Packaging.PackWebResponse+CachedResponse.GetResponseStream() at System.IO.Packaging.PackWebResponse.GetResponseStream() at System.IO.Packaging.PackWebResponse.get_ContentType() at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCacheOption, System.Guid ByRef, Boolean ByRef, System.IO.Stream ByRef, System.IO.UnmanagedMemoryStream ByRef, Microsoft.Win32.SafeHandles.SafeFileHandle ByRef) at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy, Boolean) at System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy) at System.Windows.Media.ImageSourceConverter.ConvertFrom(System.ComponentModel.ITypeDescriptorContext, System.Globalization.CultureInfo, System.Object) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateObjectWithTypeConverter(MS.Internal.Xaml.ServiceProviderContext, System.Xaml.Schema.XamlValueConverter1<System.ComponentModel.TypeConverter>, System.Object) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateFromValue(MS.Internal.Xaml.ServiceProviderContext, System.Xaml.Schema.XamlValueConverter1, System.Object, System.Xaml.XamlMember) at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateFromValue(MS.Internal.Xaml.ServiceProviderContext, System.Xaml.Schema.XamlValueConverter1<System.ComponentModel.TypeConverter>, System.Object, System.Xaml.XamlMember) at System.Xaml.XamlObjectWriter.Logic_CreateFromValue(MS.Internal.Xaml.Context.ObjectWriterContext, System.Xaml.Schema.XamlValueConverter1, System.Object, System.Xaml.XamlMember, System.String, MS.Internal.Xaml.Runtime.IAddLineInfo)

    Exception Info: System.Windows.Markup.XamlParseException at System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader, System.Xaml.IXamlObjectWriterFactory, Boolean, System.Object, System.Xaml.XamlObjectWriterSettings, System.Uri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader, Boolean, System.Object, System.Xaml.Permissions.XamlAccessLevel, System.Uri) at System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream, System.Windows.Markup.ParserContext, System.Object, Boolean) at System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream, System.Windows.Markup.ParserContext) at System.Windows.Application.LoadComponent(System.Uri, Boolean) at System.Windows.Application.DoStartup() at System.Windows.Application.<.ctor>b__1_0(System.Object) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(System.Object) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext, System.Threading.ContextCallback, System.Object) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef) at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr) at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef) at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame) at System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame) at System.Windows.Application.RunDispatcher(System.Object) at System.Windows.Application.RunInternal(System.Windows.Window) at System.Windows.Application.Run(System.Windows.Window) at Appium.App.Main()

  2. Event 1000, Application Erorr:

    Faulting application name: Appium.exe, version: 1.4.16.1, time stamp: 0x5667540e Faulting module name: KERNELBASE.dll, version: 10.0.14393.0, time stamp: 0x57898e34 Exception code: 0xe0434352 Fault offset: 0x000d96c2 Faulting process id: 0x1040 Faulting application start time: 0x01d28f9dc7f56e90 Faulting application path: D:\1\Appium\Appium.exe Faulting module path: C:\Windows\System32\KERNELBASE.dll Report Id: 0d66a3f7-88fa-45f5-82c8-23b6b797df48 Faulting package full name: Faulting package-relative application ID:

  3. Event 1001, Windows Error Reporting:

    Fault bucket 129262020772, type 5 Event Name: CLR20r3 Response: Not available Cab Id: 0

    Problem signature: P1: Appium.exe P2: 1.4.16.1 P3: 5667540e P4: mscorlib P5: 4.6.1586.0 P6: 575a1299 P7: 1587 P8: fc P9: System.Windows.Markup.XamlParse P10:

    Attached files: \?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERF59D.tmp.WERInternalMetadata.xml

    These files may be available here: C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_Appium.exe_d2a2db888c1e7a113a12c96858f9a8b6e15d1db3_b269dae2_02c0fb0b

    Analysis symbol: Rechecking for solution: 0 Report Id: 0d66a3f7-88fa-45f5-82c8-23b6b797df48 Report Status: 0 Hashed bucket: 94ef3dfcff82d06558f4fa83bdd65152

What I've tried:

  1. I installed a few different versions of Appium. Tried not installed but just copy already installed application from another PC.

  2. I reinstalled Windows

  3. I uninstalled all of the Windows' updates I was able to

  4. I tried to un/enable a various Windows features (Programs and Features -> Turn Windows features on or off). But mostly intuitively =)

The result is allways the same. So, help me, please)

How do you use foldl to find out the number of times a letter is repeated in a string?

I'm new to Erlang and am testing different functions around to get a grasp of them. I want this function to be able to return an integer that says the number of times a letter variable is repeated in a string using the foldl function but am kinda stuck with deciding the "fun" function. Any help?

Examples of what I want the function to return:

`test:count("Hello this is a test", $i)`

should return 2

test:count("Hello this is a test", $t)

should return 3

-spec count(String, Char) -> integer() when
  String::string(),
  Char::char().

count(String, Char) ->

F = ???,

lists:foldl(F, 0, String).

Tool for reproduce FIddler or http requests

For my transactions I save the requests using fiddler, for example for a purchase I have 10 requests.

Is there any way to reproduce the 10 requests using any other tool that automatwically takes care of cookies carrying them between transactions? I tried httprequests library in c# but every request is a different and I need to carry and get the cookies from them manually

Regards

Testing dates in JS

date.js

class DateHelper {
  constructor() {
    this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  }

  postedOn(from) {
    const date = new Date(from);
    const day = date.getDate();
    const month = this.months[date.getMonth()];
    const year = date.getFullYear();
    if (year === new Date().getFullYear()) {
      return `${day} ${month}`;
    }
    return `${day} ${month} ${year}`;
  }
}

date_spec.js

describe('', () => {
  it('', () => {
    const from = 'Wed Feb 25 2015 00:38:24 GMT+0200 (EET)';
    expect(newDateHelper.postedOn(from)).to.equal('25 Feb 2015');
  });
  it('', () => {
    const from = 'Wed Feb 25 2017 00:38:24 GMT+0200 (EET)';
    expect(newDateHelper.postedOn(from)).to.equal('25 Feb');
  });
});

All tests are currently passing, but because postedOn compares to the current year I will need to update those tests each year. How can I fix this?

How do I test server application?

I have a server that consists of only one object (Server), and it only has constructors as public method. How exactly should I cover its functionality with tests?

React Native Jest Enzyme Find and Press Component

i'm trying to be adventurous and im trying to get 100% code coverage on my personal project. and i cant the documentation that explains how to simulate a click event using jest, enzyme and react-native.

<Screen.TopBar>
    <Toolbar
        leftElement="arrow-back"
        onLeftElementPress={() => router.pop()}
        centerElement={pageName}
    />
</Screen.TopBar>

this is just the top part of it, but im trying to simulate a click on that element.

const wrapper = mount(
    <MockProvider store={store}>
        <ThemeProvider uiTheme={uiTheme}>
            <Category />
        </ThemeProvider>
    </MockProvider>
);
expect(wrapper.find('Toolbar').length).toBe(1);

i get an error:

ReferenceError: document is not defined

  at Object.renderIntoDocument (node_modules/react-dom/lib/ReactTestUtils.js:73:15)
  at renderWithOptions (node_modules/enzyme/build/react-compat.js:187:26)
  at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:94:59)
  at mount (node_modules/enzyme/build/mount.js:19:10)
  at Object.<anonymous> (app/screens/category/tests/Category.test.js:32:30)

so my question is how do i select the toolbar so that i can click on the button in the Toolbar component.

vendredi 24 février 2017

How do I setup Cucumber with Grails 3.2.4 for Testing with Grails?

I've been trying to do BDD testing with Grails 3.2.4 and I've had difficulty integrating Cucumber(https://cucumber.io/) with Grails 3.2. If it can be done then how do I setup cucumber for testing?

I've tried setting up with gradle cucumber but it doesn't seem to be working properly and there isn't much of a guide to getting it setup. See http://ift.tt/2lFh3tv for gradle cucumber and http://ift.tt/2mnjfnJ for Grails cucumber which is not compatible with Grails 3.2.

how to use jasmine clock (setTimeout) in nested promises when order matters? (jasmine.DEFAULT_TIMEOUT_INTERVAL error)

How to use jasmine.clock setTimeout mock inside nested promises? (result: Error: jasmine.DEFAULT_TIMEOUT_INTERVAL)

Order is crucial here.

I need to test nested promises that must have setTimeout inside - order matters. I know that then is kind of process.nextTick (or setImmediate) and it goes beyond current event loop (which is the core problem here) but this knowledge does not solve the problem :)

I know that I can put jasmine.clock().tick() inside nested promise but this is pointless because I'm testing proper order in some events related lib.

How to test something like this in jasmine? any ideas?

it("should run setTimeout mock inside chained promises",(done)=>{

      jasmine.clock().install();

      let realOrder = [];

      let ok1=new Promise((resolve,reject)=>{
          resolve("ok");
      }).then((ok)=>{
        let p=new Promise((resolve,reject)=>{
          setTimeout(()=>{ // not fired up due to 'then' method
            realOrder.push("1");
            resolve("1");
          },100);
        });
        //jasmine.clock().tick(101); //<- order is crucial here so I can't do that
        return p;
      });

      let ok2=new Promise((resolve,reject)=>{
          resolve("ok");
      }).then((ok)=>{
        let p=new Promise((resolve,reject)=>{
          setTimeout(()=>{ // not fired up due to 'then' method
            realOrder.push("2");
            resolve("2");
          },50);
        });
        //jasmine.clock().tick(51); //<- order is crucial here so I can't do that
        return p;
      });

      jasmine.clock().tick(151);// we must go outside nested promise - we dont need to run tick inplace because order will change
      Promise.all([ok1,ok2]).then((results)=>{
        expect(results).toEqual(["1","2"]);
        expect(realOrder).toEqual(["2","1"]);
        done();
      });
  });

Incorporating Django's system checks into unit test suite?

I recently deployed some broken code to our staging environment. The new code failed Django's system checks (error messages reproduced below, though this question is more general). Our unit test suite ran cleanly. My question is this: what is the right way to ensure that system checks get run before code can be deployed?

Initially I guessed that the tests were able to run without performing system checks because we use pytest instead of Django's test runner. However, adding a simple test and invoking manage.py test showed that the Django test runner also runs without performing system checks.

One idea I had is to run the manage.py check command in our build pipeline, and fail the build on a nonzero return value. A downside of this approach is that it'd introduce another developer step before code could be committed (e.g. remember to run manage.py check in addition to running the unit test suite).

Another idea is to add a unit test that runs the system checks. This seems technically feasible, but is it consistent with the purpose and design of Django's system check framework?

I note that the documentation has a section on writing tests for custom checks, which doesn't quite get at what I'm asking. I don't see other documentation on incorporating system checks into tests in the Django docs.

Error messages:

SystemCheckError: System check identified some issues:

ERRORS:
myapp.MyCoolModel.linked_groups: (fields.E304) Reverse accessor for 'MyCoolModel.linked_groups' clashes with reverse accessor for 'MyCoolModel.primary_group'.
    HINT: Add or change a related_name argument to the definition for 'MyCoolModel.linked_groups' or 'MyCoolModel.primary_group'.
myapp.MyCoolModel.primary_group: (fields.E304) Reverse accessor for 'MyCoolModel.primary_group' clashes with reverse accessor for 'MyCoolModel.linked_groups'.
    HINT: Add or change a related_name argument to the definition for 'MyCoolModel.primary_group' or 'MyCoolModel.linked_groups'.

How to automate checking all responses to a form on a website?

I would like to check all options on an airline website. So I would like a script or service to:

  • automatically log in
  • choose the departure
  • the destination
  • the date, etc.

I then needs to click some pop-ups and check the response. The site gives an error if it finds no seats, so it should be easy to see if a positive result is found.

It then needs to increment the date and try again.

I have tried Selenium, but it seems to struggle with the website when I was recording. I have also tried Screenster, but it seems it will only state if it finds errors.

Anyone have ideas or software I could try?

how run c by getting input and output in java? [on hold]

in my project i have to test some benchmark code that written in C and run and compile in java. i know how a c code run and compile in java but have no idea how get input and output in c code when my c code is running on java. my input value is some test case that must be called from c code and create some output and all this must be execute in java.

Django Same Test fails sometimes and sometimes is successful

I created a Test for my own Admin LogEntry Message. So sometimes this Test is successful and sometimes it fails. I can't understand why. Do you see the mistake here? I use this code to test my app:

python3 manage.py test

Here is the TestCase:

class AdminLogTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.admin_user = ProfileUser.objects.create(
            email='test_admin@test.de', first_name='Admin', family_name='Testadmin',
            is_active=True, is_superuser=True)
        cls.admin_user.set_password('testtest')
        cls.admin_user.save()

    def setUp(self):
        self.client = Client()

    def test_log_admin_create_user(self):
        self.client.login(email='test_admin@test.de', password='testtest')
        response = self.client.post('/admin/addressbook/profileuser/add/', {
            'address': 'Herr', 'first_name': 'Max', 'family_name': 'Meiser', 
            'email': 'test1@test.test', 'password1': 'testtest', 
            'password2': 'testtest', })
        test1_user = ProfileUser.objects.get(email='test1@test.test')
        response = LogEntry.objects.filter(
            action_flag=1, object_id=test1_user.pk)
        print(response)
        response = self.client.get('/admin/addressbook/profileuser/{}/history/'.format(test1_user.pk))
        self.assertContains(response, 'Admin Testadmin added Max Meiser')
        test1_user.delete()

And here the error:

FAIL: test_log_admin_create_user (addressbook.tests.AdminLogTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/addressbook/tests.py", line 180, in test_log_admin_create_user
self.assertContains(response, 'Admin Testadmin added Max Meiser')
  File "/usr/local/lib/python3.5/dist-packages/django/test/testcases.py", line 382, in assertContains
    self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: False is not true : Couldn't find 'Admin Testadmin added Max Meiser' in response

HTTP Traffic Monitoring for Automated Testing

I would like to be able to monitor all the HTTP requests being made by a web page in an automated testing scenario.

I know how to drive browsers with Selenium.

Is there some kind of proxy that can be interacted with programatically. What would help is something that can be flagged to start recording all the HTTP requests then flagged to stop.

I believe FireFox has some proxy settings that can be driven from Selenium but Chrome is the highest priority browser for testing.

I have heard of BetaMax but think this is more about simulating and replaying REST calls rather than monitoring traffic programatically.

assertJson failing even when fragment exists

assertJson fails even though fragment exists in response:

// test
...
$response->assertJson([
                'type' => 'multiple_choice'
            ]);
...

response dump

.....array:3 [
  0 => {#1503
    +"id": 1
    +"title_en": "Multiple Choice"
    +"title_fr": "Multiple Choice"
    +"type": "multiple_choice"
    +"created_at": null
    +"updated_at": null
  }
  1 => {#1143
    +"id": 2
    +"title_en": "Multiple Select"
    +"title_fr": "Multiple Select"
    +"type": "multiple_select"
    +"created_at": null
    +"updated_at": null
  }
  2 => {#981
    +"id": 3
    +"title_en": "Text"
    +"title_fr": "Text"
    +"type": "text"
    +"created_at": null
    +"updated_at": null
  }
]

Problems with React - Testing input datefields with Karma and Expect

I'm having a problem while testing a React component. This component is a filter for my application. There is a form with two input fields with type date, where you put a "from" date and a "to" date. I'm testing if the component is calling a prop with the correct arguments. Here is my code:

Test:

it('should call onFilterByDate when dates are provided', () => {
    var dateFrom = 1487548800000;
    var dateTo = 1487549900000;    
    var spy = expect.createSpy();
    var filterItem = TestUtils.renderIntoDocument(<FilterItem onFilterByDate={spy}/>);
    filterItem.setState({filterVisible: true});
    var $el = $(ReactDOM.findDOMNode(filterItem));

    filterItem.refs.fromDateFilter.valueAsNumber = dateFrom;
    filterItem.refs.toDateFilter.valueAsNumber = dateTo;    

    TestUtils.Simulate.submit($el.find('form')[0]);

    console.log(spy.calls[0].arguments);

    expect(spy).toHaveBeenCalledWith(moment(dateFrom).utc().unix(), moment(dateTo).utc().unix());
})

I'm passing the date value as a number to ValueAsNumber. It worked in a previous test I did.

Component:

class FilterItem extends Component {
    constructor(props) {
        super(props);

        this.state = {
            filterVisible: false
        };

        this.handleFilterByDate = this.handleFilterByDate.bind(this);            
        this.handleShowHideFilter = this.handleShowHideFilter.bind(this);
    }

    handleFilterByDate (e) {
        e.preventDefault();    
        var dateFrom = moment(this.refs.fromDateFilter.valueAsDate).unix();    
        var dateTo = moment(this.refs.toDateFilter.valueAsDate).unix();    
        this.props.onFilterByDate(dateFrom, dateTo);
    }

    handleShowHideFilter () {
        this.setState({
            filterVisible: !this.state.filterVisible
        });
    }

    var renderApp = () => {      
        if (firebase.auth().currentUser) {
            return (
            <div>
                <div className="row row-add-item box-material">
                <AddItem onAddItem={this.handleAddItem}/>              
                </div>
                <div className="row row-filter box-material">              
                <FilterItem onFilterByText={this.handleFilterByText} onFilterByDate={this.handleFilterByDate} />              
                </div>
                <div className="row row-items box-material">              
                <ItemList items={expenses} title={"Expenses"} totalValue={expenseTotal} onDelete={ this.handleDelete }/>
                <ItemList items={incomes} title={"Incomes"} totalValue={incomeTotal} onDelete={ this.handleDelete }/>              
                </div>
                <div className="row row-balance box-material">              
                <Balance expenseTotal={expenseTotal} incomeTotal={incomeTotal} />              
                </div>
            </div>
            )
        } else {
            return (
            <div className="row">
                <div className="columns small-centered medium-12 large-12">              
                <Login onGithubLogin={ this.handleGithubLogin } onGoogleLogin={ this.handleGoogleLogin } onLogout={ this.handleLogout }/>
                </div>
            </div>
            )
        }        
        }

        var renderLogout = () => {
        if (firebase.auth().currentUser) {
            return <a className="p-logout" onClick={this.handleLogout}>Logout</a>
        }
        } 

        return (
        <div>
            {renderLogout()}
            <h1 className="text-center">React Finance App</h1>
            {renderApp()}
        </div>
        )
    }
}

There are some stuff that I removed to make it more simple. The problem is, when I run the test, it calls the prop with the "fromDate" and the "toDate" as the same value. After some digging, this seems to be where the problem is, but I can't find a solution:

filterItem.refs.fromDateFilter.valueAsNumber = dateFrom;
filterItem.refs.toDateFilter.valueAsNumber = dateTo;  

These two lines seems to be changing the input values to the same value. In this case, this is the value of the "dateFrom" variable. The log that is present on the test code returns this:

LOG: [1487548800, 1487548800]

Can someone help?

Cakephp 3 Test: How to load records from database?

I need to test some reports, there is a complex data structure and a lot of data affect for those reports, so creating fixtures for this purpose would be very tedious work. I'd like to use an existing database (actually copy of it) to test reports.

How can I achieve this in cakephp 3 tests? Is it possible to load records for fixtures (not a structure of table) from database in cakephp 3?

protractor-flake not re-running failed tests

I have installed protractor-flake and use the following command to run it:

protractor-flake --max-attempts=3 --parser standard --node-bin node --color=magenta -- ../conf/conf.js

However it should re-run failed tests, but it doesn't. Why?

Automatic permissions request Android Instrumentation Tests

I am doing my first Android Instrumentation tests and some of them needs permissions as Internet or Write External Storage. Following new Marshmallow permission way,I defined these permissions in my AndroidManifest.xml and defined a rule in my test like:

@Rule
public final PermissionsRule permissionsRule = new PermissionsRule(
        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE});

PermissionsRule is:

public class PermissionsRule implements TestRule {

    private final String[] permissions;

    public PermissionsRule(String[] permissions) {
        this.permissions = permissions;
    }

    @Override
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {

                allowPermissions();

                base.evaluate();

                revokePermissions();
            }
        };
    }



    private void allowPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                System.out.println("allowPermissions "+permission);
                getInstrumentation().getUiAutomation().executeShellCommand(
                        "pm grant " + InstrumentationRegistry.getTargetContext().getPackageName()
                                + " " + permission);
            }
        }
    }

    private void revokePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                getInstrumentation().getUiAutomation().executeShellCommand(
                        "pm revoke " + InstrumentationRegistry.getTargetContext().getPackageName()
                                + " " + permission);
            }
        }
    }
}

Internet permission runs fine but write or read no. why?

How to test transclusion (ng-content) in Angular2?

i have a component to test as follow :

import {Component, OnInit, Input} from "@angular/core";

@Component({
    selector: 'column',
    template: '<ng-content></ng-content>',
    host: {
        '[class]': '"col col-" + width'
    }
})
export class ColumnComponent implements OnInit {

    @Input() public width: number;

    ngOnInit() {
        if (!this.width || this.width > 12 || this.width < 1) {
            this.width = 12;
        }
    }

}

i am not able to find an elegant way to test the <ng-content>. checked the documentations but not able to find a good way.

I thought having a test wrapper component will help. But the comp is not the one used TestContainerComponent so the test fails

  @Component({
        selector: 'test-container',
        template: `<column width="12">Hello</column>`
    })
    export class TestContainerComponent {
    }

    fdescribe(`Column`, () => {
        let comp: ColumnComponent;
        let fixture: ComponentFixture<ColumnComponent>;

        let testContainerComp: TestContainerComponent;
        let testContainerFixture: ComponentFixture<TestContainerComponent>;
        let testContainerDe: DebugElement;
        let testContainerEl: HTMLElement;

        beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [ColumnComponent, TestContainerComponent]
            }).compileComponents();
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(ColumnComponent);
            testContainerFixture = TestBed.createComponent(TestContainerComponent);
            comp = fixture.componentInstance;

            testContainerComp = testContainerFixture.componentInstance;
            testContainerDe = testContainerFixture.debugElement.query(By.css('column'));
            testContainerEl = testContainerDe.nativeElement.;

        });


        it(`Should have a width class as 'col-...' if width attribute set`, () => {
            comp.width = 6;
            testContainerFixture.detectChanges();
         expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy();
        });

    });

I guess i need a way to get the ColumnComponent component from the TestContainerComponent.

Testing for difference in bootstrapped AUC value for different classifiers

I am training five classification models for a binary classification problem. I would like to evaluate their performance and have chosen the classical AUC as the metric I want to use. Now I think that simply basing a decision on one AUC value per classifier would be inssuficient. Therefore I am creating bootstrap samples from the training data set with replacement of the same size of the original training set. So for 50 bootstraps, I have 5 times 50 AUC values which I can plot using a boxplot. Now aside from assessing their difference through visualization I would also like to assess the difference in AUC values per model by a statistical test. I have read about the following test for testing AUC values.

  • Wilcoxon test
  • Friedman's test
  • Delong's test ((DeLong et al. (1988))

As far as I understand I can use the first to detect a significant difference in AUC value of two different methods. Where the difference in AUC's of both models are taken and ranked and then the null-hypothesis is tested that one is statistically larger than the other. I read the example in the following link: http://ift.tt/1U67mvg. For which the implementation can be done using the standard R-function: wilcox.test.

I have also found some papers comparing AUC's using Friedman's test, here and here. Where the second paper seems to use the test to check if there is any difference between a whole set of K classifiers, possibly larger than 2.

As far as I understand the third bootstraps values from the ROC curve to estimate confidence intervals of the AUC and is not really a way of comparing sequences of AUC's for different bootstrap samples.

My question is: Which tests would be appropriate in this case, and are there any no-go's?

How to write a test case for my code

Is there a way for me to write a test case for my code? Do i need to remove anything before i test it using a test suite?

I am new to testing and would like to know i can test the code below.

var hello = "Hello, ";

function greet(name){

//Requirement UpperCase
function upperCase(){
if (name.toUpperCase() === name) { //uppercase string
  console.log(hello.toUpperCase() + name + '!');
} 
else {
  console.log(hello + name + ".");
}

}
//Requirement last element
function namesArray(){
if (name.length > 1){
var lastElement = name.pop();
console.log(hello + name + " and " + lastElement + ".");
}

else{
  console.log(hello + name + ".");
}

}

//Comparing name//

if (name == null) {
console.log(hello + "my friend.")
}
else if(typeof name === 'string'){//will accept strings and return them.
upperCase();
}
else if (Array.isArray(name)){//will accept arrays and return them.
namesArray();
}

}

greet()
greet("James")
greet("Ruth");
greet(["Barry", "Kate"])
greet(["Kerry", "Mike", "Snake", "FOX"])

How to write acceptance tests on ember.js for download file form?

I have a form which will download file from back-end.

<form action="" method="GET">
    <input type="hidden" name="access_token" value="">
    <input type="submit" value="Download Template">
</form>

How can i test it?

Need help in identifying code coverage tool while performing manual unit testing of a web application in JavaScript and jquery

Is there any JavaScript code coverage tool which gives the code coverage after performing manual unit test cases in browsers for a web application.please suggest.

Why is my button undefined in my test?

My test:

  describe('button component', () => {
    it('should toggle off when clicked', () => {
      let component;
      component = ReactTestUtils.renderIntoDocument(<Search />);
      let searchbtn = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'button');
      ReactTestUtils.Simulate.click(searchbtn);
      console.log(searchbtn, 'search button***'); //UNDEFINED
      expect(searchbtn.calledOnce).to.equal(false);
    })
  });

This is my search component:

  render() {
    return (
      <div className="search">
        <button className="searchButton" onClick={this.handleSearch}>{this.state.on ? 'ON' : 'OFF'}</button>
      </div>
    );
  }

Do I need to spy on it or mock it? or is there a better way to test buttons in react?

jeudi 23 février 2017

Testing if class/solution code contains string

Is it possible to test if my code contains for example "{ get; set; }". I have a BaseClass of { get; set; } syntax and I need a test to make sure that the code only contains my BaseClass of the getsetter. The test would fail if it found a { get; set; } and I would know to replace the code with my BaseClass code.

Ansible Module RAW OUTPUT

Trying to run test-module and getting bizarre output. I verified the ansible_module_my_module.py exists.

* including generated source, if any, saving to: /home/some_path/.ansible_module_generated
* ansiballz module detected; extracted module source to: /home/some_path/debug_dir
***********************************
RAW OUTPUT

/bin/sh: 1: /home/some_path/debug_dir/ansible_module_my_module.py: not found

***********************************
INVALID OUTPUT FORMAT

Traceback (most recent call last):
  File "/home/some_path/ansible/hacking/test-module", line 197, in runtest
    results = json.loads(out)
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Why doesn't enzymes find() with component props work the same way when using full rendering or shallow rendering?

According to the enzyme documentation for find() for shallow rendering and full rendering (mount), one should be able to look up components using the value of props. This does not seem to work the same way for full and shallow rendering thought I the documentation doesn't seem to explain that there would be any difference expected.

Example component under test

import React, { Component } from 'react';

class Foo extends Component {
  render() {
    return (
      <div>
        <h1>Foo</h1>
        {this.props.children}
      </div>
    );
  }
}

class Bar extends Component {
  render() {
    return (<h1>Bar</h1>);
  }
}

class FindTest extends Component {
  render() {
    return (
      <div>
        <span spanProp="spanValue">Enzyme Find Test</span>
        <Foo fooProp="fooValue">
          <Bar barProp="barValue" />
        </Foo>
      </div>
    );
  }
}

export default FindTest;
export { Foo, Bar };

Example Test File

import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';

import FindTest, { Foo, Bar } from 'components/FindTest/FindTest.js';

describe('<FindTest />', () => {
  it('can find using props with shallow rendering', () => {
    const wrapper = shallow(<FindTest />);
    // Passes
    expect(wrapper.find({ spanProp: 'spanValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find({ fooProp: 'fooValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find({ barProp: 'barValue' })).to.have.length(1);
    // Passes
    expect(wrapper.find(Foo).find({ barProp: 'barValue' })).to.have.length(1);
  });

  it('can find using props with mount rendering', () => {
    const wrapper = mount(<FindTest />);
    //Passes
    expect(wrapper.find({ spanProp: 'spanValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find({ fooProp: 'fooValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find({ barProp: 'barValue' })).to.have.length(1);
    // Fails
    expect(wrapper.find(Foo).find({ barProp: 'barValue' })).to.have.length(1);
  });
});