samedi 31 octobre 2015

Runs test function of RNG quality

I wrote the function that uses the runs test to access the quality of RNG. Is there a way to write it without "if" and "for"?

u=runif(10,0,1)
runs.test=function(u){
x=(u<0.5)
x=as.numeric(x)
count=1;
for (i in 1:(length(x)-1)){
  if (x[i]==x[i+1]){
    count=count;
  }else{
    count=count+1;
  }
  }
  return(count);
}

Clojure - tests with components strategy

I am implementing an app using Stuart Sierra component. As he states in the README :

Having a coherent way to set up and tear down all the state associated with an application enables rapid development cycles without restarting the JVM. It can also make unit tests faster and more independent, since the cost of creating and starting a system is low enough that every test can create a new instance of the system.

What would be the preferred strategy here ? Something similar to JUnit oneTimeSetUp / oneTimeTearDown , or really between each test (similar to setUp / tearDown) ?

And if between each test, is there a simple way to start/stop a system for all tests (before and after) without repeating the code every time ?

Note : I am talking about unit-testing here.

Automatic testing of examples in documentation

In the end of the SageMath manual they explain why they chose to implement SageMath in Python. One of the items says: "Excellent support for documentation of functions and packages in the source code, including automatic extraction of documentation and automatic testing of all examples. The examples are automatically tested regularly and guaranteed to work as indicated."

This sounds neat, but I haven't found the way to do it. How can I automatically test all the examples that appear in the documentation to my functions?

Yii2 testing environment guidelines for extension development

I am developing an Yii 2 public (MIT) extension to change some of the yii\web\View behaviours (minify, combine and many other optimizations).

I can do it easily. But I really want to write as many tests (codeception) as possible for it. This is where I am very confused.

I already have some unit tests (for example: testing a specific minifing, or returning combined minified result). But I would like to test the entire result and the final integration between my extension and the Yii2 web application using it.

I just would like some guidelines for this process:

  1. Should I have a real (complete) app inside my extension for testing purposes? If so, should it be 'installed' inside tests dir?

  2. Would you use functional testing ? (I think so because the View will find files in AssetBundles, combine and minify them, publish the result as a single file and replace the assets' urls by new url (i.e., the optimized asset url) inside the view;

  3. Could you provide some very basic examples/guidelines?

I just would like to highlight that I dont intend you do my testing job, I really want to learn how to do it. This is why I really would be very grateful for any tips.

Thank you so much.

Strange activity with Ruby on Rails

I have created a small app with Ruby on Rails, and testing the app output three errors. However, these errors seem irregular. For instance, each of the errors asks me to insert a parenthesis where one is not needed in the line of the source code file at all. This is the set of errors:

         1) Error:
 StaticPagesControllerTest#test_should_get_about:
 SyntaxError: C:/Sites/sample_app/app/views/static_pages/about.html.erb:1:      syntax error, unexpected ',', expecting ')'
 ...putBuffer.new; provide (:title, "About")
 ...                               ^
 C:/Sites/sample_app/app/views/static_pages/about.html.erb:1: syntax error,    unexpected ')', expecting keyword_end
 ....new; provide (:title, "About")
 ...                               ^
 test/controllers/static_pages_controller_test.rb:17:in `block in   <class:StaticPagesControllerTest>'


         2) Error:
 StaticPagesControllerTest#test_should_get_help:
 SyntaxError: C:/Sites/sample_app/app/views/static_pages/help.html.erb:1:    syntax error, unexpected ',', expecting ')'
 ...putBuffer.new; provide (:title, "Help")
 ...                               ^
 C:/Sites/sample_app/app/views/static_pages/help.html.erb:1: syntax error,   unexpected ')', expecting keyword_end
 ...r.new; provide (:title, "Help")
 ...                               ^
 test/controllers/static_pages_controller_test.rb:11:in `block in <class:StaticPagesControllerTest>'


         3) Error:
 StaticPagesControllerTest#test_should_get_home:
 SyntaxError: C:/Sites/sample_app/app/views/static_pages/home.html.erb:1:   syntax error, unexpected ',', expecting ')'
 ...putBuffer.new; provide (:title, "Home")
 ...                               ^
 C:/Sites/sample_app/app/views/static_pages/home.html.erb:1: syntax error,    unexpected ')', expecting keyword_end
 ...r.new; provide (:title, "Home")
 ...                               ^
 test/controllers/static_pages_controller_test.rb:5:in `block in   <class:StaticPagesControllerTest>'

How can I correct this in the program, if it is needed? Is it even something on my side of the program?

Test private members of a object in scala

Here is the object:

package object beautifier {
  private val scientificPattern = """([+-]?\d+(\.\d+)?)([Ee]([+-]?\d+))?""".r
}

And the test:

import org.scalatest._ import vu.co.kaiyin.formatting.scientificNotaion.beautifier.scientificPattern

class ScientificNotationSpec extends FlatSpec with Matchers {
  "Regex" should "return correct matches" in {
    "-4.2e-3" match {
      case scientificPattern(coef, _, _, exponent) => {
        coef should be (-4.2)
        exponent should be (-3)
      }
    }
  }
}

And I got an error of course:

Error:(2, 8) object scientificPattern is not a member of package vu.co.kaiyin.formatting.scientificNotaion.beautifier
import vu.co.kaiyin.formatting.scientificNotaion.beautifier.scientificPattern
       ^

How do I solve this problem?

Rails and rspec. uninitialized constant Errors

I have a rails App. I have this file app/errors/status.rb

I try to pass the test but is not not working.

module Errors 
  class Status
    def initialize status
      @status = status
    end

    def default_message
      "Error in the server status: #{status}"
    end

    private

    attr_reader :status
  end
end

And the test on spec/errors/status_spec.rb:

require 'rails_helper'

describe Errors::Status do
  let(:status) { double 'status' }

  subject { described_class.new status }

  describe 'default_message' do
    it 'returns the default message' do
      expect(subject.call).to eq( "Error in the server status: #{status}")
    end
  end
end

And it keeps throwing this error:

/Users/gerardmorera/bet_play/spec/errors/status_spec.rb:3:in `<top (required)>': uninitialized constant Errors (NameError)
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `load'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `block in load_spec_files'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `each'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `load_spec_files'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:102:in `setup'
    from /Users/gerardmorera/.rvm/rubies/ruby-2.2.0/lib/ruby/gems/2.2.0/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:88:in `run'

How to deploy a test database for DBIx Class

I have Mojolicious app with a test suite using Test::Class::Moose. Using DBIx::Class to interact with my database, is there a way to setup an in-memory database that I can add fixture data to?

I'd like to use an in memory database because it'll mean that the application will have less setup configuration. I do know how to setup an actual SQLite database for testing but managing that for testing along with a mySQL database for production doesn't sound like easy management (eg "oh no, forgot to rebuild the testing database").

Loading data from fixtures seems ideal, that way you have more control over what is actually in the database. Example, you find a bug with a row that contains certain data, add a row like that to your fixture file and test until successful.

Now how to actually set up an in-memory database using DBIx? :)

Right now this is how I'm building the schema for my Test::Class::Moose suite:

has cats => (
    is => 'ro',
    isa => 'Test::Mojo::Cats',
    default => sub { return Test::Mojo::Cats->new(); }
);

has schema => (
    is => 'ro',
    lazy => 1,
    builder => '_build_schema_and_populate',
);

sub _build_schema_and_populate {
    my $test = shift;
    my $config = $test->cats->app->config();
    my $schema = Cat::Database::Schema->connect(
        $config->{db_dsn},
        $config->{db_user},
        $config->{db_pass},
        {
            HandleError => DBIx::Error->HandleError,
            unsafe => 1
        }
    );

    require DBIx::Class::DeploymentHandler;
    my $dh = DBIx::Class::DeploymentHandler->new({
        schema  => $schema,
        sql_translator_args => { add_drop_table => 0 },
        schema_version => 3,
    });
    $dh->prepare_install;
    $dh->install;

    my $json = read_file $config->{fixture_file};
    my $fixtures = JSON::decode_json($json);

    $schema->resultset($_)->populate($fixtures->{$_}) for keys %{$fixtures};

    return $schema;
}

Where my config specifies dbi:SQLite:dbname=:memory: as the database dsn.

When running the test suite, the tables don't seem to be loaded, as I get errors stating the table does not exist, eg Can't locate object method "id" via package "no such table: cats"

Is there some extra setup that I'm not doing when wanting to deploy to an in-memory database?

Thanks

How can i use variables and methos defined in BeforeMethod annotation

i have defined which webdriver to open (firefox/chrome/IE) and that method is driver() which i have in BeforeMethod annotation, which is creating drive object . Now i want to use same WebDriver object in my afterMethod and test annotation. How can i achieve this ?

@Test
 public void f() throws IOException {
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.navigate().refresh();
  LoginPage.link_Guest(driver).click();
    try{
        Assert.assertTrue(driver.findElement(By.xpath(".//* [@id='main-menu-    ist']")).isDisplayed());
    }catch (Exception e){
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("C:\\User\\src\\ScreenShots\\TC_GS_01_GuestHomePage.png"));
    }
}
@BeforeMethod
public void beforeMethod() throws IOException {
    DOMConfigurator.configure("log4j.xml");

    Properties prop = new Properties();
    FileInputStream fis = new FileInputStream("C:\\Users\\src\\constants\\dataFile.properties");
    prop.load(fis);


    Reporter.log("Browser has been initiated");
    WebDriver driver = Constants.driver();
    driver.get(prop.getProperty("testUrl"));
  }

  @AfterMethod
   public void afterMethod() {
  driver.quit();
 }

'Undefined' result in Javascript testing

I am creating a Kata on Codewars. Its objective is to make a Player with certain attributes and values. This is the complete working solution,

function Player(name, position, age, dribbling, pass, shoot) {
 this.name = name;
 this.position = position;
 this.age = age;
 this.dribbling = dribbling;
 this.pass = pass;
 this.shoot = shoot;
} 

var myPlayer = new Player('Player', 'Right Winger', 25, 75, 90, 65);

And this is the Test Cases I have to provide to validate the complete working solution in order to publish the Kata,

describe('Player class', function () {
  it('should create a Player', function (){
    var myPlayer = new Player()
      Test.assertEquals(myPlayer.name, 'Player')
      Test.assertEquals(myPlayer.position, 'Right Winger')
      Test.assertEquals(myPlayer.age, 25)
      Test.assertEquals(myPlayer.dribbling, 75)
      Test.assertEquals(myPlayer.pass, 90)
      Test.assertEquals(myPlayer.shoot, 65)
    })
})`

