mercredi 30 septembre 2015

How do you test uploading a file with capybara and Dropzone?

I've switched to using the Dropzone.js plugin for drag-and-drop file uploads. How can I write a Capybara test to ensure this functionality keeps on working?

Previously I had a template with an input file element:

<input type="file" name="attachments">

And the test was simple:

When(/^I upload "([^"]*)"$/) do |filename|
  attach_file("attachments", File.expand_path(filename))
  # add assertion here
end

However this no longer works because Dropzone doesn't have a visible file input.

Firefox OS on android emulator, testing sms error

I have Firefox OS on android emulator.

When I send sms from emulator, I want get different errors for testing.

Is there a way to test various errors coming from android modem after fail sending sms?

Thank you in advance!

Android: checking a button is enabled

I am having problems with testing my app. I created an espresso test which is supposed to fail, since whenever I launch my app in the emulator, I get the expected behavior. There is my test:

 onView(withText("wrong answer")).perform(click());
 onView(withId(R.id.nextQuestionButton)).check(matches(isEnabled()));

When launching the test, nothing is reported, whereas nextQuestionButton should not be enabled upon clicking the radioButton whose text is "wrong answer".

Multiple VU in Jmeter-Only one user able to insert data

Test Plan:-

1.User logs in

2.Enter details in a form and save it(Which is stored in DB)

3.Logs out

When ran with 2 Virtual User

Number Of Threads(user) = 2

Ramp Up Period = 1 Loop Count = 1

Only 1 user is able to successfully store the details in DB

2nd Thread/user gives some url in response instead of JSON Data

When used one thread and script is ran many times it is successfully storing data in DB

Elements used:-

HTTP Cookie Manager

View Result Tree

Am I missing some element ? What mistake i am doing ?

"Installation failed since the device already has a newer version of this application" Black-box Robotium testing Android Studio

I have a black-box Robotium test working in Eclipse. I have imported the test into Android Studio. In the gradle file I've added: - Dependency to Robotium library: androidTestCompile 'com.jayway.android.robotium:robotium-solo:5.5.1'

  • The package of the app under test in the attribute: testApplicationId "package.app.under.test"

When I run the test I get the Exception:

* "Installation failed since the device already has a newer version of this application. In order to proceed, you have to uninstall the existing application." *

I tried to uninstall the app, re-install, change the version of the app but I cannot run the test.

Does anyone know how to run a black-box Robotium test in Android Studio, for an app without the source code available? Is correct to add the package of the app under test in the testApplicationId attribute.

Setting up Cucumber Testing Framework on a Mac

I have very little experience setting up automated testing. I've had success setting up Cucumber on a windows machine and managed to make the example tests pass, but now that I've switched to a Mac, Cucumber spits out this error after trying to run the example tests:

@dev
Scenario:                                           
Given I am a new user                             
When I navigate to "/"                             
Then I should see the title "intentional failure"  

TypeError: Object true has no method 'getTitle' at World.<anonymous>
(features/step_definitions/sample_steps.js:23:9)

I'm not sure what I've done wrong! Any help would be appreciated.

How can I force expression given as function parameter to be calculated after the function call?

I am writing my own testing class. The problem I have encountered is testing whether a function being tested throws expected exception.

I know I can do something like this:

try{
  tested_function($expression*$that->will()*$throw->an_exception());
}catch ($exception){
   if($exception instanceof MyExpectedException){
     echo 'OK';
   } else {
     echo 'FAILED';
   }
}

but I'd wish I don't have to write all this try ... catch block everytime, so I want to put it in a tester class method.

But when I do something like this

class Tester {
   /**
    * @param mixed expression to evaluate
    * @param string expected exception class name
    */
   public function assertException($expression, $expectedException){
     try{
       $expression;
     } catch ($ex) {
       if(is_subclass_of($ex, $expectedException)){
         echo 'OK';
       } else {
         echo 'FAILED';
       }
     }

this fails, because $expression is evaluated in the moment of method call, so before the program enters try block.

The other way I tried is to use eval and passing the $expression as a string:

class Tester {
   /**
    * @param string expression to evaluate
    * @param string expected exception class name
    */
   public function assertException($expression, $expectedException){
     try{
       eval($expression);
     } catch ($ex) {
       if(is_subclass_of($ex, $expectedException)){
         echo 'OK';
       } else {
         echo 'FAILED';
       }
     }

This is ok, but it does not allow me to use variables from the main scope, so for example this line fails $test->assertException('$d/0'); because I don't have the $d variable in Tester::assertException() scope.

Should I declare all possible variable names as global?

How can I force the expression to be evaluated within a method (or in other way achieve the desired result)?

I know that there are ready-to-use unit testers (PHPUnit, SimpleTest etc.) but I was desiring to make this myself.

Checking existance of a file on web server using server-side Javascript

I am generating html code using JavaScript on a web server and the html contains an object that has an id "ImageID" and a src parameters pointing to "Picture1.jpg".

I want to refresh the web page every 5 seconds and use Javascript to generate a new file path using incrementing numbers to say "Picture2.jpg" or "Picture3.jpg" but I want to use the Javascript to check whether such a new file name exists on the server before trying to refresh the img object using

document.getElementById("ImageID").src="Picture2.jpg";

How can server-side JavaScript be used to test the existence of a particular server-side file?

Is these a simple FileExists() method or does the object returned by document.getElementById(ImageName) have to be queried somehow to find out if it successfully found the file or not.

Thanks everyone.

NUnit: any way to build test project to standalone exe?

I have NUnit test project in my solution. I'd like to be able to run its tests on a set of different environments using a network of virtual machines and then aggregate result XMLs from each machine to my server.

I guess I would need to install NUnit to all my VMs in order to do it that way. But maybe I can avoid it somehow? Hypotetically I can change my test assembly's output type from class library to console app and call all my test methods (those ones with right NUnit attributes) using reflection manually from Main method and write XML output myself.

So I'd like to know if there are any testing framework that can make it for me. Ideally I would like it to create standalone executable that I will be able to run on a bare installed system, with no need to install some additional testing software. This executable will run all its tests and generate some test result output (it better be NUnit-compatible, but it's fine if it's not, I can handle some post processing).

Any ideas how I can achieve this? Thanks in advance.

UI test for hybrid Windows Phone apps

Does anybody know how to create UI test for hybrid Windows Phone apps?

I've already checked, that CodedUI ( Viusal Studio tool ) does not support hybrid application. It only supports Xaml based applications.

Is it bad practice to debug unit tests?

A colleague of mine mentioned that it is bad practice to debug unit tests and I'm wondering if this is true. If it is, why is this considered bad practice?

Node Jasmine 2.0 and multiple conditions

Jasmine has this funky methodology of not halting at a first failure within a test. This is fine in general, but it doesn't come without issues. I'm wondering what the best practice is for a scenario such as this:

it('should process async results nicely', function (done) {
    this.getJSON('something', function(response) {
        expect(response.status).toEqual('ok');
        expect(response.data).toBeDefined();
        expect(response.data.length).toEqual(5);
        done();
    }
}

The problem here is that this will crash the whole test suite if response.data is undefined. Then again, writing conditionals within a test case is generally frowned upon. Do I have any other choice for this scenario? Given the async nature of most of the tests, this is a very common issue.

property-based-test for simple object validation

consider this simple example:

  • Theres a Person object
  • It must have one of: FirstName and LastName (or both, but one is mandatory)
  • It must have a valid Age (integer, between 0 and 150)

How would you property-base-test this simple case?

How to analyse thor output

I have been searching for a solution to do performance test on websockets. I found thor at github. I was able to setup a simple echo server in my localhost to test thor. I was managed to get it working. But I have no idea analyzing the thor output. Below is an example output I managed to generate using thor,

Online               16525 milliseconds
Time taken           16525 milliseconds
Connected            236
Disconnected         0
Failed               0
Total transferred    4.37MB
Total received       4.37MB

Durations (ms):

                     min     mean     stddev  median max    
Handshaking          132     5685       4928    4307 16353  
Latency              5       181          60     198 276    

Percentile (ms):

                      50%     66%     75%     80%     90%     95%     98%     98%    100%   
Handshaking          4307    7358    9575    10770   13618   15008   15866   16099   16353  
Latency              198     227     233     236     240     244     253     260     276   

How can I analyse this result and set a benchmark for a Good server as well as low performing server? There isn't any documentation regarding the benchmarks in github. Can someone explain this in brief?

Identify Controls Name/ID in QT app on Linux

I am testing a QT app on Redhat Linux and many of the controls have a graphic and not text. On windows I would use Spy++ to get the id/name of the control but not sure what to use on Linux and have not been able to find an answer on Google.

I would like to be able to say: On screen xyz button project.com.moduleName.buttonName - is missing caption, does not do x as expected. It should have caption blah and should do xyz.

What are my options for find the name of the button without going to the source?

Static variable in method doesn't reset on instance unset

Interesting behavior in PHP 5.6.12-arm and PHP 7 RC3 (though I guess it's like that in all version, I just wanted to note which versions I've used to test):

Example 1 - using a static variable inside class method

<?php
class Foo {
    public function Bar() {
        static $var = 0;

        return ++$var;
    }
}

$Foo_instance = new Foo;

print $Foo_instance->Bar(); // prints 1
print PHP_EOL;

unset($Foo_instance);

$Foo_instance2 = new Foo;

print $Foo_instance2->Bar(); // prints 2 - but why?
print PHP_EOL;
?>

Question: How can a 2 be printed, since we unseted the whole instance before calling Foo->Bar() again?

Please note that this question and its answers don't answer my question.

Best regards.

Test file upload in Flask

I have a flask's controller (POST) to upload a file:

f = request.files['external_data']
filename = secure_filename(f.filename)
f.save(filename)

I have tried to test it:

handle = open(filepath, 'rb')
fs = FileStorage(stream=handle, filename=filename, name='external_data')
payload['files'] = fs
url = '/my/upload/url'
test_client.post(url, data=payload)

But in the controller request.files contains:

ImmutableMultiDict: ImmutableMultiDict([('files', <FileStorage: u'myfile.png' ('image/png')>)])

How is it possible to create flask test request that contains request.files('external_data')?

Define a constant module in elixir

I would like to create some changeable boundary module. Ideally the result would look like any other module but the behaviour could be set at compile time or in the configuration files. I think I am looking for something like define in erlang

Say I have a SystemClock module and a DummyClock tuple module. Ideally the Clock module would be one or other of the two modules above chosen in the config file.

In config/test.ex

define(Clock, {DummyClock, 12345678})

Later

Clock.now
# => 12345678

In config/prod.ex

define(Clock, SystemClock)

Later

Clock.now
# => 32145687

XCTestSuite of XCTestCase

I need to test a UIViewController which behavior depends on parameters given to it (controls are dynamically instantied in viewDidLoad based on a webservice call).

I would to be able to run the same XCTestCase derived class and inject testing the context. I thought I would use XCTestSuite for that but this is not the case as XCTestSuite is a suite of XCTest and not XCTestCase.

Basically I would like to do:

XCTestCaseSuite* suite = [[XCTestCaseSuite alloc] init];
for (Condition* condition in conditions) {
  MyTestCase* case = [[MyTestCase alloc] initWithCondition:condition];
  [suite addTestCase:case];
]
[suite runTest];

Is there any way to do this? Thanks!

Jmeter : Responce Error

I have recorded the script in jmeter. after recording i run that script and save the result in view result tree listener. In result Responce data showing me following for every sampler request

<?xml version="1.0" ?>
 <server_response>
<redirect><![CDATA[http://ift.tt/1JBLGAP;
</server_response>

Why server responce showing me timeout for every sampler? M I doing wrong recording or what is the issue? please guide me

mardi 29 septembre 2015

How to test the django webapp?

I'm trying to write a test for my django webapp but I can't seem to get a context object right when I manually populate the data structure.

def test_exclude_examed_courses_from_other():
    import social.users.views as views
    import social.users.menu_views as menu_views
    from django.utils.translation import ugettext as _
    td.login(td.users.ture)
    profile = td.users.ture.get_profile()
    grouped_subscriptions = profile.get_grouped_subscriptions()
    groupt = grouped_subscriptions.get(u'course', {})
    other_courses = groupt.get((-999, _(u'\xd6vriga')), {})
    print " OTHER COURSES " + str(other_courses)
    examed_courses = []
    examed_courses.append("context: Corporate Finance (ME1311)(5)")
    examed_courses.append("context: Electromagnetism and Waves (SK1114)(4)")      
    subscriptions_courses = views.exclude_examed_courses_from_other_courses(grouped_subscriptions.get(u'course', {}), examed_courses)

The function I'm testing is working when I run the app:

def exclude_examed_courses_from_other_courses(subscriptions_courses, examed_courses):
    if examed_courses:
        examed_contexts = [course.context for course in examed_courses]
        other_courses = subscriptions_courses.get((-999, _(u'\xd6vriga')), {})
        for course.context in examed_contexts:
            if course.context in [subscription.context for other_course, subscription in other_courses.iteritems()]:
                del subscriptions_courses.get((-999, _(u'\xd6vriga')))[course.context.name]
    return subscriptions_courses

How should I write the test? The error I'm getting is that the context object doesn't exist:

#929      test_my_subscriptions.test_exclude_examed_courses_from_other ...  OTHER COURSES {u'Artificial intelligence (DD2380)': <Subscription: (id: 1, user: Ture Tureson, context: Artificial intelligence (DD2380)(3)), as_email: False>, u'Corporate Finance (ME1311)': <Subscription: (id: 3, user: Ture Tureson, context: Corporate Finance (ME1311)(5)), as_email: False>, u'Electromagnetism and Waves (SK1114)': <Subscription: (id: 2, user: Ture Tureson, context: Electromagnetism and Waves (SK1114)(4)), as_email: False>}
> /etc/proj/social/social/users/views.py(310)exclude_examed_courses_from_other_courses()
-> examed_contexts = [course.context for course in examed_courses]
(Pdb) [course.context for course in examed_courses]
*** AttributeError: 'str' object has no attribute 'context'

ZAP security tool is very time consuming

I have run ZAP security tool for Test .net MVC application, ZAP tool takes too much time to run script and sometimes tool not responding well. Is there any other tool which gives me accurate results like zap?

Thanks.

Rename data-driven Coded UI test name

So I'm using Coded UI [VS 2013 Premium] to test a very large software.

I'm in the process now of automation one module that is called by 69 different ways. I want to use data-driven testing but I have a problem with the results. The test results outcome does not have a very detailed test name "CodedUITest_1", "CodedUITest_2"...

Is there a way to programmatically rename my test in any way?

I'm currently trying on playing with TestContext but no luck.

Thanks for the help.

How to create in-app quiz based on user-generated data in Rails 4

I'm creating my first rails app, a glossary app, which has three main models: Language, Glossary and Word.

The Word.rb holds the words created by users and contains the following attributes: id, word, transcription, translation, glossary_id, language_id

What I wanna do is to collect these words within the particular glossary, for instance "English", and create in-app quiz for testing words, which belong to this glossary.

But I stuck at this very moment...

The quiz is going to contain a number of questions(words to repeat) chosen by the users, but mustn't exceed the actual number of words in the glossary. A question page will have a question itself and 4 variants of answers, each question should be displayed on a separate page.

The Question page will follow this pattern, I suppose:

<%= @glossary.words.each do |word| %>
  <h1>What's the translation for <%= word.word %>?</h1>

  <%= @words.each do |word| %>
    <ol><li><p><%= word.translation %></p></li></ol>
  <% end %>
<% end %>

But I can't understand how to assign the correct answer, as well as, how to make the words within the answers section to be random on every single question and of course how to create per page question view with the progress bar of the test.

I appreciate any help! Thanks in advance!

How do I properly write out a JUnit test for a method that counts how many e's are in a string?

Here is the method I have defined that is supposed to accept a String as input and should return the number of times the char 'e' occurs as an int:

public int count_e(String input){
    int count = 0;
    for (int i = 0;i<input.length();i++){
        char e = 'e';
        if (input.charAt(i)==e){
            count=count+1;
            i++;
            return count;
        }
        else{
            count=count+1;
            i++;
        }
    }
    return count;
}

}

I am trying to write a JUnit test to see if I can input a string into the method and return the correct number of e's. Below is my test, and at the moment I keep getting an error saying that my method count_e is undefined for type String.

Can someone tell me why it is coming up as undefined?

@Test
public void testCount_e() {
    String input= "Isabelle";
    int expected= 2;
    int actual=input.count_e();
    assertTrue("There are this many e's in the String.",expected==actual);
}

}

How to get test-instances from HP ALM using REST API using Java?

I've successfully connected to HP ALM, but do not know how to get the test-instance data. This is what the url looks like:

http://ift.tt/1VpRswf

Is there a way to append a query to the URL and get all the test-instances under this project?

Thanks

TestFlight not showing the full build images/not downloading the whole build

I'm trying to see if any one has the same problem ever since the "processed file exceeds 100Mb" Error appears next to my builds submitted to iTunes connect when I put it up for Testing using the test flight app. When people download it the images are not there just X's. It's like not all of my project is being uploaded. So is this something that will be fixed after my app gets approved the Apple Store. Or is this a problem just wondering? Thanks

Testing for exception fails

When I save a User model, I would like to check if it has a username. Therefore I wrote this pre_save:

@receiver(pre_save, sender=User)
def validate_user(sender, instance, **kwargs):
    if len(instance.username) <= 5: raise Exception("Username too short")

Now in my testing method I would like to test this exception:

def test_user_no_username(self):
    u = User.objects.create()
    self.assertRaises(Exception, u.save())

The test fails. Why?

Mocking NSBundle infoDictionary

What is the correct way to mock NSBundle's infoDictionary in a Swift unit test?

If I try to override the method I get a number of errors and warnings

enter image description here

Also, how should a stored property be overriden in unit tests?

How to test OneToOne with User?

I trying to write a test, which asserts if a profile model is created, once a user model is.

My profile model looks like this

class Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    image_url = models.URLField(max_length=500, blank=True)
    address = models.ForeignKey(Address, null=True, blank=True)

My test method looks like

class TestUserBasics(TestCase):
    def test_profile_user_one_to_one(self):
        u = user.objects.create()
        u.save()
        self.assertTrue(u.profile != None)

The test fails, for the test user has no profile field. However in manage.py shell the same scenario ends positive.

What am I missing?

How internal tester can download the "Android" pre-released App build?

Could anyone plz let me know, How internal tester can download the "Android" pre-released App build ? Because now "TestFlight" is only for iOS as acquired by Apple. Whether, solution is to upload the Android pre-release app build on "Google Play" and invite internal-tester to get download. **Earlier I used "TestFlight", I downloaded pre-released app build on iOS7 device, the distributed by Developer for internal testing. Thanks,

Rake doesn't create Mailer Templates when running RSpec

In our project we have rake task, that creates mailer templates in database. While running all specs, some of them are failing saying that the db record for some mailers don't exist. Any ideas on what could be the reason for this and how to fix it?

Here the example of the task to create Mailer template.

desc "Creates mailer templates"
task create_mailers: :environment do

  MailerTemplate.delete_all

  I18n.available_locales.each do |locale|
    MailerTemplate.create(locale: locale, mailer: "info#action", content: %{<p>Content</p>})
  end
end

Dynamically Running Mocha Tests

I'm trying to run a series of tests dynamically. I have the following setup but it doesn't seem to run and I'm not getting any errors:

import Mocha from 'mocha';
const Test = Mocha.Test;
const Suite = Mocha.Suite;
const mocha = new Mocha();
for (let s in tests) {
  let suite = Suite.create(mocha.suite, s);
  tests[s].forEach((test) => {
    console.log('add test', test.name)
    suite.addTest(new Test(test.name), () => {
      expect(1+1).to.equal(2);
    });
  });
}
mocha.run();

The tests I'm running look like this:

{ todo: 
  [ { name: 'POST /todos',
      should: 'create a new todo',
      method: 'POST',
      endpoint: '/todos',
      body: [Object] } ] }

(though at this point my test is just trying to check a basic expect)

Based on the console.logs the iteration seems fine and it appears to be adding the tests, so I'm confident in the flow of operations, I just can't get any execution or errors.

How to interpret graph result of jmeter load test?

I am running a test with jmeter on osx against a server cluster. Now I am wondering how to interpret the test results taken with "graph result".

This is an example output running 50 threads on a macbook pro 2015:

enter image description here

It states 2,090.949/minute throughput. Is this 2M requests per minute? That would equal 33K/s ?! The y-Axis indicates ms, is this latency or time for each request? What do the numbers Average, Median etc. indicate, are those ms per request?

Thank you for any help on this.

Get exceptions from log

There are a lot of fail-safe processes in the Java application, which I test. This means, all the exceptions are caught and logged. I want to check, how many, and what kind of exceptions occurred during the test run. How can I do it?

We are using Logback to log.

My first idea is to write logs to a file, and parse it in the test, but it isn't so nice and fast solution. Any better idea?

Android testing. Espresso. Change text in a TextView

It is easy to update an EditText with Espresso, but I can not find a way to change a text (like with a TextView.setText("someText"); method) during the testing process.

 ViewAction.replaceText(stringToBeSet);

Is not working, cos it should be an EditText;

How to test links with RSPEC

I have a side navigation menu and top navigation menu rendering using partials on all pages. On the welcome page, I am trying to check the clicks. I have this, but it is not working at the moment.

it "Checks the home link"
  get '/welcome'
  sleep 5
  page.should have_content("Basis tool")
end

JMeter: "Response code: 500, Response message: Internal Server Error" in Sampler Result

I am extracting all dynamic values of my asp.net Website dynamically however, I can see "Response code: 500, Response message: Internal Server Error" in Sampler Result.

Below is the Request from View Results in a Tree:

POST http://MyURL/MyPortal/login.aspx

POST data:
__VIEWSTATE=%2FwEPDwUKMTI3MjAzNjAzNGRkjr4joFF5LWOOmI2LfqKYaLCnJoWEEuersumW%2Fyg8oSE%3D&__EVENTVALIDATION=%2FwEdAAe%2FZNCyf7CfdyOuzLZ7mDoL9Tt6KoVd96dN6zOjIKoOlInkg%2Fut7Je4AtoEsfzZAOLszNp1xh91HdjgSkSmA8AOAmWyFUPYYwjYUgZAnHgtx2Vqz9dZFL0pGDKPfgeuicZtnfqjBya34OcE2Eru6nT4MwnrIcmty4bwVAU6VEb6qrGc%2BEe7Y58My78ZHzJqq0k%3D&txtUserID=1111111&txtPWD=ASDF&BtnSubmit=Submit&hdnE=5&hdnN=323&hdnD=173

Cookie Data:
ASP.NET_SessionId=e0ibh0ihceof54ulvhkx1

Request Headers:
Connection: keep-alive
Referer: http://MyURL/MyPortal/login.aspx
Accept-Language: en-US,en;q=0.5
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Length: 386

And, Response Code is:

<!DOCTYPE html>
<html>
    <head>
        <title>Runtime Error</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/MyPortal' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>Runtime Error</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
            <br><br>

            <b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a &quot;web.config&quot; configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its &quot;mode&quot; attribute set to &quot;Off&quot;.<br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

&lt;!-- Web.Config Configuration File --&gt;

&lt;configuration&gt;
    &lt;system.web&gt;
        &lt;customErrors mode=&quot;Off&quot;/&gt;
    &lt;/system.web&gt;
&lt;/configuration&gt;</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the &quot;defaultRedirect&quot; attribute of the application&#39;s &lt;customErrors&gt; configuration tag to point to a custom error page URL.<br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

&lt;!-- Web.Config Configuration File --&gt;

&lt;configuration&gt;
    &lt;system.web&gt;
        &lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;mycustompage.htm&quot;/&gt;
    &lt;/system.web&gt;
&lt;/configuration&gt;</pre></code>

                  </td>
               </tr>
            </table>

            <br>

    </body>
</html>

JMeter: "Object moved to here" as Response Code

I am load testing for Login/Logout feature implemented in ASP.NET. When a number of users are increased, it starts showing response code as following after one of the user logout:

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/aurl/Login.aspx">here</a>.</h2>
</body></html>

I have checked "Follow Requests" in HTTP Sampler.

Selenium Webdriver can't find elements inside of iframes

I'm having some problems trying to run a test with selenium webdriver when an Iframe is present on the code.

There is a single Iframe inside the webpage with that I'm working:

<div class="bwc layout">
    <div class="bwc-frame">
        <iframe id="bwc-frame" class="bwc-frame" src="index.php?module=Campaigns&action=EditView&return_module=Campaigns&return_action=index&bwcFrame=1">
            (...)
        </iframe>
    </div>
</div>

But, when i try to find an element inside of that frame i get this error message:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"name"}

If i use Selenium IDE i haven't problems finding that element. It happens only with webdriver.

This is my (selenium) code:

WebDriver drive = new FirefoxDriver();
driver.get(myUrl);
WebDriverWait wait = new WebDriverWait(driver, 20);

//Login in my site
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("username")));
driver.findElement(By.name("username")).sendKeys("username");
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.name("login_button")).click();
//end of Login (everything is ok with this part, no Iframes inside)

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //For Web Loading
driver.switchTo().frame(0); //There is a single Iframe 
driver.findElement(By.id("name")); //Webdriver can't find this element

I tried to switch to frame in many different ways:

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.bwc-frame")));

or

driver.switchTo().frame("bwc-frame");

However I'm getting the same result.

I also tried an explicit wait instead of implicit wait:

wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("iframe.bwc-frame")));