And this is the result I get when I run the 'Validate Solution' button,

Player class
should create a Player
Expected: Player, instead got: undefined
Expected: Right Winger, instead got: undefined
Expected: 25, instead got: undefined
Expected: 75, instead got: undefined
Expected: 90, instead got: undefined
Expected: 65, instead got: undefined

0 Passed
6 Failed
0 Errors

What am I doing wrong?

vendredi 30 octobre 2015

How can I use strings to describe test cases in Java?

With JUnit, the description of my test cases would normally in the method name, like:

@Test
public void should_return_6_if_distance_is_2km() {
}

or

@Test
public void shouldReturn6IfDistanceIs2km() {
}

Which is not quite readable.

But with the testing frameworks of other lanuage, like javascript, or scala, I can use:

describe("Taximeter") {
    it("should return 6 if the distance is 2km") {
        ...
    }
}

which is more readable with plain strings.

Is it possible to do this in Java?

Is there a more efficient way to use assert with arrays in C?

in one part of my program I need to use assert to test multiple arrays (5 sets total), and I was wondering if there's a more efficient way to do that besides what I am doing right now, which is basically just creating a new array every time. FYI I do have assert.h at the beginning of the program.

void UnitTest3D(void){
    double test1[3] = {0,0,0};
    double test2[3] = {5,0,0};
    assert(find3Ddistance(test1,test2) - 5) < 0.001);

    double test3[3] = {-2, -3, 3.4};
    double test4[3] = {-2, -3, -1.6};
    assert(find3Ddistance(test3,test4) - 5) < 0.001);

    double test5[3] = {-2, -3.2, -5};
    double test6[3] = {3, 1.8, 0};
    assert(find3Ddistance(test5,test6) - sqrt(75)) < 0.001);
    return;
    }

Titan storage.backend=inmemory Causes Incompatible Data Type Exception

I've been using titan-cassandra storage.backend=cassandra in my testing environment and recently learned that I can simply plop in storage.backend=inmemory to test with an in-memory graph. As this will drastically increase the speed of the hundreds of tests - this sounds great. But, making this change to my otherwise simple test configuration causes many of my once passing tests to fail. Here's my configuration:

storage.backend=inmemory
storage.hostname=localhost
storage.cassandra.keyspace=test

There are two errors that come up, the vast majority being:

java.lang.IllegalArgumentException: Incompatible data types for: variable

while much less commonly:

com.thinkaurelius.titan.core.TitanException: Could not commit transaction due to exception during persistence

Any idea on how I can resolve these issues?

How to avoid an onPause() with mockito?

I have this method

@Override
protected void onPause() {
    unsuscribeFromMessageDispatcher(RaffleListActivity.this);
    Intent service = new Intent(this, AsyncIntentService.class);
    service.putExtra("TASK", TASKID_GET_RAFFLE_LIST);
    stopService(service);
    super.onPause();
}

And when I make the test, if fails in the super.onPause(); How can I avoid this line with mockito?

Is there a way to get the App selected language or culture when running Xamarin.UITests

We am currently adding localization throughout an app that we are using and have haven't had any big problems with displaying differing UI depending on the culture. When attempting to update the tests I haven't been able to find a way to get the culture of the app/system from within the test (for formatting money to check against selection).

I've tried using CultureInfo.CurrentCulture, Thread.CurrentCulture and the more verbose forms of Thread culture info (both default and UIThread).

Does anyone know of how to do this or if it is even possible?

Find first null value of an Array[Int]

I'm using scala but how test if a value is null or not ? Especially in a Array[Int]

In java it's :

if( tab[i] == null )

On scala, same test , ide says :