and i get the same result, NoSuchElementException when i try to find the element inside of Iframe.

Please, anyone have any idea why this is failing ? Thanks.

How to mock model attributes with Rspec?

I have a controller action with something like:

    @widget = Widget.new(permitted_params)
    @widget.user_id = current_user.id

    if @widget.save
      @widget
    else
      { errors: @widget.errors.full_messages }
    end

And I'm trying to create a spec for that controller.

widget = mock_model(Widget)

allow(Widget).to receive(:new).and_return(widget)
allow(widget).to receive(:user_id).and_return(widget)
allow(widget).to receive(:save).and_return(true)

expect(widgets).to receive(:build)
expect(widget).to receive(:save)
post '/v2/widgets', name: 'foo'
expect(json_response).to eq widget.as_json

Now the weird thing that I'm getting :

 Failure/Error: post '/v2/widgets', name: 'foo'
   #<Double "Widget_1133"> received unexpected message :user_id= with (1129)

Even when I have

allow(widget).to receive(:user_id).and_return(widget)

Any help what is the mistake i'm doing?

Thanks

Running AngularJS / Jasmine tests on build or source version of a project

I'm building a project with the help of AngularJS with multiple apps in one projects sharing components / modules.

Now I'm starting to write my tests in Jasmine and I'm wondering if I should use the "optimized" build by Grunt or the real sources as the base of my tests.

The Grunt build also bundles files and templates in different folders than they are in orginal project source. That's why loading templates fails in the tests relying on the orginal source, because after the build they are located in a different paths, which get used in the components. (i.e. original: /app/apps/foo/templates/bar.html -> after build: /templates/bar.html)

So the overall question is: Should I run my tests in Jasmine for an AngularJS project on the orginal sources or the builded version?

Multiple users login & Performing different tasks using selenium

My requirement is that 10 different users should be able to login to a particular website and perform different tasks and then after 1 hour all the users should logout simultaneously.

Can this be automated using selenium +testng?? If not,which tool can I use for this particular Load Testing??

Trying to understand number of ParseError in html5lib-test

I was looking at following test case in html5lib-tests:

{"description":"<!DOCTYPE\\u0008",
"input":"<!DOCTYPE\u0008",
"output":["ParseError", "ParseError", "ParseError", 
           ["DOCTYPE",  "\u0008", null, null, false]]},

source

State                      |Input char |  Actions
--------------------------------------------------------------------------------------------
Data State                 |  "<"      | -> TagOpenState
TagOpenState               | "!"       | -> MarkupDeclarationOpenState
MarkupDeclarationOpenState | "DOCTYPE" | -> DOCTYPE state
DOCTYPE state              | "\u0008"  | Parse error; -> before DOCTYPE name state (reconsume)
before DOCTYPE name state  | "\u0008"  | DOCTYPE(name = "\u0008"); -> DOCTYPE name state
DOCTYPE name state         | EOF       | Parse error. Set force quirks on. Emit DOCTYPE -> Data state. 
Data state                 | EOF       | Emit EOF.

I'm wondering where do those three errors come from? I can only track two, but I assume I'm making an error in logic, somewhere.

Junit tests for JPA Repository methods

I have the following test method:

@Injected
private ProductRepository productRepository;
    @Test
    @Transactional
    public void shoudChangeProductTilte(){
    Product product = productRepository.getProductById(123L);
            product.setTitle("test_product");
            productRepository.save(product);
            Product updatedProduct = productRepository.getProductById(123L);
    assertNotNull(updatedProduct);
            assertEquals("test_product", updatedProduct.getTitle());
    }

My question is: Do you see any sence in this test? Is it looking good?

All method will be executed it one transaction. I am not sure that we will write anything directly to db. Also, I do not like idea with product and updatedProduct ... hmm, I feel that something wrong, but is it really true?

What do you think?

Specflow - Is there a way to manage a background so that it only runs for certain scenarios in a feature?

I have a Specflow .feature file containing a number of scenarios.

The majority of the scenarios within the feature file use a background. However, one scenario does not require this background.

How can I stop the background from running for this specific scenario without having to move it to a separate feature?

Radio button onclick() Jwebunit not working

I am using Jwebunit to test a webapp which contains radio buttons with onclick() javascript function. When I use the function clickRadioOption(radiogroup, radiooption) the onclick function does not get triggered.

Note: my radio button didn't have the value attribute and since the clickRadioOption function takes value as an attribute, i first added the value attribute to my radio button by using IElement.setAttribute(attribute,value) function.

Sample Code:IElement radio = getElementById(buttonid); radio.setAttribute("value",but_value); clickRadioOption(radio_grp,but_value);

lundi 28 septembre 2015

How to handle double entry check java script prompt using selenium

any one help me out, scenario: need to fill the double entry check prompt/alert This prompt/alert has two text boxes.. need to fill these two and click on ok button.

Tried solutions: 1) Switch to the prompt/alert using Alert alert1=driver.switchTo().alert(); with out any error able to switch to alert. but unable to locate textboxes. 2) This prompt looks like window.. but by using getWindowHandles() is not giving any of window code to this prompt.. so it mayn't be a window..

Thanks, sateesh.k

Applying multiple Spring profiles to a single Configuration class

I have 4 possible Spring profiles for my application

  • TEST (This is for Unit/Integration testing)
  • QA
  • STAGE
  • PRODUCTION

The last 3 in the above list are actutal environments in which this application will run.

Here's the overview of my configuration class called AppConfig

@Configuration
@ComponentScan(basePackages={"org.mycompany.services","org.mycompany.domain", "org.mycompany.utils"})
public class AppContext {

}

Here's my question: I want the AppContext's configuration to be applied for QA, STAGE and PRODUCTION profiles only (But not for TEST profile). What's the best way to do that?

The reason for this is that the above config class scans & picks classes from org.mycompany.services. But I do not want this package to be picked up for TEST profile as I'm intending to mock the classes in this package using Mockito.

Another possible question is if I need to rethink the way I'm approaching Unit/Integration testing so that I can simplify mocking of classes in org.mycompany.service package?

On a web page with Html Table, how do I determine if a Html Row is selected or not using c#?

I am using Visual Studio 2015 and doing Test Automation - On a web page with Html Table, how do I determine if a Html Row is selected or not using c#?

What is Pairwise testing and does it require special software?

What is pairwise testing? Is this method preferred over equivalence classes and boundary value testing? Does pairwise testing require the use of automated test case generation software?

spring test - setup data, run tests and rollback

I have many spring tests across many test classes. What I'd like to do is:

  1. run a db script to initialize the data (only once)
  2. run all tests
  3. run another db script to update the data to the original state (only once)

I've been struggling about this... what would be the best approach to solve this issue?

Thanks a lot in advance!!

Need to mock elastic search response

Hi i need to test a program that consume an elastic search server, but i need to mock the response from elastic search. When mocking the connection to external endpoints we used wiremock, but it seems that this won't work with an elastic search query.

The program that we need to test is developed using spring boot and java 8.

Have anyone test an elastic search query mocking the service?

Greetings!

Codeception: how do I test file download?

I have a page with a several options and a button named "Download".

How do I test that this button works - document begin downloading, using Codeception acceptance tests?

Unit test on another pc

I want to generate an executable from my unit test in VS2015. So another person on another computer without VS can start the test and see an output of the unit test. (Which one is failed, which not)

Is this possible or should I manually write a tool for that?

I can't find anything on MSDN.

Testing an impure function

As part of an online programming course (6.00.1x), I'm asked (Quiz p8) to create a function, satisfiesF(L), that filters L in-place using f, then returns the length of L.

  • f is a function defined for me that returns True for items that should remain in the list
  • The remaining list items should be in the same order as before

I've written 2 solutions to this problem, tested them, and submitted them, but both were rejected. No reason was provided, as the problem is designed to test our ability to come up with our own test cases. For this reason, please do not provide working code, but rather give me a general idea of what's going wrong. I see 3 main possibilities at the moment:

  • I have misunderstood the problem
  • I made a subtle programming mistake
  • edX made a mistake with their test cases (unlikely)

Here are my 2 solutions:

def satisfiesL(L):
    L[:] = [i for i in L if f(i)]
    return len(L)

def satisfiesL(L):
    i = 0
    while len(L) > i:
        if f(L[i]): i += 1
        else: L.pop(i)

Here is the full description of the problem verbatim:

Write a Python function called satisfiesF that has the specification below. Then make the function call run_satisfiesF(L, satisfiesF). Your code should look like:

def satisfiesF(L):
    """
    Assumes L is a list of strings
    Assume function f is already defined for you and it maps a string to a Boolean
    Mutates L such that it contains all of the strings, s, originally in L such
            that f(s) returns True, and no other elements. Remaining elements in L
            should be in the same order.
    Returns the length of L after mutation
    """
    # Your function implementation here

run_satisfiesF(L, satisfiesF)

For your own testing of satisfiesF, for example, see the following test function f and test code:

def f(s):
    return 'a' in s

L = ['a', 'b', 'a']
print satisfiesF(L)
print L

Should print:

2
['a', 'a']

Paste your entire function satisfiesF, including the definition, in the box below. After you define your function, make a function call to run_satisfiesF(L, satisfiesF). Do not define f or run_satisfiesF. Do not leave any debugging print statements.

For this question, you will not be able to see the test cases we run. This problem will test your ability to come up with your own test cases.