comparing values of types Int and Null using `==' will always yield false

Thanks you

Using Protractor in Electron

I am trying to set up unit tests and e2e tests for an application I have running with Electron using Protractor. I've been refering to many different posts (this one did help), but I still get an error I don't understand :

Message:
  Error while waiting for Protractor to sync with the page: "angular could not be found on the window"
Stacktrace:
  undefined

My conf.js file looks like this:

exports.config = {
    directConnect : true,
    seleniumAddress: 'http://localhost:4444/wd/hub',
    baseUrl:"file://home/me/workspace/testing-project/main.js",
    capabilities: {
        browserName: "chrome",
        chromeOptions: {
            binary: "/home/me/.linuxbrew/lib/node_modules/electron-prebuilt/dist/electron",
            args: ["--test-type=webdriver"]
        }
    },
    specs: ['todo-specs.js'],
    onPrepare: function(){
        browser.resetUrl = "file://";
        browser.driver.get("file://");
    }
};

Considering the documentation given on the Protractor website, I am under the impression that I don't need to install anything else (Jasmine for example).
What surprises me is that even though the path to the main.js (that starts the application accordingly to Electron's specifications) is correct, I can't see anything in the Electron window that pops up.
Did any of you encountered this issue? Did you manage to resolve it?

Is the Intern really really able to run on any Selenium service?

I've written some functional tests for the Intern, which supposedly should work on SauceLabs, BrowserStack, TestingBot, or my own Selenium grid.

The same code doesn't seem to work on all services though. I initially got the functional tests working on SauceLabs, so I'm using that service as my "base", so to speak.

On BrowserStack, the tests appeared to fail because the commands were executing too quickly. For example, I am using .pressKeys('TEST\nIN\nPROGRESS\n'), where \n is supposed to execute javascript on the page to turn the previous text into a tag (like the SO tags for this question: [intern] [javascript] [testing]).

That command should result in the following:

[TEST] [IN] [PROGRESS]

but instead results in

[TESTIN] [PROGRESS]

causing my assertions to fail. Changing the pressKeys command to

.pressKeys('TEST\n')
.sleep(500)
.pressKeys('IN\n')
.sleep(500)
.pressKeys('PROGRESS\n')

did not solve the issue. The test would pass / fail inconsistently, with the tags sometimes coming out as [TEST] [IN] [PROGRESS], and sometimes as [TESTIN] [PROGRESS].

Another example is that it wouldn't always wait for the next page to load when I .click() on a link, even with a .sleep() command after.

With regards to TestingBot, the application flat-out failed to upload files, and I could not for the life of me figure out how to enable the file_watcher service required to do so. They have a file upload example here, but I don't know how to configure the Intern to do this for me.

Isn't the Intern supposed to take care of these differences in the cloud providers for the tests?

Is there some standardized way of writing my tests in the Intern so that I can change my cloud testing provider without changing the tests themselves?

How to write a feature test for something that's determined by the user?

Let's say I'm working on a comments functionality that I want to add to the application I'm developing.

I can test it like so with a feature test:

scenario "they can comment on a book" do
  visit book_url(book)

  fill_in "Name", with: "John"
  fill_in "Comment", with: "This is a comment."
  click_button "Add Comment"

  expect(current_path).to eq(book_path(book))
  expect(page).to have_text("Your comment is successfully added")
  expect(page).to have_text(Comment.last.content)
end

But what if I also add a functionality, wherein the user can decide whether or not a comment needs an approval. If it doesn't need an approval, then the above test would work. But if the user changes the settings and decides that a comment needs an approval before being published, this test wouldn't work.

What would be a good way to write a test covering all these scenarios?

testing ejb in spring or guice

There's a legacy ejb application and I wan't to write and test jpa queries and maybe services. The arquillian seems to be a great choice. But it's not working as in tutorial ;) I cannot test my simple ejb bean only because it depends on the other bean and so on and so forth.
To summarize I've to manually prepare ear with all the dependencies taken from pom. I have some problems yet and the deployment takes to long to test ad hoc my persistance layer.

So I've an idea to create new project for test purpose only where I can use spring or guice and test persistance or even service layer. It should be feasible. I think I've to add custom support for @EJB, @Stateless annotations.
- is there a project or extension that support such functionality, in fact running ejb without container ?
- what's di framework is better for this purpose ? I know spring but guice is used in the project
- do you think it make sense ? I'd like to add some integration tests

Distribution generic test function

I try to create a generic test function for distribution error for binomial negative, Poisson and normal. But my function doesn't work and I don't know why, any member can help me? My function is:

require(MASS)

BD<-rpois(1000,10) ### Data set for test

Dist<-c("negative binomial","normal","Poisson")

for(typeD in 1:Dist){
k <- fitdistr(BD,typeD[Dist])
par <- k$estimate
size <- par[1]#Parameter
mu <- par[2]#Mean
SD<-sd(BD)
N <- length(BD)

if (typeD[Dist]=='negative binomial'){       ### For binomial negativa
est <-N*dnbinom(BD,size=size,mu=mu)  ## Estimates
fecdf <- ecdf(BD) ###ecdf- Empiric cumulative function
knotsX <- knots(fecdf)
emp <- fecdf(c(knotsX,Inf))  # Empiric
chisq.test(table(emp),table(est),correct=TRUE) ##Chi test
}
if (typeD[Dist]=='normal'){          ### For normal
est <-N*dnorm(BD,mean=mu, sd=SD)  ## Estimates
fecdf <- ecdf(BD) ###ecdf- Empiric cumulative function
knotsX <- knots(fecdf)
emp <- fecdf(c(knotsX,Inf))  # Empiric
chisq.test(table(emp),table(est),correct=TRUE) ##Chi test

}
 if (typeD[Dist]=='Poisson'){        ### For Poisson
est <-N*dpois(BD,lambda=mu)  ## Estimate
fecdf <- ecdf(BD) ###cdf- Empiric cumulative function
knotsX <- knots(fecdf)
emp <- fecdf(c(knotsX,Inf))  # Empiric
chisq.test(table(emp),table(est),correct=TRUE) ## Chi test
}
}
# 

Thanks,

ASANTOS

Protractor not locating testing spec files?

please see below screenshot - for some reason, protractor is not picking up the spec files specified in the conf.js file. As far as I can tell the path is correct... Any ideas what I'm missing? Thanks.

enter image description here

test spring jpa in gradle

I am moving from maven to gradle. I have some database tests. I can run them in maven but I want run them in gradle. By default these tests fail (BeanCreationException and stuff). I found that in order to run them successfully I have to place such configuration in build.gradle

sourceSets.main.output.classesDir = sourceSets.test.output.classesDir
sourceSets.main.output.resourcesDir = sourceSets.main.output.classesDir
sourceSets.test.output.resourcesDir = sourceSets.test.output.classesDir

My build.gradle contains also dependencies and description. That is all. Pretty simple.

I would like to solve that with proper classpath. However, when I list the content of sourceSets.test.runtimeClasspath I get (omitted outside of project jars)

project/build/classes/test
project/build/resources/test
project/build/classes/main
project/build/resources/main

All the tests need is in these directories. I cannot figure out why classpath is insufficient. How can I make it sufficient? Why do I have to place all files in same dir?

I use only spring-data-jpa from spring. There are no other transitive spring dependencies.

Test Failure Missing Attribute From Disabled Middleware Laravel Lumen

I'm trying to create some tests for a Controller in my Laravel Lumen application, but I have been having a problem with a missing attribute that I has set in the Middleware.

So in my middleware I set a attribute to then use in my controller after.

//Save data user data into userdata attribute
$request->userdata = $user_session[0];

Then I use the attribute to select my data needed.

//Select current user data
$user = app('db')->select('SELECT * FROM users 
                           WHERE id='.$request->userdata->user_id);

The Problem I'm facing is when I want to build a test for my controller.

$this->app->instance('middleware.disable', true);
$response = $this->call('GET', '/v1/user/me');

I disabled the middleware as I cannot use it for the test. But I was wonder if I can solve my problem by mocking the attribute in some way.

Any help would be greatly appreciated, thanks all.

Symfony Functional Testing not working when clicking links

i'm trying to write a functional test in which case i want a link to be clicked and make an assertion from the new page in order to check if the button redirects properly. My test case

public function testNavigationCustomersButton()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/');
        $link = $crawler->selectLink('Customers')->link();
        $crawler = $client->click($link);
        $this->assertContains('Customers Managment - Index', $client->getResponse()->getContent());
    }

When i run the test and the $client->getResponse() is printed on the console i get the html from the index page , so i think that the link does not work properly. How can i use the crawler in order to click a link and make an assertion depending on the new loaded page?

Spring with JUnit Testing and Dependency Injection does not function

I try to use Springs own Dependency Injection in a Junit test case:

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

import org.binarisinformatik.api.AppConfig;
import org.binarisinformatik.satzrechner.SatzRechner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
//@SpringApplicationConfiguration(classes = {AppConfig.class}) 
public class SatzRechnerTest {

    @Autowired
    private SatzRechner satzRechner;  //SUT

    @Before
    public void setUp() {
    //  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SatzRechnerTest.class);
        //satzRechner=context.getBean(SatzRechner.class);
    }

    @Test
    public void addiere_satz_4komma6_zu_zahlwert_10() {

        assertThat("Addition von \"4,6\" ergibt nicht 10!",
                satzRechner.summe("4,6"), is(equalTo(10)));
    }

Im testing a class names SatzRechner in which Spring should also autowire some variables. Here is my Class under test:

@Component
public class SatzRechner {

    @Autowired //@Inject
    private Rechner taschenRechner; 
    @Autowired
    private Zahlenfabrik zahlenfabrik;

    public Integer summe(String zeichenSatz) {
        return taschenRechner.summe(zahlenfabrik.erzeugeZahlen(zeichenSatz));
    }
}

And AppConfig.class which is using as Configurationfile looks like that:

@Configuration
@ComponentScan(value={"org.binarisinformatik"})
public class AppConfig {
}

What is here the problem?

How do I expose embedded webkit/webview app on OSX for Selenium test automation?

I'm looking for a way to expose embedded view browser for selenium automation on Mac OSX. On Windows we have exposed CEF using settings.remote_debugging_port = 2012. Is there any similar way to do the same on Webview/Mac OSX?

Creating Unit test for DAO in spring mvc

Hi i want to create DAO unit test in SPRING mvc forexample for this type of code

package users;

public interface UserDAO {


    public void setDataSource(DataSource ds);

    public void create(int id, int personal, String password, String first_name, String last_name, String role,
            String email, Date date, int id_team);

    public User getUser(Integer user_id);

    public List<User> listUsers();

    void create1(int id, int personal, String password, String first_name, String last_name, String role, String email,
            Date start_date);
}

...what is the best way to do it

Tell phpunit to call public instead of private

My Question is. I have a class i want to test (myClass). In myClass there is a function wich calls a private function thats also in the myClass.

I know i can't test private functions. Is it possible to tell phpunit to call another function instead of the private?

Example

$this->testclass is now the class i want to test

$this->testclass = new \stdClass();
$this->testclass->mock = $this->getMockBuilder('myClass')->getMock();

Outside my testcase i have created a fake class.

$this->mockextended = new \stdClass();
$this->mockextended->mock = new MOCKEXTENDEDCLASSES();

in the $this->mockextended i have a public function.

the function i want to test

public function TestMe(){
$this->somePrivateFunctioniHate(); <==== this is the pain in my ass
}

and the private function

private function somePrivateFunctioniHate(){
   //come code
    }

What i want to do is. the function TestMe is calling a private function. Is it possible to tell phpunit to override the private function and call another function thats inside $this->mockextended; I have tried it like this.

$this->testclass->somePrivateFunctioniHate() = $this->mockextended->theWholeNewPrivateFunction()

only this gives me a nice error. I did this before and it worked. Called it like this

$this->testclass->chunks = new \stdClass();
//MOCKchunckTpl is the fake class outside my testcase
        $this->testclass->chunks->config = new MOCKchunkTpl("config", false, true); 

This works. Whenever a function wants to call $this->testclass->chunks->config->Somefunction(); it will be redirected to my fake class.

GoldenFiles testing and TFS server workspaces

Our product (C++ windows application, Google Test as testing framework, VS2015 as IDE) has a number of file-based interfaces to external products, i.e., we generate a file which is then imported into an external product. For testing these interfaces, we have chosen a golden file approach:

  1. Invoke the code that produces an interface file, save the resulting file for later reference (this is our golden file - we here assume that the current state of interface code is correct).
  2. Commit the golden file to the TFS repository.
  3. Make changes to the interface code.
  4. Invoke the code, compare the resulting file with the according golden file.
  5. If the files are equal, the test passes. Otherwise,
  6. Enable the refresh modus which makes sure that the golden file is overriden by the file resulting from invoking the interface code.
  7. Invoke the interface code (thus refreshing the golden file).
  8. Investigate the outgoing changes in VS's team explorer. If the changes are as desired by our code changes from step 3, commit code changes and golden file. Otherwise, go back to step 3.

This approach works great for us, but it has one drawback: VS only recognizes that the golden files have changed (and thus allows us to investigate the changes) if we use a local workspace. If we use a server workspace, programmatically remove the read-only flag from the golden files and refresh them as described above, VS still does not recognize that the files have changed.

So my question is: Is there any way to make our golden file testing approach work with server workspaces, e.g. by telling VS that some files have changed?

Open source record and playback tool for mobile application testing (both android and IOS)?

Is there any open source record and playback tool for mobile application testing (both Android and IOS)?

Thanks.

Phpunit mock private function

My question is. I have a class i want to test only thing the function i want to test is calling a private function in the class i want to test. The private function calls another class function.

I want to mock the private function so i can return value to the public functions that calls the private. I try it by creating a new class with the same function but with the value i want the function to return.

Here is my code

//function i want to test
public function checksomedata($objectID){
        $config = $this->theprivatefunction($objectID,'id');
        return $config;
    }

the private function i want to mock

private function theprivatefunction($objectID,'id'){
//do some code here. nothing special
//return the value here
}

here is my test

public function testCheckObjectAcces() {
        $objectID = '12';
      $this->testclass->checksomedata($objectID);
    }

here is my class i want to call to return some value.

public function theprivatefunction(){
        $result = "THIS VALUE NEEDS TO BE RETURNED";
        return $result;
    }

and my setUP where i try to mock the priavte function

$this->mockextended = new \stdClass();
        $this->mockextended = new MOCKEXTENDEDCLASSES();
        $this->testclass->theprivatefunction() = $this->mockextended->theprivatefunction();

In my setUp i want the code to think $this->testclass->theprivatefunction() is $this->mockextended->theprivatefunction();

So when a function is calling the private function it needs to be redirected to $this->mockextended->theprivatefunction();

A/B / Split testing in rails 3.2

I am working on Lead generation website and I am redirected from diffrent website and coming to my application with different forms with different layout and fields. Application is in ruby on rails and it is on heroku.

This form loading is based on the traffic rule which is define on admin site like 70% form form A and 30% for form B.

I want to A/B test the both the form like which form is submitted more or user went to how many steps.I also want the analysis of all that test.

Please suggest me the gem or plugin i can use. If there is a better way to do via programming?

Guidelines on performance testing and profiling android eclipse

I searched a lot on internet and stack overflow but couldn't understand how to do performance testing and profiling of android application . I have never done android or any testing before please can anybody help me with the same.

Thank you

Checking that returns JSON data in mockMVC test

this is my test:

    @Test
    public void testGetRest() throws Exception {
        mockMvc.perform(get("/rest/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())      
    }

status().isOK() check REST return 200, but how can I check if the JSON at least one record?

Session closed exception thrown while testing Spring+Hibernate Service using TestNG

I am trying to learn testing web services with TestNG. I got some project code from my friend.It uses spring for auto-wiring and hibernate for database connectivity.So I was trying to test a service.But its throwing exception

    Session is closed!; nested exception is javax.persistence.PersistenceException: org.hibernate.SessionException: Session is closed! 

But I tested the same with JUnit and no such exception was thrown.The service code is perfect and I am sure about it.So I believe that its an issue with my testing code.

The java test class is:

    @ContextConfiguration(locations={"classpath:testapplicationContext.xml"})
    @Transactional
    @TransactionConfiguration(transactionManager = "jpaTransactionManager", defaultRollback = false)
    public class TreatmentTypeManagementServiceImplTest extends AbstractTestNGSpringContextTests 
    {


      @Autowired
      TreatmentTypeManagementService treatmentTypeManagementService;  

      @Test()
      public void addTreatmentTypeTest() {
          TreatmentTypeUI TreatmentType = new TreatmentTypeUI();
          LoginUserInfo loginUserInfo = new LoginUserInfo();
          TreatmentType.setLabelText("fever");
          loginUserInfo.setSessionCompanyNid(555646);
          loginUserInfo.setUserNid(26416161);


          treatmentTypeManagementService.addTreatmentType(TreatmentType, loginUserInfo);
      } 
    }

The configuration xml is running fine with JUnit, So I believe there is no error in that.can you help me find a solution.

Looping through fields in an Angular form and testing input validations using Protractor?

I'm a beginner & am trying to loop through all the fields in an Angular form, and test that the input validation is working, using Protractor. So far I'm failing miserably. My pseudo code is as follows:

//PSEUDO CODE FOR TEST PROCESS:
//------------------------------
// 1.For each field requiring validation
// 2.Reset test environment
// 3.Populate field with dummy data
// 4.Get result
// 5.Evaluate result versus expectation for test type
// 6.Pass test description & test result (true/false) to Protractor to print to command line

The code I've written is below. It's not great, and I'm not even sure if it's possible to achieve my objective without specifying individual tests for each validation test for each field. What am I doing wrong / what is the correct approach?

describe('Sample form', function() {

// Fields subject to input validation
  var userName          = element(by.model('user.name'));           // required field
  var userSurname       = element(by.model('user.surname'));        // required field
  var userId            = element(by.model('user.id'));             // required field

// Test population
  var fieldsRequired    = [userName, userSurname, userId];          // fields to be tested

// helper function to check class of a specified element --> ng-valid / ng-invalid etc.
  var hasClass = function (element, cls) {
    return element.getAttribute('class').then(function (classes) {
      return classes.split(' ').indexOf(cls) !== -1;
    });
  };

// The testing function
  function testRequired(fieldsRequired) {
    //1. loop through each field
      for (var i = 0; i < fieldsRequired.length; i++) {

      //2. Reset page  prior to each test
        browser.get('http://ift.tt/1P9cRd2');      

      //3. Populate field with dummy data
        fieldsRequired[i].sendkeys();  

      //4,5 & 6. Protractor test
        it('should fail validation when ' + fieldsRequired[i] + ' is missing', expect(hasClass(fieldsRequired[i],'ng-valid')).toEqual(false));
      }
  }
});

jeudi 29 octobre 2015

executeUpdate () not update on grails spock-integration testing

hi i am new to grails testing. Willing to do integration test as below but problem is that executeUpdate() doesnot update value

How to do integration testing for executeUpdate('update query goes here') ??

Please help suggest me Sample code is given for problem demo. Thanks in advance.

def "for given merchantTier Id update merchantTier value"(){

    setup:
    def merchantTier = new MerchantTier(              
            value:1.11).save(flush: true) //it saves merchantTier

    when:"when update with setProperty"
    testData = editWithSetProperty(merchantTier.id) //id is passed

    then:"it updates data and test is success"
    merchantTier.value == 2.22

    when:"executeUpdate query is used instead"
    testData = editWithExecuteUpdate(merchantTier.id)// id is passed

    then:"it does not update the data and test is failed"
    merchantTier.value == 3.33
}

def editWithSetProperty(id) {
    def merchantTier = MerchantTier.get(id.toLong())
    merchantTier.setValue(2.22.toDouble())
}

def editWithExecuteUpdate(id) {
        MerchantTier.executeUpdate('update MerchantTier mt set mt.value=:mrValue where mt.id=:mtId', [mrValue: 3.33.toDouble(), mtId: id.toLong()])
}

How to do integration testing for executeUpdate('update query goes here') ??

What are the first steps in hardening a legacy Rails application?

There is a production system that has been running for many years, first as a PHP application, then as a hybrid with Rails, and now completely in Rails. It's unclear how long it has been around. The oldest git commit is from 5 years ago.

The goal is to keep the system running at all costs. It doesn't matter what code we use as long as nothing breaks. Currently it's at Rails version 3.2.33.

If we don't upgrade any gems we run the chance of becoming obsolete and undeployable. If we upgrade we will need to make changes to the code causing potential bugs to creep in. Not only do we face code rot, but also downtime due to AWS outages.

What would be the first step to make sure nothing breaks? I've spent months writing cucumber (integration) tests but it's hard to cover every edge case. The app has been running so long that most bugs have been fixed and there are few new exceptions. Testing was not a priority from the beginning so most of the code is undocumented.

JUnit Test Method for a method that returns a string

Below is my Cylinder class, and then the JUnit test that I am trying to use to test the getLabel method I wrote. I am having trouble understanding how to properly form a test method when I am testing for a string that the user will input.

public class Cylinder {
   private String label = "";
   private double radius;
   private double height;
   private static int count = 0;

   /**
   * Creates a new Cylinder object with a given label, radius, and height.
   * 
   * @param label2 The name of the cylinder returned as a String.
   * @param radius2 The radius of the cylinder as a double.
   * @param height2 The height of the cylinder as a double.
   */
   public Cylinder(String label2, double radius2, double height2, int count2) {
      setLabel(label2);
      setRadius(radius2);
      setHeight(height2);
      setCount(count2);
   }
   /**
   * This method is respondible for getting the label from the user 
   * and returns a string representation of the label.
   *
   * @return String representation of the label of the Cylinder.
   */
   public String getLabel() {
      return label;
   }

Below is my JUnit test class, which I am using to create a test for each method in my Cylinder class.

public class CylinderTest {

   private String label = "";
   private double radius;
   private double height;

   /*
   *
   */
   @Test public void labelTest() {
      Cylinder c1 = new Cylinder("", radius, height);

      String result = c1.getLabel(label);

      Assert.assertEquals(" ", label);

gulp karma test TypeError: Server is not a function

Trying to run karma using gulp for running tests but after following the example from: http://ift.tt/1y16a2M

My gulp file:

var gulp = require('gulp');
var Server = require('karma').Server;

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

/**
 * Watch for file changes and re-run tests on each change
 */
gulp.task('tdd', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js'
  }, done).start();
});

gulp.task('default', ['tdd']);

after I run: gulp test I get the Error:

TypeError: Server is not a function at Gulp.<anonymous>

Any suggestions of what might be wrong?

RoR: Model test looks for nonexistent table then gives an error

I have a rails test

class OrganizerTest < ActiveSupport::TestCase

def setup
  @organizer = Organizer.new(name: "Example Organizer", email: "organizer@example.com")
end

test "should be valid" do
  assert @organizer.valid?
end

end

and the model looks like

class Organizer < ActiveRecord::Base
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i    
  validates :email, presence: true, length: { maximum: 255 },
                format: { with: VALID_EMAIL_REGEX }
end

Now, when I run `rake test:models' I get the output:

Run options: --seed 41657

# Running:

[DEPRECATION] requiring "RMagick" is deprecated. Use "rmagick" instead
E

Finished in 0.119294s, 8.3826 runs/s, 0.0000 assertions/s.

  1) Error:
OrganizerTest#test_should_be_valid:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "sessions" does not exist
LINE 1: DELETE FROM "sessions"
                    ^
: DELETE FROM "sessions"


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

But this is sooo confusing! I have no clue why the test is looking for a table called "sessions". I have a sessions controller, but no model or db table. Been playing with this for a while but google doesn't return great results for the error message so I would appreciate if anyone can explain what's going on!

writing a spec for partial used in the layout

I'm trying to test a partial included in a layout. Following is my setup.

I have a base controller which is based for several other controllers.

BaseController < ApplciationController
  layout 'base' 
end

So, in the base layout I have included a partial _my_partial. I'm not sure how exactly to test , if the layout renders the partial.

Ex: I can test it from a controller action spec which inherit by base controller.

UsersController < BaseController
  def index

  end
end 

#users controller spec #index action
get :index
response.should render_template(:partial => "_my_partial")

But this seems to me little odd, because I actually want to test if the partial in included in every controller which inherits it. I'm thinking this test doesn't implies that.

Any ideas on how write this spec which make sense , thanks in advance..

Is the cause of a logical error necessarily the line of code for the earliest state which is wrong?

A logical error, contrary to a fatal runtime error, is a run time error which doesn't fatally terminate a program, but does something not intended.

Is a logical error necessarily caused by the line of code for the earliest state which is wrong?

Or can a logical error be caused by a line of code before the line for the earliest wrong state?

My question mainly comes from that if debugging can help to locate the cause of a logical error, since debugging can only help to find states that are right or wrong. Thanks.

Junit testing in TeamCity

I have a java application using Maven. I want to view tests results as charts or tables or something viewable, not just build logs. Can I do that? And how? Thanks for your help.

I run my test with maven wrapper, like: mvnw.cmd test.

I have a Mercurial repo polled by TeamCity for any changes pushed in, and if any found it updates my database with Liquibase-maven-plugin and then run unit-testing, with JUnit4SpringBoot and maven

Is there a way to install/emulate an older version of Safari ? (i.e 8)

On OSX: After an update to El Capitan, I found that Safari 9 was installed by default. For software testing purposes, I need to test a web app through Safari 8 (which is still the latest version in Yosemite). I searched but there is no way (expect for browserstack) to install or emulate an older version of Safari.

Other than downgrading to Yosemite, is there a way to do it?

How to avoid huge test refactoring on form change in Django

Suppose there is a model, like:

class Book(Model):
    title = CharField(...)

So now I decide to add a choice field. So I add one plus set the default value thinking that this will allow me not to refactor code that much:

class Book(Model):
    title = CharField(...)
    book_type = ChoiceField(..., default=SOME_CHOICE_DEFAULT)

But unfortunately this forces to me to refactor a lot of tests. For example there about 10 tests for the form for this model like:

def test_book_form_is_invalid_on_some_condition():
    form = BookForm({'title': 'iwfew23@f'})
    assert not form.is_valid()

I have to add a book_type field to each one. This is really frustrating. Also I have to refactor more functional tests:

def test_update_view_changes_something(admin_client):
    admin_client.post(reverse('book:update'), {'title': 'some_title'})
    ...

This will also complain that book_type isn't there.

How do I deal with such cascade refactoring when introducing a small model change?

I guess one of the ways to challenge this would be to introduce a global fixture which contains a default form data:

 @pytest.fixture
 def book_form_data():
     return {'title': 'some title'}

 def test_some_form_test(book_form_data):
     book_form_data['title'] = 'another title for this test'
     form = BookForm(book_form_data)
     ...

So the only place where I should add book_type will be this fixture. But that does not look quite right as well.

Finding visible elements on webapp using selenium

I need help to find visible elements on a webapp page using selenium. For example, I need to find a row that is click-able and click on it. The problem is that the elements are visible but not present in the page source as they are generated. Also, I'm coding in Java to find the elements. I tried using xpath and css path which I found using Firefox Firebug, but it didn't work. The click-able rows in the table all have the same class. They have different text though. Any help? Thanks!

migration testing in postgres using flyway and pgtap

Ok, I'm going to do everything right this time.

I set up flyway for migrations and pgtap for testing. Now I want to find a good way to perform the migration testing.

I'm also going to have lots of stored procedures. So migration includes:

  • (maybe) testing before migration to ensure everything is in an appropriate state. I can rerun tests from the previous migration or assume everything is fine
  • migrating schema and data
  • changing stored procedures
  • testing the schema
  • validating data
  • unit-testing stored procedures
  • integration tests, docker makes it easier

So I have migrations in the flyway. This one seems to be hard.

 V34__split_a_column_in_a_table.sql

I want to test it. I have so many questions:

  • Should I add tests to a flyway migration? Should these tests be run in production database after tested in dev and staging environments? Should I only validate schema here? Should I only have somewhat lightweight tests here and have a separate set of heavy tests?
  • Should I have all stored procedures redefined one by one? Or all of them at once? I mean I can copypaste an SP to the migration code and change it, but tracking changes would be hard and it's error prone I guess. What if I copy an entire previous SPs file, change it and see those changes using diff?

What if I have a migration, stored procedures, and tests in a group of files.

 V34_1__the_migration_itself___split_a_column_in_a_table.sql
 V34_2__stored_procedures.sql
 V34_3__validate_schema.sql
 V34_4__tests.sql

Now I can see changes between current and previous sets of SPs:

 $ diff V33_2__stored_procedures.sql V34_2__stored_procedures.sql  

Same for schema validation and tests.


What am I missing? Any ideas how to improve this workflow? What can go wrong? Any better workflow?

Android publish just to aplha?

Is it possible on the developer console to publish only an alpha APK? I recently enabled and set up alpha testing on my new app, but when i click publish, it not only publishes to alpha, but also releases it to production. What is the point in alpha testing if you have to release it to everyone as well!

Am i doing something wrong, or will i just have to make no devices supported on the production version?

Any help is greatly appreciated, thanks.

Is it possible to save/export results of website audit from Webkit Developer Tools Audit panel?

As stated above, is it possible - whether using 3rd party plugins for Opera/Chrome or some of chrome://chrome-urls/ or maybe some hidden experimental browser features? I need to perform series of website performance audits and data from results must be available for me, for further analysis.

Although Firefox's built-in dev tools Audit tool allows me to import results, the tool itself lacks the built-in hints system like webkit dev tools have - the result data is raw.

If there's currently no solution to this problem, what external website performance testing tools you recommend then? Rather free(mium) than paid.

I can't catch Requests between Mobile Android and server using fiddler

I do all configuration on fiddler on my Pc and on My android Phone.

The application that I want to catch his request use last loopJ library.

When I make login or any action on my application nothing appear on fiddler.

If fiddler can't catch requests, is there any alternatives.

Force @media print for automated test

From bootstrap, I am using hidden-print to hide certain things when printed. I want to write an automated test to verify this. I don't know how to force the browser so that @media print media queries will fire.

Currently we are using protractor for this kind of testing, but if anyone can provide any solution with another tool, that would be a great starting point.

official test suite for PL/I like for Cobol 85?

Could anybody point me to an official test suite for PL/I ?

as PL/I is an ANSI standard, I was hoping to find such a suite but I'm unsuccessful in my search until now.

Ideal would be to find a suite like the test suite for COBOL85 test suite produced by the National Computing Centre and available at http://ift.tt/1Rg1D5R

Goal is to validate a PL/I compiler for x86 through formal testing.

Thanks in advance !

didier

Linked in - multiple test accounts