And, for the sake of completeness, here are my latest set of tests (I'm using [doctest]):

>>> L = ['bat', 'cat', 'dog', 'elephant']
>>> satisfiesF(L) == len([i for i in L if f(i)])
True
>>> [i for i in L if not f(i)]
[]
>>> L = ['ab', 'b', 'ac']
>>> satisfiesF(L)
2
>>> L
['ab', 'ac']
>>> L = ['a', 'a', 'b']
>>> satisfiesF(L)
2
>>> L
['a', 'a']
>>> L = ['a', 'a', 'a']
>>> satisfiesF(L)
3
>>> L
['a', 'a', 'a']
>>> L = ['b', 'c', 'd', 'a']
>>> satisfiesF(L)
1
>>> L
['a']

I've tried replacing satisfiesF(L) with run_satisfiesF(L, satisfiesF), but the tests still pass.


Other questions about 6.00.1x Quiz p8

Protractor: Find Element by Attribute

I have the following element i need to find for testing:

<div class="alert alert-danger" role="alert" ng-show="notValid">Zugangsdaten eingeben</div>

How can i find this element to check visibility (ng-show)?

The ng-show attribute and value are the only attribute and value to identify the element uniquely. The class is used in many elements...

I am searching for something like:

var notValid = element(by.Attribute('ng-show', 'notValid');

XCTest test for not happening before timeout

I found a lot of questions about how to write a unit test that tests whether something happens before a timeout, using something like

- (void)waitForExpectationsWithTimeout:(NSTimeInterval)timeout handler:(nullable XCWaitCompletionHandler)handler;

but are there any ways to test for "Make sure X does not get called within Y seconds" ?

Our current approach was something like:

[[NSRunLoop currentRunLoop] runUntilDate:<short before timeout>]

and afterwards check that the block never got called.

Unfortunately since XCode 7 the outcome of these tests has become very non-deterministic... is there a better way to test this?

Running integration/acceptance tests for an umbrella app in elixir

I have a project that consists of an Umbrella App. The child apps under the umbrella consist of a core/main/domain application a delivery app, a database backed repository and an in memory repository.

I would like to write a few integration tests that send http requests and check the changes in the database. As these tests require the coordination of several of the child apps these tests belong in the umbrella app and not in an individual childs test directory.

The default umbrella project does not get created with a test directory so I am unsure where they belong.

I have created a test dir and added a test_helper.exs that calls ExUnit.start and a project_test.exs test. but when I run mix test from the umbrella directory it only finds test in the apps/component/test directory and not the tests in the test directory

How can i test the response time of a website for free?

I am a computer science student ,planning to develop a website for my dissertation. I am just developing a artifact of the website to show my concept with the database provided by the university. how can i test the response time and performance using the open source testing tool? Please help me, i need to include testing and evaluation of my artifact in my documentation. Is there any tool/website which tests the website model?

php user-level session persistence

I have a use-case where I need to be able to access my site from the local server. Specifically, it's for a html-to-pdf export of parts of various pages, but this would be nice for testing parts of the website as well.

The problem is that we have a login splash page, which needs to be dealt with before I can access any parts of the website. It would be really nice if I could just call a command "wkhtml2pdf 'localhost/[myurl]'" and have it pdf some stuff, but it hits this splash page.

Is there some way that I can perma-persist just one single session on the server? Or enable login-less access from localhost? Or could I just add a new apache entry that accesses our site, whitelists only localhost and somehow circumvents the login?

Anybody out there handling this problem? What's the best solution?

-Scott!

JMeter: Is there any way to inject value "Patient_1077,ELLA(161st Pharmacy address)" in a input field

I have a a field which accepts value as "Patient_1077,ELLA(161st Pharmacy address)" i.e: Patient ID, name and Address, that I want to parameterize, CSV is not helpful in this case as value contains comma itself, is there any alternative way where I can inject these kind of values from file and parameterize the same?

Can we do performance testing on share point 2013 web app using visual studio ultimate 2010?

As per our client's request we are going to do performance testing on share point 2013 we application so can i use visual studio ultimate 2010?

Code coverage and Node coverage

please help me to do these questions..

1.What is the the minimal set for 100% Node Coverage?

2.What's the coverage level of Edge coverage for the above given Test set?

`public static void bubbleSort(int[] numArray) {

int n = numArray.length;                           //NODE1
int temp = 0;                                      //NODE1

for (int i = 0; i < n; i++) {                      //NODE2
    for (int j = 1; j < (n - i); j++) {            //NODE3
        if (numArray[j - 1] > numArray[j]) {       //NODE4
            temp = numArray[j - 1];                //NODE5
            numArray[j - 1] = numArray[j];         //NODE5
            numArray[j] = temp;                    //NODE5
        }
    }
} 

Sysytem.ot.println("end"); //NODE6 }`

dimanche 27 septembre 2015

IKM Questions for Manual and Automation Testing

I need to know how the pattern comes for IKM test for manual and automation testing.Am preparing for IKM test ,i am going to take up the test next month.How to prepare for the test?Guide me with materials please!!

Making a software test harness - combination of methods

I am building a software test harness in Java using the concept of reflection. The specification is that I will need to create test cases which have combination of methods.

For example, if you have the method int f(string) and the method float g(int) and the method string h(float), we would expect to test the combinations h(g(f("first value from a file"))), h(g(f(h(g(f"first value from a file")))))) and so on.

I have done it for a low level combination - f(h()); Can anyone help me with generating the next level combinations ?

Here's my code till now:

public static void LevelOne(Test testObject, Method[] method)
    {
        try{
        for(int i=0; i<method.length; i++)
        {
            for(int j=0; j< method.length; j++)
            {
                if( i!=j)
                {
                    Class[] parameterTypes = method[j].getParameterTypes();
                    Class returnType = method[i].getReturnType();
                    for( int k=0; k < parameterTypes.length; k++)
                    {
                        if(returnType.equals(parameterTypes[k]))
                        {
                            Class[] parameterFunction = method[i].getParameterTypes(); 
                            for(int l = 0; l < parameterFunction.length ; l++)
                            {
                                if(parameterFunction[l].equals(int.class))
                                {
                                    for(int num = 0; num <100; num++)
                                        method[j].invoke(testObject, method[i].invoke(testObject, num));
                                }

                                else if(parameterFunction[l].equals(String.class))
                                {
                                    method[j].invoke(testObject, method[i].invoke(testObject, "Hello World"));
                                }

                                else if(parameterFunction[l].equals(float.class))
                                {
                                    for(float num = 0.0f; num < 100.0f; num = num + 0.5f)
                                        method[j].invoke(testObject, method[i].invoke(testObject, num));
                                }

                                else;
                            }
                        }
                    }
                }
            }
        }
    } catch(Exception e)
        {

        }
    }

MediaType of Png. HTTP request

I've a web app with some static content. For example, I've an image published in http://localhost/images/Head.png.

Now, I'm doing a Http request to this image.

ResponseEntity<byte[]> entity = new TestRestTemplate().getForEntity("http://localhost/images/Head.png", byte[].class);`

And I want to know which content has this entity. It should be image/png, but it isn't. I get an exception here:

 assertEquals("Wrong content type:\n" + entity.getHeaders().getContentType(),
              MediaType.valueOf("image/png"), entity.getHeaders().getContentType());`

Which content type should I be?

Thanks.

How can I make my test file work?

I have 3 class files: Bin2Dec implements to throw an exception, BinaryFormatException is the exception file, and bin2DecTest is the test file to test the correct operation of both the BinaryFormatException and bin2Dec. I don't know why but I can't get the test file to run. Someone please help me!!

TEST FILE:

    //Prepare scanner from utility for input.
    import java.util.Scanner;
    public class bin2DecTest {
        public static void main (String[] args){
            //Convert the input string to their decimal equivalent.
                //Open scanner for input.
                    Scanner input = new Scanner(System.in);
                    //Declare variable s.
                    String s;

            //Prompt user to enter binary string of 0s and 1s.
            System.out.print("Enter a binary string of 0s and 1s: ");
            //Save input to s variable.
            s = input.nextLine();
                //With the input, use try-catch blocks.
                //Print statement if input is valid with the conversion.
                try {
                 System.out.println("The decimal value of the binary number "+ "'" + s + "'" +" is "+conversion(s));
                 //Catch the exception if input is invalid.
                  } catch (BinaryFormatException e) {
                      //If invalid, print the error message from BinaryFormatException.
                    System.out.println(e.getMessage());
                  }
                }
    }

Bin2Dec FILE:

    //Prepare scanner from utility for input.
    import java.util.Scanner;
    public class Bin2Dec {
                  //Declare exception.

          public static int conversion(String parameter) throws BinaryFormatException {
            int digit = 0;

          for (int i = 0; i < parameter.length(); i++) {
              char wrong_number = parameter.charAt(i);


              if (wrong_number != '1' && wrong_number != '0') { 
                throw new BinaryFormatException("");
              }

              //Make an else statement and throw an exception.

              else 
                digit = digit * 2 + parameter.charAt(i) - '0';
            }
            return digit;
          } 
        }

BinaryFormatException FILE:

    //Define a custom exception called BinaryFormatException.
    public class BinaryFormatException extends Exception {
        //Declare message.
          private String message;
          public BinaryFormatException(String msg) {
            this.message = msg;
          }
          //Return this message for invalid input to Bin2Dec class.
          public String getMessage() {
             return "Error: This is not a binary number";
          }
        }

Can you run a specific Xcuitest from the command line?

Playing with iOS 9.0, Xcode GM and the new Xcuitesting framework. How can I run a specific test from the command line instead of having to click play in the ide? I know there's a shortcut to run all the tests but I want to run a single test.

Thanks!

Can you run Xcuitests in parallel?

Wondering if anyone has found a way to run Xcuitests in parallel. Pretty sure this functionality isn't built in but it may be possible to write a script that can spread it over multiple machines if you can run a specific Xcuitest from the command line.

So sub question, how do you run a specific Xcuitest from the command line?

I'd appreciate it if anyone's played around with this and can share what they've learned or if they have any resources they could point me to. Thanks!

What is the purpose of preparing a check list?

I was reading about project audit and review checklist but didn't understand the purpose of creating checklist in software test.

TestKit for Erlang

Is there any kind of test framework for Erlang which is similar to TestKit in Akka?

The goal is to test processes in an integrated environment, for example, to send some messages to a group of processes on one end and assert the resulting messages coming out on the other end. The Akka Testkit makes these kinds of tests fairly straightforward, but I have not been able to find the equivalent in Erlang yet.

How to testing Spring validator with Junit and Mockito

I have a Spring Validator:

@Component
public class AddClientAccountValidator implements Validator {

    @Autowired
    private ValidatorUtils validatorUtils;

    @Override
    public boolean supports(Class<?> clazz) {
        return UserDto.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserDto user = (UserDto) target;
        validatorUtils.setParam(errors, user);

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
                "confirmPassword.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "personalId", "personalId.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "city.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "phone.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "contribution", "contribution.required");

        validatorUtils.validateAddClientAccount();
    }
}

In above Validator have inject to ValidatorUtils class:

@Component
class ValidatorUtils {

    @Autowired
    private PersonalIdValidator personalIdValidator;
    private Errors errors;
    private UserDto user;

    void setParam(Errors errors, UserDto user) {
        this.errors = errors;
        this.user = user;
    }

    void validateAddClientAccount() {
        validateAccount();
        validContributionAccount();
    }

    private void validateAccount() {
        validUsername();
        validPassword();
        validFirstName();
        validLastName();
        validPersonalId();
        validCity();
        validAddress();
        validEmail();
        validPhone();
    }
    public void validateChangePassword() {
        validChangePassword();
    }

    private void validUsername() {
        if (!user.getUsername().isEmpty()) {
            String username = user.getUsername();
            if ((username.length() < 3) || (username.length() > 40)) {
                errors.rejectValue("username", "username.format");
            }
        }
    }

    private void validPassword() {
        if (!user.getPassword().isEmpty()) {
            String password = user.getPassword();
            if ((password.length() < 3) || (password.length() > 40)) {
                errors.rejectValue("password", "password.format");
            }
            if (!password.equals(user.getConfirmPassword())) {
                errors.rejectValue("confirmPassword", "password.confirm");
            }
        }
    }

    private void validFirstName() {
        if (!user.getFirstName().isEmpty()) {
            String firstName = user.getFirstName();
            String regex = "[A-ZŁ{1}]+[a-zł]+";
            boolean validFirstName = Pattern.matches(regex, firstName);
            if ((firstName.length() < 3) || (firstName.length() > 40) || !validFirstName) {
                errors.rejectValue("firstName", "firstName.format");
            }
        }
    }