i need for my application to create and generate test linked in accounts for every time i run my tests. I have researched and found only this solution which won`t work for me : http://ift.tt/1vnuSb3 2.3 Test Account You may create up to five LinkedIn test accounts for purposes of testing your Application only. You must create the accounts manually and not via any automated means, such as scripts.

These test accounts must not interact with non-test accounts (for example, you can’t use test accounts to comment to posts on a Company Page and you can’t connect test accounts with non-test accounts, including your LinkedIn account), or override our API call limits. You must clearly identify the accounts as test accounts in the applicable account profile, and must identify these additional account profiles as “Developers” in your Application registration. You may not create any profile positions at real companies (besides your own) through the test accounts.

I will need more than 5 test accounts and also would like to skip the registration of my application into linked in with Real Data...

For facebook integration i managed to make this using http://ift.tt/I37asW

If someone have any suggestions or solutions please help :)

How to deal with Setter/Getter-Methods from Mocks?

So I am still having trouble with the usage of Mockito. So let's assume I have following class (Please ignore the logic, or structure of it, it's just a short example I created from another class, with different names and so on.) :

public class Restaurant(
    @Autowired
    private CustomerService customerService;

    private CustomerInputData updateCustomer(CustomerInputData inputData){
        final String customerId = inputData.getID();
        final Customer customer = customerService.getCustomerById(customerID);
        if(customer.getAddress() != null){
            inputData.setCustomerName(customer.getCustomerName());
            inputData.setCustomerCity(customer.getCustomerCity);
            inputData.setCustomerLanguage(customer.getLanguage);
        }

        return inputData
    }
}

So my understanding of Unit-Tests is, to isolate all dependencies. Here I would have the Customer-class and the Customer-Service.

So to write a test-class, I would currently do following:

public class RestaurantTest()
{
    @Mock(name="customerService");

    private CustomerService customerService;

    @InjectMocks
    private Restaurant classUnderTest;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void updateCustomer_WithValidInput_ShouldReturnUpdatedInput(){
        //Some Mocking first
        final String customerId = "customerId";
        final Customer customer = mock(Customer.class);
        final final CustomerInputData = mock(CustomerInputData.class);

        doReturn(customer).when(customerService.getCustomerById(any(String.class)));
        doReturn(customerId).when(inputData.getId());

        doReturn("address").when(customer.getAddress());
        doReturn("Name").when(customer.getName());
        doReturn("City").when(customer.getCity());
        doReturn("Language").when(customer.getLanguage());

        doNothing().when(inputData).setCustomerName(any(String.class));
        doNothing().when(inputData).setCustomerCity(any(String.class));
        doNothing().when(inputData).setCustomerLanguage(any(String.class));

        verify(customer.getAddress(), atLeastOnce());
        verify(customer.getName(), atLeastOnce());
        //and so on...

        verify(inputData, atLeastOnce()).setCustomerName(eq("Name"));
        verify(inputData, atLeastOnce()).setCustomerCity(eq("City"));
        verify(inputData, atLeastOnce()).setCustomerLanguage(eq("Language");

    }
}

So currently I have no Assert, I only check if the right methods get called. The reason, why I try to do this like this, and not let the Test-class call the setter/getter is because of isolation. Let's assume inputData.setCustomerCity is broken, my test would fail. So it is depending on the CustomerInputData-Class.

Now how do I approach these getter and setters, what is the best practice?

Do I have not understood Mockito good enough? When I use mock(), can I then just use the setter-methods and gethods, and don't need to worry about using doReturns and so on?

I know it is a whitebox-test, I know the methods and what's going on.

Testing directives with controller

I have a directive with a controller:

aaaApp.directive('aaaButton', function() {
    return {
        restrict: 'E',
        scope : {
            id: '@',
            valueKey: '@value',
            label: '@'
        },
        controller: 'ButtonController',
        template:
        '<div id="{{id}}" class="aaa-button-default"> ' +
        '<button ng-click="doClick(valueKey)">{{label}}</button>' +
        '</div>'
    };
});

And i want to access to the scope functions for testing, but for now i am testing just with vars of the scope in the controller. I have pot a variable on the scope:

controller('ButtonController', function ($scope, WSService) {
    $scope.testing = "hello";
})

Im tryng to test if $scope.testing is equals to "hello" on the generated controller when the directive is compiled:

'use strict';
describe('directives', function() {
    var $scope, controller, template;
    beforeEach(module('aaaApp'));
    beforeEach(inject(function($rootScope, $compile) {
        $scope = $rootScope.$new();
        var element = angular.element('<aaa-button id="1234" value="cancel" label="Cancel"></aaa-button>');
        template = $compile(element)($scope);
        $scope.$digest();
    }));
    it("testing controller", inject(function() {
        expect($scope.testing).toBe("hello");
    }));
});

The problem is that im geting undefined on the $scope.testing so i cant acces to the $scope of the controller.

mercredi 28 octobre 2015

I want to learn to write tests for nodejs modules, where do I start?

I have this NPM module recently published and I need to write some tests for it, I will need to read some html files and verify the content, any help? Maybe you know some good tutorial or examples that can help me.

Thanks!

Drag and drop slider widget

Is it possible to select exact value of slider widget (lenght selection) in Selenium IDE? For example I need to select only 50-100 inch and test in that range only.

Right now I'm using drag and drop by moving slider by x pixels, but it does not work as depending on page view zoom same offset results in different lenght value.

How can I tell if a structure in Python has order?

I'm writing a set of test cases for users new to Python. One of the problems I've noticed with my tests is that its possible to get false positives. They may have gotten lucky and happened to give every element in the correct order, however they really should be using a structure that is ordered.

So far this is the best solution I could come up with for this solution.

self.assertTrue(isinstance(result, Sequence) or
                isinstance(result, GeneratorType) or
                callable(getattr(result, '__reversed__', False)))

However, I don't feel confident GeneratorType is really ordered, or that this test is comprehensive. I feel like there should be a better way to test for this. How do I test that a structure has order?

How do I test my c#-based cmdlet?

I've been looking all over the place for a decent example and most results are basics of power shell....

But anyway, I did manage to find this: http://ift.tt/1iiSvkt

Which gave me a start, and allowed me to end up with this test, based of the example in the above link:

using System;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using MyProject;

namespace Commands.Tests
{
    [TestClass]
    public class StartServiceTest
    {
        private RunspaceConfiguration config;

        [TestInitialize]
        public void Initialize()
        {
            config = RunspaceConfiguration.Create();
            config.Cmdlets.Append(new CmdletConfigurationEntry(
                "Start-UseService",
                typeof(StartUseServiceCommand),
                "Microsoft.Windows.Installer.PowerShell.dll-Help.xml"));
        }

        [TestMethod]
        [DeploymentItem(@"data\example.txt")]
        public void PathTest()
        {
            using (Runspace rs = RunspaceFactory.CreateRunspace(config))
            {
                rs.Open();
                using (Pipeline p = rs.CreatePipeline(@"start-useservice -service ACE"))
                {
                    Collection<PSObject> objs = p.Invoke();
                    Assert.AreEqual<int>(1, objs.Count);
                }
            }
        }
    }
}

The article doesn't explain anything, so I'm sure "data\example.txt" doesn't apply to me, but example.txt is used as a parameter in the example's test. But the method attribute just isn't discussed.

Has anyone successfully wrote a test for their cmdlet? I'm also looking for a bit of an explanation of what each piece does. (I'm not new to MSTest, but I've never used the System.Management.Automation/Runspaces Namespace(s) before)

My cmdlet name is Start-UseService

Stub controller redirect_to external url with VCR

Some third-party service which I want to use requires user to log in on their webpage. Handy url is generated in controller below. User goes there and come back to my service after his authentication succeeds

class MyController < App::BaseController
  def login
    redirect_to SOME_API.external_url(ENV['secret_id'])
  end
end

As user comes back to my service he brings some feedback from third-party service in URL params (like: http://ift.tt/1kSwA5O). There are many variants of these params so I need to handle them in my action

  def login_callback
    #SOME MAGIC WITH COOKIES/ERRORS/What ever
    redirect_to root_path
  end

I want to write feature specs for it using RSpec and capybara.

scenario 'User authenticates with third-party thing' do
    visit '/anything'
    click_link 'Go to MyController#login and than get redirect to http://ift.tt/1kSwA5Q'
    # use cassette below
    fill_out_form
    click_button confirm
    # magic happens on their side and their redirect user to my app into #login_callback action
    expect(page).to have(/all fancy things i need/)
  end
end

however calling WebMock.disable_net_connect!(allow_localhost: true) or adding vcr: { cassette_name: 'using_third_party_login', record: :new_episodes } doesn't prevent this scenario to being redirect to external url.

Capybara just let being redirected to external uri and no cassets are being recorded/played. Any idea how to stub redirect_to external_url with cassette play/record?

Ember-cli project testing with Compass includes css conflicts

I have an ember-cli generated project that uses Compass and the SASS version of Bootstrap. In my app.scss, I have the following imports (for Bootstrap):

@import "../../bower_components/bootstrap-sass/assets/stylesheets/bootstrap";

@import "../../bower_components/bootstrap-sass/assets/stylesheets/bootstrap/theme";


body {
  padding-top: 70px;
  padding-bottom: 30px;
}

When I execute the tests in a browers, the output from the tests are grayed as if there were a modal dialog open. The reason is because the test output page is including app.scss which in turns loads bootstrap and my custom changes. The output looks like this: Notice the 70px padding at the top and that everything is gray

I'm new to Ember testing, so I'm wondering if I am setting up app.scss wrong. Is there a way to have testing work properly and ignore the app.scss styles?

Web SaaS service to load test my website?

I need to load test a webpage on my server. I have looked at blitz.io, however I don't seem to be able to find any documentation on how to check if the page actually renders successfully.

What pay-as-you-go hosted alternatives are there?

How do I get a date in MMM, YYYY format using C#

I am writing a selenium automated test where I have to verify that the dates on the x-axis of the graph (shown) are correct. These dates change based on a drop down we have in the web application. (Ignore the arrow :))

enter image description here

I'm trying to generate the date in the MMM, YYYY format and compare it with the date elements in the graph

I have the following code so far:

 string circleDate2 = date.Month.ToString("MMM") + ", " + date.Year.ToString("YYYY");

however this just outputs MMM, YYYY on the console.

How do I generate the date in MMM, YYYY format and then add or subtract another month so I can verify all the date elements on the page?

MRUnit - Test success depends of output order

I have created a small example to figure out how to use MRUnit for testing MapReduce code. The example that I am trying to run is wordcount, so I won't paste the code here since it's familiar to all.

I have written tests using JUnit. What confuses me is that the success of the test depends of the order in which output values are listed.

For example, this test passes:

mapDriver.withInput(new LongWritable(), new Text("Hadoop is cool"))
            .withOutput(new Text("Hadoop"), new IntWritable(1))
            .withOutput(new Text("is"), new IntWritable(1))
            .withOutput(new Text("cool"), new IntWritable(1))
            .runTest();

But this one does not

mapDriver.withInput(new LongWritable(), new Text("Hadoop is cool"))
            .withOutput(new Text("Hadoop"), new IntWritable(1))
            .withOutput(new Text("cool"), new IntWritable(1))
            .withOutput(new Text("is"), new IntWritable(1))
            .runTest();

This is not the behavior that I would expect.

Is this a bug in MRUnit, or is there a reason for such a behavior?

Add maven task to build.gradle

I'm trying to add "maven test" taks to gradle file, but I don't find the way to do in its documentation http://ift.tt/1KxjtvM, someone wuold help me please?, thanks in advance

Java or C++ systems that use command line interface [on hold]

I'm searching for complex systems developed in Java or C++ but use command line interface, I need them to perform some performance tests. Also if it is and open source project of sorts it wold help, because I would like to compare the different versions of the same project too. But I'm having a bad time to find this kind software due to the command line interface restriction. Thanks in advance!

Access result when running mocha programmatically

I'm using mocha programmatically and want to access the result in my program for later computation.

Currently, I have:

var mocha = new Mocha({
  reporter: 'json'
});

files.forEach(file => {
  var path = process.cwd() + '/' + file;
  mocha.addFile(path);
});

mocha.run()
  .on('start', function() {
    // do something
  })
  // ...
  .on('end', function() {
    // I want to resolve the promise with the result generated by mocha:
    resolve(result);
  });

However, I never get access to the result reported by the json reporter (Only on command line). Is there a way to access the result as json in my program? For example, by writing the result to a file an reading it later?

RSpec matching request to render text

Is it possible to examine if get request rendered text?

I know there are hacks like response.body == 'any string' but it does not interest me. I'm just wondering if there is "RSpec™" way to do it.

Having this rspec:

RSpec.describe MyController, type: :controller do
  controller do
    def index
      render text: 'Hellow'
    end
  end

  describe 'rendering' do
    subject { get :index }
    it { is_expected.to render_template(text: 'Hellow')}
  end
end

I would love to be able to call it { is_expected.to render_template(text: 'Hellow')}. It raises:

 Failure/Error: it { is_expected.to render_template(text: 'Hellow') }
 ArgumentError:
   Unknown key: :text. Valid keys are: :layout, :partial, :locals, :count, :file

or maybe it { is_expected.to render_template('Hellow')}

 Failure/Error: it { is_expected.to render_template('Hellow') }
   expecting <"Hellow"> but rendering with <[]>

Is there any RSpec™ way to accomplish it?

How to check if warning is correct

I have a function which catch exception and add warning messages in console. I need to create unit test which should verify if the message is as expected.

static int function(String hostname, int ktsPort, boolean sslInsecure) {
    int foundKtsPort = ktsPort;
    if (ktsPort < 0) {
        return checkForKTSPort(hostname, KeyTrusteeConstants.KTS_PORT, sslInsecure);
    } else {

        try {
            ....
            }
        } catch (IOException e) {
            if (e instanceof smth) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn("SSL failure");
                }
            }
        }
}

Test should check if message "SSL failure" is present

I'm new in unit testing. So, maybe somebody have any idea how to do it. Thanks

PowerMock in Scala: java.lang.NullPointerException when getPackageName

This code just start a TezClient in local mode (not use any mock techniques yet), but it failed.

At first, it fails with this exception,

 java.lang.IllegalArgumentException: Can't find HmacSHA1 algorithm.

then I have to add this line to fix it,

@PowerMockIgnore(Array("javax.crypto.*"))

but it still failed. Anyone see this problem before?

Code:

import org.apache.tez.client.TezClient
import org.apache.tez.dag.api.TezConfiguration
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PowerMockIgnore
import org.powermock.modules.junit4.PowerMockRunner
import org.scalatest.junit.JUnitSuite

@RunWith(classOf[PowerMockRunner])
@PowerMockIgnore(Array("javax.crypto.*"))
class TestEdgeImpl extends JUnitSuite {

  @Test def test1() {
    val conf = new TezConfiguration
    conf.setBoolean(TezConfiguration.TEZ_AM_SESSION_MODE, true)
    conf.setBoolean(TezConfiguration.TEZ_LOCAL_MODE, true)
    val tezClient = TezClient.create("LocalClient", conf)
    tezClient.start()
  }
}

Error logs:

[info]   java.lang.NullPointerException:
[info]   at org.apache.hadoop.yarn.factories.impl.pb.RecordFactoryPBImpl.getPackageName(RecordFactoryPBImpl.java:95)
[info]   at org.apache.hadoop.yarn.factories.impl.pb.RecordFactoryPBImpl.getPBImplClassName(RecordFactoryPBImpl.java:82)
[info]   at org.apache.hadoop.yarn.factories.impl.pb.RecordFactoryPBImpl.newRecordInstance(RecordFactoryPBImpl.java:56)
[info]   at org.apache.hadoop.yarn.util.Records.newRecord(Records.java:36)
[info]   at org.apache.tez2.LocalClient.createApplication(LocalClient.scala:60)
[info]   at org.apache.tez.client.LocalClient.createApplication(LocalClient.java:41)
[info]   at org.apache.tez.client.TezClient.createApplication(TezClient.java:776)
[info]   at org.apache.tez.client.TezClient.start(TezClient.java:345)
[info]   at org.apache.tez2.tmp.TestEdgeImpl.test1(TestEdgeImpl.scala:38)
[info]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[info]   ...

Do we need writing test for UI component in Android?

I am using MVVM pattern for android. I see that writing test for ViewModel is necessary. How about View? Do we really need writing unit test for View or UI Components?

Ho to change values for SOAPUI Request?

Take values from Response Change into some String and save it.

E.g. from req1 : Response : Company Name = Abc I Want to take this Name from Response, Change to xyz and save it.

But every time I have to Change, next time I will run then I will get xyz and this time I want to Change to some string and then save. Is it possible to do automatically?

Thanks

Unit-Tests | When to use when ... | Mocktio

So I am currently writing Unit-Tests with JUnit and Mockito.

So let's say I have following testclass setup:

@Mock(name="myService")
private myServiceClass myService;

@InjectMocks
private myClassIWantToTest classUnderTest;

final myModelClass myModel = new myModelClass();

@Before
private void setUp(){
    MockitoAnnotiations.initMocks(this);

}

@Test 
private void testSomething(){
    myModel.setCode("someCode");

    final MyDataClass myData = new MyDataClass();
    myData.setCode("someCode");

    doReturn("someCode").when(myModel.getCode());
    doReturn(myModel).when(myService.getModelByCode("someCode"));

    assertEquals(classUnderTest.getDataByCode(eq("someCode")), myData);
    verify(myService.getModelByCode(eq("someCode")), atLeastOnce());
}

The method getDataByCode from my classUnderTest converts the Model into Data and it should have the same Code.

So what is a bit blurry for me is, that Unit-Tests should encapsule the classUnderTest from all dependencies. But now I have a problem. I use the setter-methods myData and myModel to set a Code. The thing is I put a DoReturn in there for myModel, but the problem is, that it's not a injected Mock. The method I try to test unfortunately doesn't have a field, it initializes this inside the method, so I can't really address it.

And the main thing is, when the set-Method of for example myModel doesn't work anymore or so, my Test as shown above, wouldn't work anymore.

So I guess I have three questions:

1.) So how hard do I need to isolate the testclass? Don't I need to use the set-method for the assertEquals?

2.) Is there another way to deal with objects, which are initialized inside a method I want to test? What is the best way to approach such a matter?

3.) Also, what would be a good pattern for structuring this? I currently initialize my expected myData result inside a Test-method. The thing is, that this is a rather short and easy example, but I have classes, where I have tons of objects and methods.

Thanks!

Testing url redirection in Django

If I go to http://localhost:8000/login/, login form will be displayed and you have to input username and password. If the credentials are right then you will be redirected to http://localhost:8000/dashboard/. The problem I am facing while testing is even though my username and password are correct it is not redirected to http://localhost:8000/dashboard/ but rather it goes to http://testserver/admin/login/?next=/dashboard/. I am using the below code to rest redirection functionality in django:

class UrlTests(TestCase):

    def test_client_cart(self):
        response = self.client.get('/login/')
        self.assertEqual(200, response.status_code)

    def test_login_client(self):
        User.objects.create_user('rakesh', 'rrs402@nyu.edu', 'ranjan')
        self.client.get('/login/')
        self.client.login(username='rakesh', password='sukla')
        print self.client.get('/dashboard/')

Could anyone tell me why i am redirected to http://testserver/admin/login/?next=/dashboard/ instead http://localhost:8000/dashboard/.

In my settings.py file:

LOGIN_URL = '/'
LOGOUT_URL = '/logout/'
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/'

My application is working fine but I am not able to test redirection thing. Could anyone give me some pointers where I am going wrong?

If I print out print self.client.login(username='rakesh', password='sukla') it is coming out to be True which means I am able to login but why not redirection ?

Element not visible Error but seen on the browser clearly

I have been doing on protractor to test some apps from end user perspective and I have got this error 'ElementNotVisibleError: Element is not currently visible and so may not be interacted with...' I have test first if the element is visible or not and the test said the element is not visible. But I see the element displayed on the browser and intractable. So anybody can help me to solve out this problem please?

mardi 27 octobre 2015

BMR Calculator testing

Was just finishing up a test class for a project on exercise and BMR when I got the error that it "cannot find symbol" while pointing at the second "BMR" while making each different person to use the test on. AFAIK the actual bmr class works fine because it doesn't give me any errors.

Test class:

public class BMRTest {
  public static void main(String[] args) {
    BMR bmr1 = new BMR("Test Person1", 123, 128, 30, 'm', 2);
    BMR bmr1 = new BMR("Test Person2", 156, 115, 24, 'f', 1);
    BMR bmr1 = new BMR("Test Person3", 136, 147, 19, 'm', 5);
    BMR bmr1 = new BMR("Test Person4", 145, 192, 24, 'm', 4);
    BMR bmr1 = new BMR("Test Person5", 125, 121, 44, 'f', 3);

    System.out.println("1" + bmr1.calculateBMRWithExercise());
    System.out.println("2" + bmr1.calculateBMRWithExercise());
    System.out.println("3" + bmr1.calculateBMRWithExercise());
    System.out.println("4" + bmr1.calculateBMRWithExercise());
    System.out.println("5" + bmr1.calculateBMRWithExercise());
  }
}

Actual BMR Class:

public class BMR {

  private String Name;
  private float weight;
  private float height;
  private int age;
  private char gender;
  private int exercise; //1-5

  //BP
  public BMR(String n, float w, float h, int a, char g, int e) {
    n = Name;
    w = weight;
    h = height;
    a = age;
    g = gender;
    e = exercise; //1-5
  }

  //CALCULATE
  public float calculateBMR() {
    float rv;

    if (gender == 'f') {
      rv = femaleBMR();
    } else {
      rv = maleBMR();
    }
    return rv;
  }

  //MALE BMR
  private float maleBMR() {
    return 66 + 6.23f * weight + 4.7f * height - 6.8f * age;
  }

  //FEMALE BMR
  private float femaleBMR() {
    return 655 + 4.35f * weight + 12.7f * height - 4.7f * age;
  }

  //EXERCISE ADJUSTMENT
  public float calculateBMRWithExcercise() {
    float rv = 0;
    float bmr = calculateBMR();

    switch (exercise) {
      case 1:
        rv = bmr * 1.2f;
        break;

      case 2:
        rv = bmr * 1.375f;
        break;

      case 3:
        rv = bmr * 1.55f;
        break;

      case 4:
        rv = bmr * 1.725f;
        break;

      case 5:
        rv = bmr * 1.9f;
        break;

      default:
        System.out.println("Error");
        break;
    }
    return rv;
  }
}

Incrementing value with Selenium IDE

How to increment value of img path when said path looks like this?

//ab[x]/img

X value increasing by 1 and has a limit of 50.

Trying to write test case on how to click on several images on website.

Rails 4 Integration Testing - Failing (event Assert True)

Alright, a little embarrassed I asked a very similar question yesterday, but we're stuck again.

We've fixed all of our controller tests, and started writing integration tests. We're encountering errors on all of our integration tests, even the famous assert = true:

site_layout_test.rb

require 'test_helper'

class SiteLayoutTest < ActionDispatch::IntegrationTest


  test "the truth" do
    assert true
  end

#commenting out our real tests for debugging

=begin
  test "top navigation bar links" do
    get 'beta/index'
    assert_template 'beta/index'
    assert_select "a[href=?]", home_path
    assert_select "a[href=?]", how_it_works_path
    to do add map, community, sign up, login paths
    to do: add paths to links on dropdown if user is logged in
  end
=end

end

Terminal Test Results

12:31:32 - INFO - Running: test/integration/site_layout_test.rb
Started with run options --seed 27747

ERROR["test_the_truth", SiteLayoutTest, 2015-10-25 11:36:28 +0800]
 test_the_truth#SiteLayoutTest (1445744188.33s)
NoMethodError:         NoMethodError: undefined method `env' for nil:NilClass


  1/1: [===================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.05380s
1 tests, 0 assertions, 0 failures, 1 errors, 0 skips

test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  include Devise::TestHelpers
  # Add more helper methods to be used by all tests here...
  #

  def setup_variables
    @base_title = "TripHappy"
  end
end

Unfortunately, that error message gives us very little clue as to where the error is occurring. I tried reading up on Minitests, but without an idea of where to look I'm fairly lost.

Thank you in advanced!

For reference, we're following M. Harti's Rails Tutorial, which means we're using Guard and Minitest Reporters. We also have a login system via Devise, if that affects anything.

How to unit test a method with dynamic return values?

I have a method like this:

public List<string> GetAllDomains()
{
       List<string> domains = new List<string>();

      DirectoryContext directoryContext = new DirectoryContext(DirectoryContextType.Domain);

      using (Domain currentDomain = Domain.GetDomain(directoryContext))
      using (Forest forest = currentDomain.Forest)
      {
          DomainCollection addDomainsInForest = forest.Domains;
          foreach (Domain domain in addDomainsInForest)
          {
              domains.Add(domain.Name);
          }
      }

      return domains; 

}

How can I write an unit test for this method? Thanks.

Testing a PHP app with Elasticsearch dependency

Haven't been testing my applications until recently so not much practice nor knowledge on the subject.

Requirement

In my php app, I want to assure the functioning of the following functionality:

  • class xService receives array of filters
  • the class forms filters for an ES search query
  • the class fetches IDs of matching documents from remote ES server
  • the class returns rows from SQL DB with corresponding IDs

Attempted solution

A test run by phpUnit.

1) The test creates models in the SQL DB and indexes them to remote ES server. (input)