    private void validLastName() {
        if (!user.getLastName().isEmpty()) {
            String lastName = user.getLastName();
            String regex = "[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]+";
            String regexWithTwoLastName = "[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]++[\\s]+[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]+";
            boolean validLastName = Pattern.matches(regex, lastName);
            boolean validWithTwoLastName = Pattern.matches(regexWithTwoLastName, lastName);
            if ((lastName.length() < 3) || (lastName.length() > 40)
                    || (!validLastName && !validWithTwoLastName)) {
                errors.rejectValue("lastName", "lastName.format");
            }
        }
    }

this class have more validator for field but I skipped it.

I want to test my Validator class use Junit or eventually mockito. I write this test class:

    @RunWith(MockitoJUnitRunner.class)
public class AddClientAccValidatorTest {

    @InjectMocks
    private AddClientAccountValidator validator;
    @Mock
    private ValidatorUtils validatoUtils;
    private UserDto userDto;
    public Errors errors;

    @Before
    public void setUp() {
        errors = new BeanPropertyBindingResult(userDto, "userDto");
    }

    @Test
    public void testValidate() {
        validator.validate(userDto, errors);
        assertFalse(errors.hasErrors());
    }

}

But when i run my test i get following Failet trace:

java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertFalse(Assert.java:64)
at org.junit.Assert.assertFalse(Assert.java:74)
at pl.piotr.ibank.validator.AddClientAccValidatorTest.testValidate(AddClientAccValidatorTest.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Why I get this error? I think cause this error is this line, but I'm not sure:

errors = new BeanPropertyBindingResult(userDto, "userDto");

And my second problem is that I can't declare multiple RunWith annotation. When I add:

@RunWith(MockitoJUnitRunner.class)

I can't parametrized my test using @RunWith(Parameterized.class)

How to solve it?

Anyone can help me? Maybe my approach is bad? What is best way to test Spring Validator with Junit?

samedi 26 septembre 2015

laravel 5 codeceoption - Couldn't click Link or Button by name or CSS or XPath

I wrote a simple test in codeception and laravel 5,every time I run it with specify name like:

vendor/bin/codecept run functional SignUpCept

it works right but without SignUpCept it doesn't work. here is my code:

$I = new FunctionalTester($scenario);
$I->am('a guest');
$I->wantTo('Sign up for a larabook account');
$I->amOnPage('/');
$I->click('Sign Up!');

and this is a link in my view:

<a href="http://ift.tt/1iBXaP2?" class="btn btn-lg btn-primary">Sign Up!</a>

and the error message is:

Couldn't click "Sign Up!":
Link or Button by name or CSS or XPath 'Sign Up!' was not found on page.

Scenario Steps:
3. I click "Sign Up!"
2. I am on page "/"
1. As a a guest

How can my game be improved?

I am a startup programmer, and I just launched my secound game. Im not sure if the game is good, so I need some third party perspectives. The game is called World Domination and the link is http://ift.tt/1gY5pUC
I do not care if the feedback is good or bad. Either way I get what I need to improve my game.

Spring context compile time validation

Is there any tool or maven plugin that can validate Spring context during compile time or maven build execution?

I understand that it's not trivial to check the full correctness of the context without the app start, but it will be good to check some trivial cases, for example if you define a bean in xml context then the bean class have to be present in classpath.

How to prevent Model events from firing using phpunit?

I want to prevent Model events such as 'created'. 'updated' etc when testing my application using phpunit.

In the documentation of Laravel it says that you can prevent events from firing by using

$this->expectsEvents(App\Events\UserRegistered::class);

But in my situation I have no class to expect.

I know that I can use $this->withoutEvents(); to prevent all events, but how can I prevent only specific model events?

JMeter: How to know why my regular expression extractor in JMeter is not extracting the data

I would like to know why regular expression extractor in JMeter is not extracting the data after parameterization. Below is the screenshot for the same:

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Verification the sum of 2 numbers

I want to write the test for a verilog program. The program is calculate the sum of a+b and return c. ( a and b are 2 binary numbers with n digits)

The test should understand if the calculation of a+b is true. It should do this verification in O(1).

How can I write the test? the order of that is important here.

How to test with Espresso if UI field or control is disabled?

I can test if some element is enabled:

onView(withId(R.id.my_element)).check(matches(isEnabled()));

But can not find how to do it if I want to check if a control is disabled?

Testing the usability (one-page website)

I need your help!

What is my first step if I would like to test the usability of my one-page website (with the pushState function)?

vendredi 25 septembre 2015

JMeter: "__VIEWSTATE" and "__EVENTVALIDATION" value does not get replaced after extracting values using Regular Expression Extractor Post Processor

I am trying to load test the ASP.net website and after a bit of research, it became apparent that JMeter was running into issues with VIEWSTATE, which is one of the workarounds ASP.NET WebForms uses to make HTTP appear to be stateful. JMeter is sending a stale value for VIEWSTATE since it is replaying the HTTP requests in the test plan. I extracted the VIEWSTATE from each response and re-include that value on requests. I did it with two Regular Expression Extractors as shown in image but I still don't see values getting replaced after parameterization.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

How can you see the XCUIElement tree?

Background:

I'm experimenting with ui level testing in iOS 9.0 with XCode GM.

Question:

Is there a command in XCode GM that will allow you to see a 'tree' of accessible elements and their relationships? Something similar to the 'page' command in Appium?

Ideally I would be able to run a command in the debugger that would give me a list of elements available for selection/manipulation. Currently you can use debugDescription on a single XCUIElement but that only gives you info for that element.

Minitest doesn't respect setting config.active_record.pluralize_table_names to false

I've been trying to set up my first tests on Rails 4.2.4 but usually I use singularized table names in DBs, thus I add this line into config/application.rb

config.active_record.pluralize_table_names = false

Since I've being working on Car and User models, let's assume I've already generated each scaffold, and already executed rake db:test:prepare so the problem begins with tests as follows:

In test/models/car_test.rb or user_test.rb, first I uncomment stub test "the truth" and run vanilla with the following error with rake test:models

# Running:

EE

Finished in 0.019095s, 104.7396 runs/s, 0.0000 assertions/s.

  1) Error:
UserTest#test_the_truth:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: users: DELETE FROM "users"



  2) Error:
CarTest#test_necessary_car_data:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: users: DELETE FROM "users"


2 runs, 0 assertions, 0 failures, 2 errors, 0 skips

When I run rake test:controllers the same ActiveRecord error shows up multiple times and I cannot fix this behaviour in any way so far.

Somebody else has come across with this issue? It's driving me mad...

PS: All development does well without any issues with singular table names, the only mess lies in testing.

How to test service object methods are called?

I'm quite new to RSpec and trying to build some tests for my service objects.

My service file is as follows...

  class FoursquareService

  def initialize(address)
    @coordinates = coordinates(address)
    @category_id = "4bf58dd8d48988d1e0931735"
    @api_version = "20150922"
    @radius = 1000
  end

  def popular_shops
    return unless @coordinates
    response = foursquare_client.explore_venues(search_options)
    venues = response.groups.find { |k,v| k["type"] == "Recommended Places" }.items.map(&:venue)
    venues.sort_by! { |venue| venue.rating.to_f }.reverse!
    venues
  end

  private

  def search_options
    search_options = {
      :ll         => @coordinates,
      :categoryId => @category_id,
      :radius     => @radius
    }
  end

  def coordinates(address)
    Geocoder.coordinates(address).try(:join, ", ")
  end

  def foursquare_client
    Foursquare2::Client.new(
        :client_id      => ENV["FOURSQUARE_ID"],
        :client_secret  => ENV["FOURSQUARE_SECRET"],
        :api_version    => @api_version)
  end

end

I want to test that the private methods are called by the public methods. This is my code...

subject { FoursquareService.new("London") }

it "receives coordinates" do
  expect(subject).to receive(:coordinates)
  subject
end

it "receives search_options" do
  expect(subject).to receive(:search_options)
  subject.popular_shops
end

But I get this error...

expected: 1 time with any arguments
received: 0 times with any arguments

What am I doing wrong here?

Testing the Execution order of handlers injected by Spring Framework

I'm using Spring Framework to inject several dependency into my code, and one of the beans look like this

<bean id="handlerChain" class="com.abc.ChainHelper">
    <property name="handlers">
        <list>
            <bean class="com.abc.AuthenticationHandler" />
            <bean class="com.abc.Handler1" />
            <ref bean="Handler2" />
        </list>
    </property>
</bean>

ChainHelper takes the list of handlers and executes the process for every handler in the order given. I have a unit test in ChainHelper to ensure that ChainHelper processes every handler in the order given. However, in the current project I'm working on, Handler1 should only be processed when AuthenticationHandler finishes authenticating a job.

AuthenticationHandler look something like this

public class AuthenticationHandler extends AbstractHandler {
    //variable declarations and constructor

    @Override
    public void process(Job job) throws Throwable {
        //some code to verify the identity of the job
        job.isVerified = verificationResult;
    }

    //some helper methods
}

and Handler1 look something like this

public class Handler1 extends AbstractHandler {
    //variable declarations and constructor

    @Override
    public void process(Job job) throws Throwable {
        if (job.isVerified) {
            //do verified job stuff
        } else {
            //do unverified job stuff
        }
    }

    //some helper methods
}

So I want to write a test to enforce that no one accidentally change the order in the list and break everything.

This seems too big for a unit test, since I'm testing the order of execution of multiple handlers and not an individual piece of code. However, I don't feel like it is big enough for a integration test. The reason is that the way I understood integration test is that it tests a specific request with valid and invalid input, and make sure we are getting the correct result based on the input, and this dependency is injected on every types of request, so it doesn't quite fit the integration tests.