2) The test sends an array to xService. (input)

3) Class xService returns rows from database (output/assertion)

Problem

Running the exact same test over and over again, the results vary. I assume this is because sometimes the indexed documents are not yet available when the search query arrives at the ES server (I am using free hosting at Facetflow).

What is the best way to assure this functionality?

How to test an object's private methods in Scala

I have an example object:

object Foo {
  private def sayFoo = "Foo!"
}

And I want to test the private sayFoo method without the following workarounds: 1. Without defining it as package private 2. without defining it as protected and than inheriting it in the test class

I saw one possible solution which is to extend privateMethodTester but it doesn't seem to work for objects just classes.

Now, I know that some, if not many, say that you are not suppose to test private methods but rather only public ones (api). Nonetheless, I still do want to test them.

thx in advanced

equivalence partitioning and boundary value analysis

I am slightly stuck with understanding the following scenario.

A procedure is designed to allow lecturers to enter a student mark which should be an integer between 0 and 100. After entry, the procedure then e-mails an appropriate message to the student if the mark is < 40 (the pass mark).

Using equivalence partitioning and boundary value analysis, identify a set of test cases for this procedure

How to verify that an element is present in CucumberJS and Protractor?

I want to verify that an element is present when I access a page using the above mentioned FWs, is there any similar assertion library for these like the one that exists in Jasmine?

Integration test for the order for a query in Rails 5

Rails 5 will deprecat assigns, which is handy when testing the order of an AR query.

test "admin sorts members by date joined" do
  get memberships_path(sort: :by_date_joined)
  memberships = assigns(:memberships)
  assert_equal [@bart, @lisa, @homer], memberships.to_a
end

Integration tests in Rails 5 encourage you to simulate the user experience as much as possible. This means we should search the rendered HTML for the right links.

[@bart, @lisa, @homer].each do |member|
  assert_select "#member_#{member.id}"
end

assert_select is useful if we want to ensure that members are being rendered correctly, but it does not guarantee order.

So what can we do to test the order?

Hide R namespaces for testing purposes

I'm developing an R package which can optionally use third-party packages, as specified in the "suggests" field of the DESCRIPTION file. Functions which may optionally use the suggested third-party packages check for their availability via the requireNamespace function. These functions behave differently depending on the presence or not of the suggested packages.

While implementing tests for theses functions, I would like to test for the case where the optional packages are not present. My question is: is it possible to temporarily hide a namespace for testing purposes, such that the requireNamespace function returns FALSE when searching for it?

Getting Error: getaddrinfo ENOTFOUND using https

I have created this simple class:

import https from 'https';

class Request {

    constructor(opts) {
        this.hostname = opts.hostname;
    }

    init(method, path, data = {}) {
        const optsReq = {
            hostname: this.hostname,
            path: path,
            method: method
        };

        return new Promise((resolve, reject) => {
            const req = https.request(optsReq, (response) => resolve(response));
            req.on('error', (error) => {
                console.log(error);
                reject(error);
            });
            req.end(JSON.stringify(data));
        });
    }

    get(path) {
        return this.init('GET', path);
    }

    post(path, data) {
        return this.init('POST', path, data);
    }

    put(path) {
        return this.init('PUT', path);
    }

    delete(path) {
        return this.init('DELETE', path);
    }

    patch(path) {
        return this.init('PATCH', path);
    }
}

export default Request;

and then I'm trying to test it:

import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';

import Request from '../src/request';

chai.use(chaiAsPromised);

describe('Request', () => {

    const hostname = 'fake-server.com';
    let server;

    before(() => {
        server = sinon.fakeServer.create();
        server.respondWith(
            'GET',
            `https://${hostname}/api/entities`,
            [ 200, { 'Content-type': 'application/json' }, JSON.stringify({ entities: 1 })]
        );
    });

    it('Receive HTTP 200 status code from a GET request', () => {
        const opts = { hostname };
        const req = new Request(opts).get('/api/entities');
        return expect(req).to.eventually.have.property('entities');
    });

    after(() => {
        server.restore();
    });
});

unfortunately whatever hostname I use I always get the following error:

[Error: getaddrinfo ENOTFOUND fake-server.com fake-server.com:443]

Any idea?

Easy to set DTC

I am working with vehicle diagnostics and CAN, but have run into a problem when trying to do testing. There is nothing wrong with the vehicle I am using. I need to find either a harmless and very likely easily reversible problem I can create on the vehicle that will set a trouble code for me to read, or I need to find a way to artificially set one. I am actually not even sure the latter is possible. I know there are plenty of things I can do to cause trouble with a vehicle, but I am trying to find something that won't permanently damage the vehicle.

I know Trouble codes aren't universal across all vehicles, or at least not all of them are, I just figured that there must be some common problem that most vehicles will set a DTC for.

scalacheck case class random data generator

I'm trying to generate random data with Scalacheck. I have a hierarchy of case classes with many properties. The only way I've found so far to populate the case classes is like this :

case class Data(a: String,
                b: String,
                c: String)

val genLigneDecompte: Gen[Data] = for {
  ag <- Gen.alphaStr
  bg <- Gen.alphaStr
  cg <- Gen.alphaStr
} yield Data(
    a = ag,
    b = bg,
    c = cg
  )

For a case class with 10-20 properties it's pretty tedious. I was wondering if there was a way to automate it somehow...

Chai-as-promise pass always the test

I have created this unit test:

import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';

import Request from '../src/request';

chai.use(chaiAsPromised);

describe('Request', () => {

    const hostname = 'http://localhost';
    let server;

    before(() => {
        server = sinon.fakeServer.create();
        server.respondWith(
            'GET',
            `${hostname}/api/entities`,
            [ 200, { 'Content-type': 'application/json' }, JSON.stringify({ entities: 1 })]
        );
    });

    it('Receive HTTP 200 status code from a GET request', () => {
        expect(new Request({ hostname }).get('/api/entities')).to.eventually.have.property('entities');
    });

    after(() => {
        server.restore();
    });
});

the point is that whatever I put on the property on the api it return successfully always. How is possible? there is something that it doesn't work.

Copy (Clone) autofac registration

In a test project i found performance gap when i use Autofac latest version. I have BaseTest class that is base class for all tests. In ctor i create Autofac ContainerBuilder object, register all types, etc.

Then - build container and use it for Service Locator.

The problem is - i could not make container static and initialize it only one (not once per each test), to save ton of time on scanning assemblies for registering types, etc.

My goal - create static ContainerBuilder (or Container) - where in static ctor BaseTest i will register all types and then in usual ctor will copy this instance (with all registration) to non static property and use it for ServiceLocator.

Why i need it - because, for example TestA change/add substitution or so TestB does knows anything about that substitution. So i need clean up all customization about registration after each test set.

Do you have any ideas about how to do it? I search a lot of info in autofac - as i understand no possible to copy or clone container. Also i could not make ContainerBuilder static and in usual ctor call Build() or Update , because it`s not allowed.

Thanks in advance.

Rails 4 - All Tests Failing (even Assert true)

New to rails and just getting started learning testing. We're having a problem that probably has a simple answer that has us stumped.

We have wrote some code and got it working in development (just static code and a login system w/ Devise). The only test cases in our file were generated by rails, for example:

  test "should get about" do
    get :about
    assert_response :success
  end

However, when we run bundle exec rake test, to our surprise, we fail every single test.

10 runs, 0 assertions, 0 failures, 10 errors, 0 skips

Each test has the same error:

ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "email" violates not-null constraint
DETAIL:  Failing row contains (980190962, null, 2015-10-27 09:40:30, 2015-10-27 09:40:30).
: INSERT INTO "leads" ("created_at", "updated_at", "id") VALUES ('2015-10-27 09:40:30', '2015-10-27 09:40:30', 980190962)

By reading that error, it seems like there is some record in our leads table without an email. E-mail was a field created later after a migration. However, looking through psqlAdmin, every row has an e-mail. Furthermore, if we look in the console after loading the pages in chrome, there are no errors.

Even the most basic test is failing with the same error:

test "the truth" do
    assert true
end

My only guess is that there is some default seeding going on, and it is trying to insert a field into leads without an e-mail. However, seeds.rb is completely blank.

Here is the start of my call in terminal:

Macintosh-2:triplanding Calvino$ bundle exec rake test
Run options: --seed 15348

# Running:

EEEEEEEEEE

Finished in 0.108843s, 91.8753 runs/s, 0.0000 assertions/s.

  1. Why are these tests failing?
  2. Why is the leads even involved in a test like assert true.

Thank you in advance!

Writing test cases for Math.Random(); codewars kata

I am authoring my first simple Kata on Codewars. The objective of the Kata is to fix the code.
This is the complete working solution,

function yourFutureCareer() {
  var career = Math.random();
    if (career <= 0.32) {
        return 'FrontEnd Developer';
    } else if (career <= 0.65) {
        return 'BackEnd Developer';
    } else {
        return 'Full-Stack Developer';
    } 
} 

yourFutureCareer();

This is initial solution the user will work on,

function {
var : Math.random();
    if (career <= 0.32) {
        return = FrontEnd Developer
     else if (career <= 0.65) 
        return : BackEnd Developer,
    } else {
        return 'Full-Stack Developer'
    }

    yourFutureCareer();

In order to publish the Kata, I have to provide Test Cases that will determine if the solution is valid or not. I've tried writing a first Test Case,

Test.assertSimilar(yourFutureCareer(), yourFutureCareer(), 'true')

Sometimes the test fails,

Expected: FrontEnd Developer, instead got: BackEnd Developer

Sometimes the test passes,

Test Passed: Value == Full-Stack Developer

So, how to write test cases so that the solution can be validated? Any example code or sample would be helpful.

How to test GCM notifications without app?

I am currently implementing a push functionality using Amazon SNS in my backend. Now, I would like to write tests for the backend and make somehow sure that the published notifications get delivered to the endpoint (GCM mobile device).

Is there a way to get a mock registrationID from the Google dev console and check an inbox if any notifications actually arrived? All without ever building an app?