So my question is how should I go about testing the execution order of this particular injection?

How to put PayPal Test Button on a site?

I'm trying to follow these instructions. I log in to developer.paypal.com, then to http://ift.tt/U9tsBr with a Business account from developer.paypal.com's Sandbox Test Accounts page. Go to Merchant Services, click "My saved buttons". Domain changes to www.paypal.com (is it as it should be?). I choose Buy Now button, specify item name and price, and click Create Button. Remove code protection, copy the code, paste it to a site. Open the page, click Buy Now button, which gets me to www.paypal.com, specify Personal account's credentials from developer.paypal.com's Sandbox Test Accounts page. Click Log In, but it says:

Please check your email address and password and try again

Please make sure you have entered your email address correctly.

Please re-enter your PayPal password.

And yep, I checked if I can log in with those credentials to http://ift.tt/U9tsBr. What am I doing wrong?

I get an error when trying to run a testsuite

This is my test case class:

require "test/unit"

class TestMemberSignin < Test::Unit::TestCase 

def setup()
    @browser1 = startNewBrowser
end


def test_memberSigninPositive()
    assert_equal(true, true)
end


def teardown()
        closeBrowser(@browser1)
end
end

This is my test suite class:

require 'test/unit/testsuite'
require 'test/unit'
require 'test/unit/ui/console/testrunner'

 class TS_MyTests 

def self.suite
    suite = Test::Unit::TestSuite.new
    suite << (TestMemberSignin)
    suite
 end
end

Test::Unit::UI::Console::TestRunner.run(TS_MyTests)

I get this error when I run it:

TS_MyTests.rb:14:in `suite': uninitialized constant TS_MyTests::TestMemberSignin (NameError)
    from /clientdata/apps/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/test-unit-3.1.3/lib/test/unit/ui/testrunner.rb:12:in `initialize'
    from /clientdata/apps/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/test-unit-3.1.3/lib/test/unit/ui/console/testrunner.rb:38:in `initialize'
    from /clientdata/apps/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/test-unit-3.1.3/lib/test/unit/ui/testrunnerutilities.rb:24:in `new'
    from /clientdata/apps/ruby-1.9.3/lib/ruby/gems/1.9.1/gems/test-unit-3.1.3/lib/test/unit/ui/testrunnerutilities.rb:24:in `run'
    from TS_MyTests.rb:22:in `<main>'

Can you please direct me to a solution?

Simulate traffic over virtual com port

I'm having a project with Arduino(s) and I would like to build a testing environment so I will be able to do end-to-end integration before testing on the real stuff.

I have a C# program that controls the actions sent to an Arduino, using serial port. The Arduino do some calculations and send back the results back to the C# controller.

I do not want to change the C# program. I do have to implement a program that runs the arudino code and transmit it to a virtual com port I've already created, so the C# program could read it.

Can you please give me some guidance how to write to the virtual com port ? The Arduino is written in C++, so I guess the solution should be implemented in C++ also.

I noticed to the existance of the tcomport, but it's written in Delphi, so I can't see how I can use it with the C++ code.

Thanks

Test my program in different windows versions

Before go to production, I have to test a windows application in several windows versions (from 7 to 10, 32 and 64 bits), what supposes download the ISOs (luckily we have licenses), create the virtual machines and install all the versions one by one. Is there any faster way to do it? Like a cloud solution as an example.

grailsApplication not available in Domain class when running all Integration tests

I'm running in to a problem when running Integration tests in Grails. One of the Domain classes in the project has a method that accesses the grailsApplication.config property. We have an integration test for one of our services that calls this method in the Domain class. When the test is run on its own using the command

grails test-app integtration: com.project.MyTestSpec

the test runs fine and the domain class can access grailsApplication. However when the whole test suite is ran using

grails test-app integration

then the test fails with the error

java.lang.NullPointerException: Cannot get property 'config' on null object

when trying to access grailsApplication.config. It seems that when the tests are all run together grailsApplication is not being injected in to the Domain class. Has anyone come across this issue before?

From what I have read it seems to be a test pollution issue but as there is no setup happening in each integration test the problem is hard to track down.

Is there a easy way to test Hessian service?

Is there any easy way to test Hessian service?

For example, if we write a web service, we can publish it and use http client to test it.

So is there any similar way to do that?

JMeter: java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "Õ­"

I am getting the following exception for a login page in Response Code:

java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "Õ­"
        at java.net.URLDecoder.decode(Unknown Source)
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sendPostData(HTTPHC4Impl.java:1151)
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.handleMethod(HTTPHC4Impl.java:453)
        at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:329)
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
        at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
        at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:434)
        at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:261)
        at java.lang.Thread.run(Unknown Source)

protractor browser error log not complete

I want to make sure my angular application does not log any errors in the console when loading the page where the application is located.

For that I use protractor and so far I have the following test:

spec.js:

describe('Protractor Demo App', function () {


    it('should show all logs', function () {

        browser.get('http://localhost:9050/#/10');

        browser.sleep(20000)

        browser.manage().logs().get('browser').then(function (browserLogs) {

            console.log(browserLogs)

            browserLogs.forEach(function (log) {
                console.log("-------------------");
                console.log(log.message);
                if (log.level.value > 900) {
                    throw log.message;
                }
            });
        });


    });
});

when I look at the terminal output I get only the first element of the logs. However if I open the console in chrome and look at the logs myself there are more error and warning logs but they are not part of the terminal output. How is this possible, what did I miss ?

Clover does not detect any tests at all

I'm using Clover in a project, to help get test coverage over 7%. I separated and renamed unit tests and integration tests into *Test.java and *IT.java, and added Surefire to reduce build times. All tests run fine.

Now suddenly Clover says test coverage is 0%.

What can be the reason for this, and how do I fix it?

Rational Test Workbench if condition

I am trying to do mobile testing with IBM Rational Test Workbench. And the problem is, that when I open the app, it opens different pages every time (its a part of a normal workflow). I recorded all the steps that might occur, but I can't find out how to invoke them differently depending on verification point (something like if/else block).

For Example: if mainpage opens proceed with steps 2 and 3 and if page2 opens proceed with steps 4 and 5.

rails rspec capybara testing ActiveRecord::RecordInvalid:

Hello every one im getting a error that i don't know how to fix and im not sure why is it even popping up

require 'spec_helper'

feature "Profile page" do
    scenario "viewing" do
        user = FactoryGirl.create(:user)

        visit user_path(user)

        expect(page).to have_content(user.name)
        expect(page).to have_content(user.email)
    end
end

feature "Editing Users" do
    scenario "Updating a project" do
        user = FactoryGirl.create(:user)

        visit user_path(user)
        click_link "Edit Profile"

        fill_in "Username", with: "new_username"
        click_button "Update Profile"

        expect(page).to have_content("Profile has been updated.")
    end
end

user/views/_form.html.erb

<%= form_for @user do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
    <h2><%= pluralize(@user.errors.count, 'error') %>
        prohibited this user from being saved:</h2>

        <ul>
            <% @ticket.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
    <% end %>

    <p>
        <%= f.label :name, "Username" %><br />
        <%= f.text_field :name %>
    </p>
    <p>
        <%= f.label :email %><br />
        <%= f.text_field :email %>
    </p>
    <p>
        <%= f.label :password, "Password" %><br />
        <%= f.text_field :password %>
    </p>
    <p>
        <%= f.label :password_confirmation %><br />
        <%= f.text_field :password_confirmation %>
    </p>
    <% if @user.new_record? %>
    <%= f.submit 'Sign up' %>
    <% else %>
    <%= f.submit "Update Profile" %>
    <% end %>

user.rb

class User < ActiveRecord::Base
    has_secure_password
end

and the error is following

1) Profile page viewing
     Failure/Error: user = FactoryGirl.create(:user)
     ArgumentError:
       Factory not registered: user
     # ./spec/features/user_profile_spec.rb:5:in `block (2 levels) in <top (required)>'

  2) Editing Users Updating a project
     Failure/Error: user = FactoryGirl.create(:user)
     ArgumentError:
       Factory not registered: user
     # ./spec/features/user_profile_spec.rb:16:in `block (2 levels) in <top (required)>'

some random text so that i can post this question to the stackoverflow forum QA editing lalalalal.

jeudi 24 septembre 2015

Best monitoring freeware [on hold]

I wonder if anyone can recommend a good tool for monitoring e.e memory and cpu utilization. The purpose is to keep track on how the computer reacts while we are running a load test. Best Regards and thanks for your help

OS: Windows

What are the factors that affect the response time of a webpage?

I'm working on some performance tests on web pages, and for me it is still unclear which factors interfere in the page response time. What makes a Web page to respond faster or slower a request from a client?

How would i unit test this class?

A bank account has a balance that can be changed by deposits and withdrawals.

Constructs a bank account with a zero balance.

Constructs a bank account with a given balance. @param initialBalance the initial balance

Deposits money into the bank account. @param amount the amount to deposit

Withdraws money from the bank account. @param amount the amount to withdraw

Gets the current balance of the bank account. @return the current balance

 public class BankAccount
        {
           private double balance;

           public BankAccount()
           {
              balance = 0;
           }

           public BankAccount(double initialBalance)
           {
              balance = initialBalance;
           }

           public void deposit(double amount)
           {
              balance = balance + amount;
           }

           public void withdraw(double amount)
           {
              balance = balance - amount;
           }

           public double getBalance()
           {
              return balance;
           }
        }

pytest: How to pass in values and create a test fixture from command line?

I have a simple test as shown below:

# contents of test_example
def test_addition(numbers):

    assert numbers < 5

And below is my conftest

# contents of conftest
import pytest

@pytest.fixture(params=[1, 2, 3, 4])
def numbers(request):
    return request.param

However now I want to test the numbers 5 and 6but not have to explicitly hardcode that. On command line, I would like to override the numbers test fixture with the numbers 5 and 6 such that:

py.test test_example.py --numbers=[5, 6]

I would expect the result of the above invocation to overwrite the conftest numbers test fixture with my test fixture created at command line and run test_addition() on 5 and 6 only.

How would I go about doing this?

usine jasmine testing on a chromebook offline

has anyone figured out how to use jasmine testing on a chromebook?

i've come across this:

http://ift.tt/1VbyzCk

which i'm not sure if it does or not. thanks!

Use Appium without starting application

I am testing an Android app with Appium but I need a way to test the application without Appium automatically trying to install and run the app. Is there a way for me to tell Appium that the app is already open?

Test controller with service injection

I am currently testing my AngularJS application and I am struggling with the tests of the controllers injecting a service.

Here is my controller:

.controller('UserCtrl', ['$scope', '$routeParams', 'User', function ($scope, $routeParams, User) {

    $scope.hello = "lol";

    $scope.userId = $routeParams.id;
    var user = new User($scope.userId);

    $scope.load = function(){
        user.load().then(
            function(user){
                $scope.name     = user.name;
            },
            function() {
                $scope.dataFail = 'error error' ;
            }
        );
    };

    $scope.load();
}]);

Here is my User service (that i want to inject in my controller's test)

.factory('user', ['$http', '$q', function ($http, $q) {

var User = function (id) {
    this.id = id;
    this.name = null;
};

User.prototype.load = function () {
    var deferred = $q.defer();

    $http.post('/user/' + this.id + '/load')
        .success(function(data) {
            var user = new User(data.id);
            user.name = data.name
            deferred.resolve(user);
        })
        .error(function(err, code) {
            deferred.reject(err);
        $log.error(err, code);
    });
    return deferred.promise;
};

return User;

And finally is my test :

describe('Controller: UserCtrl', function () {

var $controller, $scope, User;

beforeEach(module('octosendApp', function($provide){
    User = jasmine.createSpyObj('User', ['load']);

    User.load.and.returnValue({
        name: 'testName'
    });
    $provide.value('User', User);
}));

beforeEach(inject(function(_$controller_, $rootScope, _User_){
    $scope = $rootScope.$new();
    User = _User_;

    $controller = _$controller_('UserCtrl', {
        $scope: $scope,
        User : User,
        $routeParams: {id: 2}
    });
}));

it('should have a hello property', function() {
    expect($scope.hello).toBeDefined();
});

});

I get the following error :

TypeError: '[object Object]' is not a constructor (evaluating 'new User($scope.userId)')

I guess the problem is because my factory is object oriented and i can not use the constructor. i followed this tutoarial : http://ift.tt/1iOgyZQ and did the exact same, the only difference is the structure of the factory, which I do NOT want to change.

Thank you for your help.

Should model classes be tested?

Should model classes be tested?

Model classes does not contain logic, but usually contains some logic in the constructor for initialization.

These class are also shared, therefore it a very important that these class initializes correctly.

What is the standard for testing, should model classes be tested? Or the class that make use of them have responsibility to test them?

Check if file was created and deleted?

I need to test a program that creates temporary file. When run finishes it deletes the file. How can I check it file has be created and deleted.

I am thinking about sending some signals to process (like Ctrl-Z) to suspend it and check but should be simpler ways.

I am using bash in Linux.

play framework share testing code between subprojects

i have a play project with multiple subprojects. It is possible to share classes from the app folder between subprojects which depends on each other.

I have a class with methods which should be executed before every test. I need this class for nearly every test class and it isn't practicable to have this class in every test folder for each subproject. Is it generally possible to share classes in the test folder?

I have tested this but it doesn't seem to work. IntelliJ doesn't show any error and it seems to recognize the class i want to use. But when i execute the tests, it shows me that it can't find the class.

Thanks in advance for your responses.

Spring integration test with mockmvc throws org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

I have a weird problem with a spring integrationtest. I have a working controller and application that runs on tomcat. However in my integration test I get the following stacktrace:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:651)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:610)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:173)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:442)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:430)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:156)
at com.test......
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:85)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:241)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

My test looks like this:

@Category(DbIntegrationTest.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfig.class})
@WebAppConfiguration
@ActiveProfiles({"dev", "fk_mock"})
public class WhenUserSubmitsNew  {

@Autowired private WebApplicationContext context;
protected MockMvc mvc;

@Before
public void setup() {
    buildMockMVC();
    createBasicUserSetup();
}

public void buildMockMVC() {

    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            //.apply(springSecurity())
            .build();
}

public void createBasicUserSetup() {
    ...
}


@Test
public void shouldCreate() throws Exception {
    String date1 = "2015-05-05";
    String date2 = "2015-07-30";

    String json = "{\"ids\": [5, 6]}";

    String url = "/submitNew";
    mvc.perform(post(url)
            .with(user(user.getUserName()))
            .sessionAttr(AbstractController.USER_SESSION_ATTR, user)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .content(json))
        .andExpect(status().isCreated());
}
} 

And my controller method:

    @RequestMapping(value="/submitNew", method=RequestMethod.POST)
public @ResponseBody Long create(HttpSession session, @RequestBody CustomForm form) {
    ...
}

my gradle.build

apply plugin: 'war'
apply plugin: 'eclipse-wtp'
group = '...'
version = '1.0'
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext {
   springVersion = '4.2.0.RELEASE'
   springSecurityVersion = '4.0.2.RELEASE'
   springWSVersion = '2.2.2.RELEASE'
   aspectjVersion = '1.6.9'
   slf4jVersion = '1.7.5'
   tilesVersion = '3.0.5'
   jsonPathVersion = '0.8.1'
   servletApiVersion = '3.0.1'
   jacksonDatabindVersion = '2.6.1'
   h2Version = '1.3.156'
   postgresqlVersion = '9.3-1100-jdbc4'
   hibEntitymanagerVersion = '4.3.8.Final'
   //hibValidatorVersion = '4.1.0.Final'
   javaxInjectVersion = '1'
   dbcpVersion = '1.4'
   hamcrestVersion = '1.3'
   junitVersion = '4.11'
   mockitoCoreVersion = '1.9.5'
   jstlVersion = '1.2'
   slf4jAPI     = "org.slf4j:slf4j-api:${slf4jVersion}"
   slf4jJCL     = "org.slf4j:jcl-over-slf4j:${slf4jVersion}"
   slf4jLog4J   = "org.slf4j:slf4j-log4j12:${slf4jVersion}"
   log4JVersion = '1.2.16'
   log4J        = "log4j:log4j:${log4JVersion}"
}
repositories {
   mavenCentral()
}
dependencies {
    providedCompile "javax.servlet:javax.servlet-api:${servletApiVersion}"  
    //finns i båda build
     compile ("org.springframework:spring-webmvc:${springVersion}") {
        exclude group: 'commons-logging', module: 'commons-logging'
   }
   compile "org.springframework:spring-webmvc:${springVersion}"
   compile "org.springframework:spring-orm:${springVersion}"
   compile "org.springframework.security:spring-security-web:${springSecurityVersion}"
   compile "org.springframework.security:spring-security-config:${springSecurityVersion}"
   compile "org.springframework.ws:spring-ws-core:${springWSVersion}"
   compile "org.springframework.security:spring-security-crypto:${springSecurityVersion}"
//   compile 'org.springframework.data:spring-data-jpa:1.9.0.RELEASE'
   compile "com.fasterxml.jackson.core:jackson-databind:${jacksonDatabindVersion}"
   //compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.1"
   //compile "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.6.1"
   compile "org.apache.tiles:tiles-extras:${tilesVersion}"
   compile "org.apache.tiles:tiles-jsp:${tilesVersion}"
   compile "com.h2database:h2:${h2Version}"
   compile "org.postgresql:postgresql:${postgresqlVersion}"
   compile "org.hibernate:hibernate-entitymanager:${hibEntitymanagerVersion}"
//   compile "org.hibernate:hibernate-validator:${hibValidatorVersion}"
   compile "javax.inject:javax.inject:${javaxInjectVersion}"
   compile "commons-dbcp:commons-dbcp:${dbcpVersion}"
   testCompile "org.hamcrest:hamcrest-all:${hamcrestVersion}"
   testCompile "junit:junit:${junitVersion}"
   testCompile "org.springframework:spring-test:${springVersion}"
   testCompile "org.mockito:mockito-core:${mockitoCoreVersion}"
   testCompile "com.jayway.jsonpath:json-path:${jsonPathVersion}"
   testCompile "com.jayway.jsonpath:json-path-assert:${jsonPathVersion}"
   testCompile "org.springframework.security:spring-security-test:${springSecurityVersion}"
   runtime "javax.servlet:jstl:${jstlVersion}"
      // Logging:
   compile(slf4jAPI)
   runtime(
       slf4jJCL, slf4jLog4J
   )
   runtime(log4J) {
        exclude group: 'javax.mail',   module: 'mail'
        exclude group: 'javax.jms',    module: 'jms'
        exclude group: 'com.sun.jdmk', module: 'jmxtools'
        exclude group: 'com.sun.jmx',  module: 'jmxri'
   }
}

To make things more interesting I also have a unit test for the controller that works which uses standalone setup:

mockMvc = standaloneSetup(controller)
            .setMessageConverters(new MappingJackson2HttpMessageConverter())
            .build();

If anyone has any suggestions on how to move forward it would be extremely appreciated!!

Thanks Karl