samedi 31 janvier 2015

"lldb" Error When Testing In-App Purchase

Please be patient. This is my first time setting up an in-app purchase and I will try and provide as much information as I can. Instead of grooming the internet for someone else's code I ended up purchasing a class from infinite skills specifically on how to add a non-renewing subscription in-app purchase to my app. Their class was outdated, and come to find out, the "follow along" project files did not download. So I did a lot of research and this is what I came up with:




  1. I created an in-app purchase in itunes, the in-app identifier matches the identifier in my .m coding.




  2. I created a new provisioning profile and enabled in-app purchases and the icloud to manage the backend for the purchase. When I returned to the app i enabled icloud and made sure in-app purchases was turned on in the project target.




  3. I created a view controller, added buttons and for the subclass I used SKStoreProductViewController. That View Controller looks like this: in-app View Controller




  4. I imported the storekit and the SK delegates.




It crashes when I hit the tabbarbutton from my home view to bring me to the in-app view controller. error


Finally the coding: InAppViewController.h:



#import <StoreKit/StoreKit.h>

@interface InAppViewController : SKStoreProductViewController

@end


InAppViewController.m:



//
// InAppViewController.m
// Contractor Rich
//
// Created by Joshua Hart on 2/1/15.
// Copyright (c) 2015 Code By Hart. All rights reserved.
//

#import "InAppViewController.h"
#import <StoreKit/StoreKit.h>

@interface InAppViewController ()<SKProductsRequestDelegate, SKPaymentTransactionObserver>

@property (weak, nonatomic) IBOutlet UIButton *btnBuyAccess;
@property (weak, nonatomic) IBOutlet UIButton *btnPremiumFeature;
@property (weak, nonatomic) IBOutlet UILabel *lblStatus;

@property (strong, nonatomic) SKProduct *product;
@property (strong, nonatomic) NSUbiquitousKeyValueStore *keyStore;
@property (strong, nonatomic) NSDate *expirationDate;

- (IBAction)btnBuyAccessTouched: (id)sender;

-(void)getProductInfo;


@end

@implementation InAppViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_btnBuyAccess.userInteractionEnabled = NO;

_keyStore = [[NSUbiquitousKeyValueStore alloc] init];




_expirationDate = [_keyStore objectForKey:@"expirationDate"];
NSDate *today = [NSDate date];
if (_expirationDate == nil)
_expirationDate = today;

if (_expirationDate > today) {
_btnPremiumFeature.userInteractionEnabled = YES;
}
else {
_btnBuyAccess.userInteractionEnabled = YES;

[self getProductInfo];
}
}

-(void) getProductInfo{

if ([SKPaymentQueue canMakePayments])
{
NSMutableArray *productIdentifierList = [[NSMutableArray alloc] init];

[productIdentifierList addObject:[NSString stringWithFormat:@"com.joshua.contractorrich.inapp"]];

SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithArray:productIdentifierList]];

request.delegate = self;
[request start];
}
}

-(void) productsRequest: (SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *products = response.products;

if (products.count != 0)
{
_product = products[0];
_btnBuyAccess.userInteractionEnabled = YES;
_lblStatus.text = @"Ready for Purchase!";
}else{
_lblStatus.text = @"Product was not Found!";
}
products = response.invalidProductIdentifiers;
for (SKProduct *product in products)
{
NSLog(@"Product not found: %@", product);
}

}



- (IBAction)btnBuyAccessTouched: (id)sender {

SKPayment *payment = [SKPayment paymentWithProduct:_product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
_btnPremiumFeature.userInteractionEnabled = YES;
_lblStatus.text = @"Purchase Completed!";
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;

case SKPaymentTransactionStateFailed: NSLog(@"Transaction Failed!");
_lblStatus.text = @"Purchase Failed!";
[[SKPaymentQueue defaultQueue]
finishTransaction:transaction];

default:
break;
}
}
}

-(void) setExpirationDate {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:3];
NSDate *expirationDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];
[_keyStore setObject:expirationDate forKey:@"expirationDate"];
[_keyStore synchronize];
}

-(void) initializeStore {
[_keyStore setObject:nil forKey:@"expirationDate"];
[_keyStore synchronize];
}



- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end


Please understand this is my first time trying this. What may seem stupid is still the learning phase for me. Thank you!


tips for managing a project with multiple machine apps

I'm planning a project that includes three apps:



  • SERVER APP - single machine on aws

  • ADMIN APP - single machine on aws

  • CLIENT APP - many machines on many countries


Theses apps will be developed by different teams.


Whats best practices to manage this scenario? Consider versioning, repositores, testing, different teams, etc...



  1. Should I keep all apps inside a single repository? So SERVER team will have access to CLIENT app, this is wrong.

  2. Should I keep each app with your repository? So testing, versioning and deploy will be a pain.


In TDD, who writes the tests - the developers or the QA/testers?

I've been recenently reading a lot about TDD/BDD and all that good stuff. Writing tests before you code is really an idea that I like.


But, to my question. Who writes the unit-tests? The QA or the developers?


Executing DB dump dynamically in codeception acceptance helper

I want to execute different dump file for different codeception tests. Right now Db dump file is being executed from shell_exec command in _before method of AcceptanceHelper, that executes before each and every acceptance test. Something like suggested here. There are alot of tests in the app. So, the flow is as follows



- tests/acceptance/application/<contains alot of tests related to application>

- tests/acceptance/location/<contains alot of tests related to location>


Both test directories /application/ and /location/ uses same AcceptanceHelper. So, what i want is a different executable dump file for all of the tests inside /application/ directory than that of /location/ tests.


Think of something like Get current running test name. Let's say application_dump.sql for all tests inside /application/ directory and location_dump.sql for all tests inside /location/ directory.



P.S: Using a different suite for application and location is ideally not what i am looking for.

What is a right way to deal with tests, temporary files and version control

I use Ruby for writing a code, test it with Cucumber and Rspec and control versions with Git. But here are some unclear things for me. E.g. temporary files, created by tests. I don't want to track their changes with every commit. So, what way I should use for that:



  1. Locate temporary files inside project folder and use some Git tricks for ignoring changes. gitignore is not useful, because I need some files to be in the place, when tests are started.

  2. Locate temporary files in the /tmp. It gives some unclear for test environment, though.

  3. Any other ways deal with that?


How to test custom Polymer expressions?

How to test custom Polymer expressions? An example of the expression below.



PolymerExpressions.prototype.uppercase = function(input) {
return input.toUpperCase();
};

Seeding before Rails feature test

I have a number of feature tests which rely on a fair amount of data being in the database. I have put this data in a seed file and am trying to call it in the before block in my tests



feature 'capybara tests' do
self.use_transactional_fixtures = false

before do
DatabaseCleaner.strategy =:truncation
DatabaseCleaner.clean
MyApp::Application.load_tasks
Rake::Task['db:seed:capybara'].invoke
end

scenario 'one' do
end

scenario 'two' do
end
end


The above doesn't work. Scenario two has an empty database. The before block is being called just before running scenario two, but the seed rake task is silently not executing so I'm left with an empty database.


Can someone tell me why this is happening and how to fix it? Thanks


Test isolation with many requests on Symfony 2.6

My project uses Symfony 2.6. I am trying to isolate my test in order to don't commit any change on my database.


I manage to isolate my test with only one request. But when there are many of them, it doesn't work and I can't manage to find why. Any ideas ?


Here is my testController code :



use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class RequestControllerTest extends WebTestCase{

protected $client;
protected $entityManager;

protected function setUp(){
parent::setUp();
$this->client = static::createClient();
$this->entityManager = $this->client->getContainer()->get('doctrine')->getManager();
$this->entityManager->beginTransaction();
}

protected function tearDown(){
parent::tearDown();
$this->entityManager->rollback();
$this->entityManager->close();
}

// This test is working just fine : the request isn't deleted from database at the end
public function testIsolationOK(){
$this->client->request('DELETE', self::WEB_SERVICES_EXISTING_REQUEST_URL);
$this->client->request('GET', self::WEB_SERVICES_EXISTING_REQUEST_URL);
}

// But this one isn't working : the request is deleted from database at the end
public function testIsolationNOK(){
$this->client->request('GET', self::WEB_SERVICES_EXISTING_REQUEST_URL);
$this->client->request('DELETE', self::WEB_SERVICES_EXISTING_REQUEST_URL);
}

}

vendredi 30 janvier 2015

C# RichTextBox Line-by-line scan

Hey Im creating my own coding language and I already have the entire application set up with save, open, close, new, etc.


In order for the "Run" part to work, I need a way to scan and test every single line in richTextBox1.


Maybe for past Java users, something along the lines of the "java-util-scanner," but easier to use for testing each line.


Does anyone know a way to do this, where a string "scannedString" would be tested as so:



if(scannedString == "#load(moduleFiles)") {
//action here
}
string scannedStringNextLine = ???
if(scannedStringNextLine = "") {
//action here
}


Eventually it would look more like this:



if(scannedString == "code1" || scannedString == "code2" etc... ) {
if(scannedString == "code1") {
//action here
}
} else {
//error message
}


hope this is enough information...


How to correctly use TestFX with FXML

I am attempting to integrate the TestFX framework into my application. I have run into an issue that I can't run multiple tests on the same fxml view. The GuiTest doesn't appear to tear down correctly and it leaves the stage open, causing errors on the second test.



public Parent getRootNode() {
FXMLLoader loader = new FXMLLoader();
Parent node = null;
try {
node = loader.load(
this.getClass().getResource("SampleWorkSpace.fxml").openStream());
} catch (IOException e) {
// Some error handling }
return node;
}


When this runs it throws a timeout error: java.util.concurrent.TimeoutException: Timeout waiting for task. However, my test continues from there.


Then I have the following test:



@Test
public void performANameSearch() {
TableView tv = (TableView)find("#resultsTable");
click("#NameTextField").type("Some Random Name");
click("#searchButton");
waitUntil(tv, TableViews.containsCell("Some Random Name"));
Assertions.verifyThat(tv, TableViews.containsCell("Some Random Name"));
}


This test works just fine.


However when I add test two:



@Test
public void performAnIDSearch() {
TableView tv = (TableView)find("#resultsTable");
click("#idTextField").type("1234567");
click("#searchButton");
waitUntil(tv, TableViews.containsCell("1234567"));
Assertions.verifyThat(tv, TableViews.containsCell("1234567"));
}


The test launches a second stage, types the ID in the correct field, invokes the correct search. However the waitUntil() gets the first TableView in the scene graph, causing it to timeout.


I have attempted to close the active window at the end of the first test - but that always closed before the assertions, so it would hang.


I tried breaking them into a suite, but that had the same issues as noted above.


I am unsure what else to try - I really don't want to have a single test per view as that would get very large, very quick....


HP-ALM Adding Test Cases With REST API

I'm looking to automate adding new test cases into ALM using the REST API. I didn't find anything in the documentation to help me achieve this and I was wondering if anyone else had any success with it.


Syntax error causing model validation warning

Developing a Django 1.6 application, and getting a unexpected error. I had a syntax error in my code:



if:
# some stuff
if else:
# some more stuff


Clearly an error, that's not the issue (should be just else:). The issue is that when I went to run my tests (before noticing the problem), this was the error message I got:



ƒ: python manage.py test
Creating test database for alias 'default'...
CommandError: One or more models did not validate:
member.company: 'mc' has a relation with model datamining.MergedCompany, which has either not been installed or is abstract.
member.headshotwithcoloredbg: 'question' has a relation with model contest.Question, which has either not been installed or is abstract.


This has nothing to do with the problem, as far as I can see. The file that had the error is in a different app from the models that failed validation. There's really no connection.


I happened to notice the syntax error soon after and fixed it, but this behavior is worrisome.


Can anyone explain why a syntax error wasn't raised in this case? It's worrisome since the message gives very little guidance on where to look or what was actually wrong.


Thanks!


golang testing [no test files]

I'm creating a simple test within my package directory called reverseTest.go



package main
import "testing"

func TestReverse(t *testing.T) {
cases := []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
}
for _, c := range cases {
got := Reverse(c.in)
if got != c.want {
t.Errorf("Reverse(%q) == %q, want %q", c.in, got, c.want)
}
}
}


whenever i try to run it the output is



exampleFolder[no test files]


this is my go env



GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/juan/go"
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CXX="g++"
CGO_ENABLED="1"


Any help will be greatly appreciated. Thanks!!


Testing the result of Sidekiq background job with Rspec

I have a model method that sends info to a sidekiq background job. The background job changes some attributes on an object. I want to test to make sure this is happening as expected.


The Rspec test I wrote creates the object, then runs the method and expects the attribute to be changed. However, the attribute isn't changing and I suspect that the background job isn't running in the Rspec test. Anyone know how to make sidekiq process a job in the test so that it actually changes the attributes


Web service for testing client code response to error conditions and delays?

I am building an application that consumes several web services. I am trying to test this portion of the application. Specifically, I am trying to test how my code response to errors and delays from the web service.


I have seen a web service that lets you pass in a delay and/or an error code via URL parameters. It then responses with that error code after the designated delay. Unfortunately, I have lost that link. I have done numerous Google searches and have not been able to find it.


Does anyone know of a web service that can be called from a client and will generate designated error responses after designated delays?


Protractor: creating an array from nested elements

I'm trying to get elements in my DOM and return them as an array. They are nested. I want protractor to return something like this:



{
category_title: "cat1",
items: {item_title: "item1"}, {item_title: "item2"}
},
{
category_title: "cat2",
items: {item_title: "item1"}, {item_title: "item2"}
}


DOM:



<div ng-repeat="category in categories">
<div id="category-title">{{ category.title }} </div>
<div ng-repeat="item in category.items">
<div id="item-title">{{ item.title }} </div>
</div>
</div>


This is what I'm trying in Protractor:



return element.all(by.repeater("category in categories")).map(function(elm) {
var category_title = elm.element(by.id('category-title')).getText(),
var t = {
category_title: category_title,
dimensions: {}
};
// After this part, I'm lost...
return elm.all(by.repeater("item in category.items")).map(function(elm) {
return {
category_title: category_title,
dimension: elm.element(by.id('item-title')).getText(),
}
});
});

How to use Test::Simple conditionally?

I would like to add the option to test my Program conditionally with a command line option like --test which execute &test.


Unfortunately even if I add use Test::Simple tests => 1 inside the &test subroutine, Perl think I want to do the tests everywhere else.


Is it possible to use Test::Simple or even Test::More only when needed?


Specflow or BDDfy

I am looking to start using BDD in my next .NET project and I was wondering if anyone has experience using Specflow and BDDfy and which of the two they would recommend for a team that is new to BDD. This excersise will be a trial and if successful will become the BDD standard/best practice for future projects.


The team will be working with a QA and a BA, the BA will be responsible for writing user stories with the help of the QA. The QA might also help in writing the test stubs for the scenarios.


Thanks,


Chris


jeudi 29 janvier 2015

What extra features Appium gives over Selenium?

I want a single automated tool to test andorid ios and desktop web based applications. Appium only gives support for mobile applications. What features I will miss if I decide to go with Selenium and not with Appium? thank you in advance.


How does one trigger and test events on an IObservable?

I'm writing a basic UDP Server that listens for messages on a given port, massages the input a little, and triggers an event with the processed message. I would like to write tests that send a message to the server and verify that the correct event is raised.


The server looks something like this:



type UdpServer() =
let messageReady = new Event<string>()

member x.Start () = async {
let rec loop () =
let message = receiveMessage ()
messageReceived.Trigger(message)
return loop ()
return! loop ()
}

member x.MessageReady = messageReady.Publish


I'd like to write a test something like this:



[<Test>]
let ``Should process message correctly`` () =
let server = new UdpServer()
server.Start() |> Async.Start
sendMessageToServer "test message"

// This will wait indefinitely since the message was already sent in the previous line
let processedMessage = server.MessageReady |> Async.AwaitEvent |> Async.RunSynchronously
processedMessage |> should be "expected output"


How do I send a message to the server and then test that the MessageReady event was triggered correctly? I could use a mutable to store the value, but this doesn't seem like the F# way:



let mutable processedMessage = ""
server.MessageReady |> Observable.subscribe(fun m -> processedMessage <- m)
sendMessageToServer "test message"
processedMessage |> should be "expected output"

If ElseIf in Robot Framework

I want get value from Keyword By use else if.


example



String text = ""
If variable > 5
text = "one";
else if variable <5
text = "two";
else
text = "three";




In Robot Framework


I use code.



${txt} Set Variable
${txt}= Run Keyword If ${lenght} > 5 Some Keyword
\ ELSE IF ${lenght} < 5 Some Keyword
\ ELSE Some Keyword
Log ${txt}




EROR !!



In Keyword ELSE IF ; Keyword name cannot be empty

Automated testing of webrtc application?

I am developing a conferencing app, details:




  • target: chrome browser




  • server: node.js ( currently windows env)




simplest test scenario would be:



  1. open two browser tabs( open browser if need be)

  2. emulate button click on both.

  3. emulate accept getUserMedia request( hardest part)

  4. more emulation stuff and reading JavaScript variable values and verifying them.


Till now, I have been doing manual testing for all of this, but decided that it would be impractical for the long run. I have not done much automated testing( just a bit of unit testing). Initially, i thought mocha would do the job, but beginning to think it is not enough.


I need some pointers as to what are tools or alternate test frameworks needed to achieve browser starting, tab opening and giving media sharing permissions.


create a post controller spec test

I am doing a controller test but it seems that spec.rb is wrong. Do you have a suggestion ?


This is my posts_controller.rb



class PostsController < ApplicationController

def create
@post = Post.new(params[:post])
if @post.save
redirect_to @wall
end
end

def destroy
@post.destroy
end

end


and this is my posts_controller_spec.rb



require 'rails_helper'

describe PostsController do

describe "#create" do
it "saves the new post in the wall" do
post :create, { wall_id: '1', content: "Some text I would like to put in my post" }

end
end

describe "#destroy" do
it "deletes the post in the wall" do

end
end
end


could you please help me to correct my spec.rb? Thanks


using APITestCase with django-rest-framework

I followed this code:



from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase

class AccountTests(APITestCase):
def test_create_account(self):
"""
Ensure we can create a new account object.
"""
url = reverse('account-list')
data = {'name': 'DabApps'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, data)


Found in the django-rest-framewok docs here:


http://ift.tt/1zhUdHk


I created a single Model with a single field name, and I am still getting a "bad request 400 error". The view and reverse name is also set up correctly, and I have manually tested viewing the URL with success. I don't have Authentication enabled


And can't figure out if I am missing a step?


Does anyone have a working example of a django-rest-framework APITestCase create model object test code snippet?


Thanks


Stimulate android devices

I would like to develop an application allowing to stimulate several parameters of my device (like RAM, SD, l'EMMC, CPU, GPU...)


Would anybody know how could I implement that please?


Thanks in advance


Rails-4 missing dom_id method in cucumber step definition


  • OS = CentOS-6.6

  • Ruby = 2.0.0

  • Rails = 4.2.0

  • Cucumber = 3.1.18

  • Capybara = 2.4.4


We are moving an existing RoR-3.2 to 4.2. We have added in the necessary gems to ease the pain of many of the deprecations:



# Temporary gems to get to Rails4
gem 'protected_attributes'
gem 'rails-observers'
gem 'actionpack-page_caching'
gem 'actionpack-action_caching'
gem 'activerecord-deprecated_finders'
gem 'dynamic_form'


However, I am somewhat stymied with this situation involving one of our Cucumber step_definitions:



When /deletes? the "(.*)" correspondent/ do |row|
this_correspondent = Correspondent.find_by_correspondent_common_name(
"my correspondent number #{row.hll_words_to_i}")
within("td#" + dom_id( this_correspondent, :delete )) do
click_link( "Destroy Correspondent" )
end
end


Which produces this error:



(::) failed steps (::)

undefined method `dom_id' for
#<Cucumber::Rails::World:0x000000089c92f0> (NoMethodError)
./features/app/models/correspondents/step_definitions
/correspondent_steps.rb:43:in
`/deletes? the "(.*)" correspondent/'
features/app/models/correspondents/correspondent.feature:68:in
`When they delete the "first" correspondent'


Testing this view code:



<% for correspondent in @correspondents %>
<tr id="<%=dom_id(correspondent, :row_1)%>">
<td><%=h correspondent.correspondent_common_name.titlecase -%></td>
<td></td>
<td><%=h correspondent.correspondent_legal_form -%></td>
<!-- See http://ift.tt/1Dl518s -->
<!-- and http://ift.tt/1Dl518s -->
<td><%= "%06d" % correspondent.id -%></td>
<td id="<%=dom_id(correspondent, :show)%>"><%= link_to 'Show Correspondent',
correspondent -%></td>
<td id="<%=dom_id(correspondent, :edit)%>"><%= link_to 'Edit Correspondent',
edit_correspondent_path(correspondent) -%></td>
<td id="<%=dom_id(correspondent, :delete)%>"><%= link_to 'Destroy Correspondent',
correspondent, :confirm => 'Are you sure?', :method => :delete -%>
</td>
</tr>


The Rails upgrade guide says this:



Rails 4.0 deprecates the dom_id and dom_class methods in controllers (they are fine in views). You will need to include the ActionView::RecordIdentifier module in controllers requiring this feature.



Which I am fine with. I cannot find any occurrence in the existing code base where either method is explicitly used outside of view templates.


However, I am not sure how I am supposed to test for view elements using dom_id() using Cucumber. Is there something I need to add to the development/test gems to get back this behaviour?


How to test Uber type of application for both driver and rider?

Can someone explain me about tools and technology i can use to test an application like "Uber". I would like to test both driver and user application on Android and iPhone.


A small description about tools/technology and how will help me.


Cannot run test execution using watir/taza/rspec

I'm using Unix system and trying to run Watir/Taza/RSpec test execution.


I just perform commands for creating taza structure, site, homepage and flow:



> taza create structure
> taza site google
> taza page home google
> taza flow search google


Then I run test using next command:



rake spec:isolation:google


but I get an error:



rake aborted! LoadError: cannot load such file -- taza/tasks /Users/ismotrov/works/test/Rakefile:3:in require' /Users/ismotrov/works/test/Rakefile:3:in' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/rake_module.rb:28:in load' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/rake_module.rb:28:in load_rakefile' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:689:in raw_load_rakefile' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:94:in block in load_rakefile' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:176:in standard_exception_handling' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:93:in load_rakefile' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:77:in block in run' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:176:in standard_exception_handling' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/lib/rake/application.rb:75:in run' /Library/Ruby/Gems/2.0.0/gems/rake-10.4.2/bin/rake:33:in' /usr/bin/rake:23:in load' /usr/bin/rake:23:in'



Who knows what to do? And another moment I would like to dicuss - in file config/config.yml I have the following:



---
browser: firefox
driver: watir_webdriver


But on my Mac I don't have Firefox installed. How can I use this with, for example, Chrome and can It cause my problem?


Thanks in advance!


Running JavaScript tests

I am overwhelmed by the topic of how to test JavaScript applications and feel like I'm in need of a simple explanation.


While I was trying to figure it out for myself I lost track of all the terms and technologies. I came as far as understanding that there are multiple test suites and libraries like Karma and Jasmine and that there are different types of tests, such as unit tests and end-to-end ones.


I would like to begin with unit tests in order to make sure a given component works fine. Yet I am unsure about the pros and cons of the different suites and how to work with them.


To put it simple, I need to know



  • Is there a test suite which is more suitable for unit tests than other ones?


  • What is the most simple way of running such a test?




  • How do the the available suits differ from each other?




what is the name of this design (anti-)pattern?

Recently I took a project which was initially a thick client Java application written in Swing. Later they got a requirement to support http requests. So they implemented a code like this:



public void handleRequest(...) {
if(contextPath.equals("purchase-product")) {
getMainPanel().getPurchasePanelButton().doClick();
getMainPanel().getPurchasePanel().selectProductById(productId);
if(getMainPanel().getPurchasePanel().getPurchaseButton().isEnabled()) {
getMainPanel().getPurchasePanel().getPurchaseButton().doClick();
...
}
}
....
}


My first thought was WTF. Weren't they familiar with MVC pattern?


But then I was thinking they implemented the code like this to be able to do Swing GUI tests via http requests using JMeter or SoapUI instead of complicated GUI frameworks like Squish.


My question is do people use similar technique to simplify their component tests? What is the name of this (anti-) pattern ?


rspec with different DNS server

I have a bunch of rspec test which uses external databases (I know, this is not a good idea, but there are a lot of reasons this is the best solution in this case). I've set up a different vlan with a test environment to run the tests within a isolated environment. Now I want to define that all rspec tests use a different DNS server to resolve the hostnames (to work with the dev environment). Is there something I can use?


Is it possible to use a @Profile("test") configuration to override the default?

We have a spring project which defined some classes without @Profile, like:



interface MyService {
String changeName(String name);
}

@Service
class MyService1 implements MyService {
public String changeName(String name) {
return name.toUpperCase();
}
}

@Controller
class SampleController {

@Autowired
private MyService myService;

@ResponseBody
@RequestMapping(value = "/hello/{name}", produces = "application/json")
String home(@PathVariable String name) {
return "Hello " + myService.changeName(name) + "!";
}

}


I can start a server to run it:



@EnableAutoConfiguration
@ComponentScan
@Configuration
public class Main {
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder(Main.class)
.run(args);
}
}


Then I can visit the url http://localhost:8080/hello/freewind and got the text Hello FREEWIND!.


I want to start a testing server, so I want to find a way to replace the existing MyService1 with a mock class. And I found there is a @Profile seems promissing:



@Profile("test")
@Configuration
class TestConfig {

@Bean
public MyService myService() {
return new MyService() {
public String changeName(String name) {
return "###" + name + "###";
}
};
}

}


And change Main to active profile test:



new SpringApplicationBuilder(Main.class)
.profiles("test")
.run(args);


But when I start it, it reports error:



Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type [web.MyService] is defined:
expected single matching bean but found 2: myService1,myService


If I want it work, I HAVE to change the existing code to give the MyService1 a different profile, like:



@Profile("dev")
@Configuration
class DevConfig {

@Bean
public MyService myService() {
return new MyService1();
}

class MyService1 implements MyService {
public String changeName(String name) {
return name.toUpperCase();
}
}

}


Now it will work well, but I don't want to modify the existing code.


Is there any way to use @Profile without modifying the existing code, or is there any other way to replace an existing bean with a custom bean?


Mocha Failing with "timeout exceeded"

I'm new to Mocha and I'm trying to run the tests on this code:



"use strict";

process.env.NODE_ENV = 'test';

var assert = require('assert'),
Browser = require('zombie'),
xapp = require('../app'),
app,
User = require('../models/users').User,
testMail = 'aaa@aaa.aaa',
testPassword = 'aD1$#!_é',
server;

before(function(done) {
xapp(function(sapp) {
app = sapp;
server = app.listen(3000, done);
});
});

after(function(done) {
app.closeMongo(function() {
server.close(done);
});
});

function clearDb(done) {
User.findOne({email: testMail}, function(err, user) {
if(err) return done(err);
if(!user) return done();
else {
user.remove(done);
}
});
}

describe('User signup', function() {
this.timeout(3200);

before(clearDb);

describe('Homepage Form', function() {
this.timeout(3200);
it('should load the trial form', function(done) {
Browser.visit('http://localhost:3000/', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
var form = browser.query('form[action="/users/signup"]');
assert.notEqual(form, null, 'Form on homepage exists');
assert.notEqual(browser.query("input[type=email]", form), null, 'has email input on page');
done();
});
});

it('should test the trial form', function(done) {
Browser.visit('http://localhost:3000/', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
browser
.fill('email', testMail)
.pressButton('Sign up', function(err) {
if(err) return done(err);
assert.equal(browser.location.pathname, '/users/signup', 'Links to signup page');
assert.notEqual(browser.text('h1').indexOf('Sign up'), -1, 'Title page contains "Sign up"');
var form = browser.query('form#form-signup');
assert.notEqual(form, null, 'Form on signup page exists');
var emailInput = browser.query('input[type=email]#email', form);
assert.notEqual(emailInput, null, 'has email input on signup page');
assert.equal(emailInput.value, testMail, 'email input has entered value on homepage');
done();
});
});
});
});

describe('Signup page form', function() {
this.timeout(3200);
it('should load the signup form', function(done) {
Browser.visit('http://localhost:3000/users/signup', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
var form = browser.query('form[action="/users/signup"]#form-signup');
assert.notEqual(form, null, 'Form on signup page exists');
assert.equal(form.method, "post", "Form is POST");
assert.notEqual(browser.query("input[type=email]#email", form), null, 'has email input on page');
assert.notEqual(browser.query("input[type=password]#password", form), null, 'has password input on page');
assert.notEqual(browser.query("input[type=password]#passwordConfirm", form), null, 'has password confirmation input on page');
done();
});
});

it('should sign up a test user', function(done) {
Browser.visit('http://localhost:3000/users/signup', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
browser
.fill('Email:', testMail)
.fill('Password:', testPassword)
.fill('Password confirmation:', testPassword)
.pressButton('#form-signup button[type=submit]', function(err) {
if(err) return done(err);
assert.notEqual(browser.query('.alert-success'), null, 'Has success alert');
assert.notEqual(browser.text('.alert-success').indexOf('Sign up successful'), -1, 'Found the text "Sign up successful" in alert');
done();
});
});
});

it('shouldn\'t sign up the same email twice', function(done) {
Browser.visit('http://localhost:3000/users/signup', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
browser
.fill('Email:', testMail)
.fill('Password:', testPassword)
.fill('Password confirmation:', testPassword)
.pressButton('#form-signup button[type=submit]', function(err) {
if(err) return done(err);
assert.equal(browser.location.pathname, '/users/signup', 'Still on the signup page');
assert.notEqual(browser.query('.alert-danger'), null, 'Has danger alert');
assert.notEqual(browser.text('.alert-danger').indexOf('This email address already exists!'), -1, 'Found the text "This email address already exists!" in alert');
done();
});
});
});
});
});

describe('User login', function() {
this.timeout(2500);

after(clearDb);

describe('Homepage form', function() {
this.timeout(3200);
it('should appear when we click login', function(done) {
Browser.visit('http://localhost:3000/', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
assert.equal(browser.query('form[action="/users/login"]'), null, 'No login form should be visible before we click on login');
browser.clickLink('Login', function(err) {
if(err) return done(err);
var form = browser.query('form[action="/users/login"]');
assert.notEqual(form, null, 'Login form should be visible after click on login');
assert.notEqual(browser.query('input[type=email]#email'), null, 'Has email input');
assert.notEqual(browser.query('a', form), null, 'Forgot your password?');
assert.notEqual(browser.query('input[type=password]#password'), null, 'Has password input');
done();
});
});
});

it('should not work with wrong credentials', function(done) {
this.timeout(3200);
Browser.visit('http://localhost:3000/', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
browser.clickLink('Login', function(err) {
if(err) return done(err);
browser
.fill('Email:', testMail)
.fill('Password:', (testPassword + 'a'))
.pressButton('Login', function(err) {
if(err) return done(err);
assert.equal(browser.location.pathname, '/users/login');
assert.notEqual(browser.query('.alert-danger'), null, "Has danger alert");
assert.notEqual(browser.text('.alert-danger').indexOf('Invalid email or password.'), -1, 'alert contain error message "Invalid email or password."');
done();
});
});
});
});
});

describe('Login form', function() {
this.timeout(3200);
it('should login with valid credentials', function(done) {
Browser.visit('http://localhost:3000/users/login', function(err, browser) {
if(err) return done(err);
assert.ok(browser.success, "page loaded");
browser
.fill('#form-signin input[type=email]', testMail)
.fill('#form-signin input[type=password]', testPassword)
.pressButton('Sign in', function(err) {
if(err) return done(err);
assert.equal(browser.location.pathname, '/');
assert.notEqual(browser.query('.alert-success'), null, "Has success alert");
assert.equal(browser.text('.alert-success'), '×Close You are now logged in.');
assert.notEqual(browser.link('Dashboard'), null, 'Has dashboard link');
assert.notEqual(browser.link('Log out'), null, 'Has log out link');
done();
});
});
});
});
});


This is the command I'm using:



$ mocha -b -R spec -s 1000


And it's failing with this message:



1) "before all" hook

0 passing (2s)
1 failing

1) "before all" hook:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:159:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)


Could you please help me figure out why this is caused?


I know that if I change the timeout for the test runner:



$ mocha -b -R spec -s 1000 -t 3000


The tests work. But I want to know the actual cause of this error.


Thank you!


shall we copy excel on all the machines of selenium grid

I am facing a problem. I am good in selenium webdriver. Now i wish to run my datadriven test cases on mac,linux and other machines. my window machine will be my hub. shall i need to copy excel files of my data driven test cases on each machine(say node).? As mac does not support my xls(not intalled office). Or grid will only fetch data from my machine's xls files and run test on all different mac machines.?


Are there Parameterized Test Fixtures for xunit?

Does xunit.net support "Parameterized Test Fixtures" like nunit (see example code below). Note I'm not looking for IUseFixture<T> or [Theory] because these do not provide the same functionality as Parameterized Test Fixtures



[TestFixture("hello", "hello", "goodbye")]
[TestFixture("zip", "zip")]
[TestFixture(42, 42, 99)]
public class ParameterizedTestFixture
{
private string eq1;
private string eq2;
private string neq;

public ParameterizedTestFixture(string eq1, string eq2, string neq)
{
this.eq1 = eq1;
this.eq2 = eq2;
this.neq = neq;
}

public ParameterizedTestFixture(string eq1, string eq2)
: this(eq1, eq2, null) { }

public ParameterizedTestFixture(int eq1, int eq2, int neq)
{
this.eq1 = eq1.ToString();
this.eq2 = eq2.ToString();
this.neq = neq.ToString();
}

[Test]
public void TestEquality()
{
Assert.AreEqual(eq1, eq2);
if (eq1 != null && eq2 != null)
Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode());
}

[Test]
public void TestInequality()
{
Assert.AreNotEqual(eq1, neq);
if (eq1 != null && neq != null)
Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode());
}
}

Automating the mobile browser on Android with Appium

I am writing a simple test to navigate to a website on a mobile browser, mostly to get an understanding of Appium. I am using an android emulator. My code looks like this:



import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileBrowserType;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.URL;

public class DLMobileTest
{
private WebDriver driver;

@Test
public void loadingSinglePageTest() throws Exception{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("platformVersion", "5.0.1");
capabilities.setCapability("deviceName", "Nexus 7");
capabilities.setCapability("browserName", MobileBrowserType.BROWSER);
driver = new AndroidDriver(new URL("http://ift.tt/1eWSHgW"), capabilities);
driver.get("http://en.wikipedia.org");
driver.quit();
}
}


When I run the test, the emulator's browser briefly starts, but before it navigates to the Wikipedia site I'm aiming for, I get this:



org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Did not get session redirect from Chromedriver) (WARNING: The server did not provide any stacktrace information)


I'm not sure what my mistake is here. Any help is appreciated.


mercredi 28 janvier 2015

Testing 3rd party package in golang

I'm new to golang and trying to write a simple learning app using the facebook package from http://ift.tt/15WS2zh.


I was able to get the package and connect to facebook and hit the facebook API. This is great but testing is my concern.


At first I was simply calling the method and creating a facebook object inside of it. Then after some research I tried passing in the facebook method I wanted to mock. Realizing there were multiple methods I needed, I am convinced that passing an interface is the right way to go.


So I tried creating interfaces that the package would implement.



type IFbApp interface {
ExchangeToken(string) (string, int, error)
Session(string) IFbSession
}

type MyFbApp struct{}

func (myFbApp *MyFbApp) ExchangeToken(token string) (string, int, error) {
return myFbApp.ExchangeToken(token)
}

func (myFbApp *MyFbApp) Session(token string) IFbSession {
return myFbApp.Session(token)
}

type IFbSession interface {
User() (string, error)
Get(string, map[string]interface{}) (map[string]interface{}, error)
}

type MyFbSession struct{}
func (myFbSession *MyFbSession) User() (string, error) {
return myFbSession.User()
}

func (myFbSession *MyFbSession) Get(path string, params map[string]string) (map[string]string, error) {
return myFbSession.Get(path, params)
}

func Test() {
Facebook(fb.New("appId", "appSecret")); // fb calls package
}

func Facebook(fbI IFbApp) {
fbI.ExchangeToken("sometokenhere");
}


I cannot compile this code since I get an error



cannot use facebook.New("appId", "appSecret") (type *facebook.App) as type IFbApp in argument to Facebook:
*facebook.App does not implement IFbApp (wrong type for Session method)
have Session(string) *facebook.Session
want Session(string) IFbSession


Switching IFbSession to *facebook.Session would make it compile of course but then I need to mock methods from the Session struct as well.


Anyone have any tips?


Thanks.


what should be test input data for a function to ensure that function works fine for complete allowed range

I have a function f(n) which returns sum from 1 to n ie



f(1)=1
f(2)=3
f(3)=6


Suppose this function have some issue and n can range from 1 to 100000.

How can i test it by providing minimum number of test cases. like n=1 can be 1 test case. n=50 can be another test case.

I mean is there any algorithm which can generate what all inputs can i test to ensure that all input from 1 to 100000 are working fine.


How to import other js files in casperjs

Basically,I have extracted the re-usable functions into a file 'utility.js'.I want to import this file into each test script.I'm following the documentation here


When i try the above mentioned approach,I'm getting the following error.



'undefined' is not a function



Folder structure is like this



utility.js
test1.js
test2.js


Test file has following code as suggested by the above documentation



var require = patchRequire(require);
var helper = require('utility');


and I access the function in utility.js as follows helper.fn_do_something()


I tried to use other methods provided by casperJS,like



casper.options.clientscript = [relativepath];


But that didn't help.I'm getting the same error.


I'm using PhantomJS 1.9.8.


How to automate testing of Pivotal CRM

Has anyone managed to find an automation framework/tool that can inspect Pivotal CRM? I have looked at numerous frameworks and tools and none are able to hook into the application to provide any useful information. QTP has come the closest with the ability to locate most buttons, but still a lot of items that are displayed are not accessible.


Django: How to associate a user with a request factory

I am writing some tests for a form on a Django site. I want to test that a logged in user is able to use the form assuming correct input. To that end, I am using a Django request factory. I can't seem to get my test user logged in though. That, or I'm not even making the request correctly. I'm not sure. Relevant code below:



def create_user():
username = 'User '+id_generator()
return User.objects.create(username = username, password = 'password')

def test_can_register_deck(self):
t = create_empty_tourney()
u = create_user()
d = create_deck(u)
rf = RequestFactory()
request = rf.post(reverse('tourney:tourney', args=(t.slug,)),{'deck' : d})
request.user = u
response = self.client.get(reverse('tourney:tourney', args=(t.slug,)), request)
self.assertEqual(response.status_code, 200)


The request has to think the user is logged in, or the rest of the test won't work. This throws no errors, but I'm not even sure my response is utilizing the request correctly. Am I correctly telling the test to "make a post request to the tourney page as this user, and try to submit a deck"?


How can I test my project using testFX

I'm a student working on a small javaFX project and I'm really new on testing a Software specially with GUI. I want to know how can I provide the method getRootNode with my rootNode from my GUI. I'm using testFX as framework


public class ButtonTest extends GuiTest {



@Override
protected Parent getRootNode() {
return null;
}


}



public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/PhotoOverview.fxml"));

Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");

stage.setTitle("Easy Manager");
stage.setScene(scene);
stage.show();
}

/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}


}


Using ActivityInstrumentationTestCase2 to select a menu item?

I am trying to write test cases for my main activity. All my main activity shows right now is a list view, and I was able to write tests to start the activity and make sure the list view was created by doing this:



public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity>{
private MainActivity mainActivity;
private ListView mListView;

public MainActivityTest(){
super("MainActivityTest", MainActivity.class);
}

@Override
protected void setUp() throws Exception {
super.setUp();
mainActivity = this.getActivity();
mListView = (ListView) mainActivity.findViewById(R.id.prescriptionListView);
}

public void testPreconditions(){
assertNotNull(mListView);
}
}


What I would like to do next is open the options menu and select an item. When that item is selected, it should create an intent and start a new activity. However, I can't figure out how to reference the menu. I have tried a few things:



public void testOptionItem(){
// Not sure how to use this
mainActivity.getMenuInflater();

// Not sure if this actually opens the menu
// app closes to quickly, but even if it does I don't know how to select item
mainActivity.openOptionsMenu();

// I get a null reference exception on the menu item.
mainActivity.onOptionsItemSelected((MenuItem) mainActivity.findViewById(R.id.action_addPrescription));
}


How can I obtain a reference to the menu and select an item?


How to write Unit test, branch test, condition, branch and relational operator, definition use criteria for class writen in JAVA

I have to write unit test, branch test, condition.... but i have no idea how to do that Can someone help me ? I am beginner and i really don't understand testing... I read some simple examples given by the professor but this one...



class IntegerArray {

private int a[];

public IntegerArray(int a[]) {
this.a = Arrays.copyOf(a, a.length);
}

private IntegerArray(int a[],boolean to_copy) {
if ( to_copy )
this.a = a;
else
this.a = Arrays.copyOf(a, a.length);
}

public int length() {
return a.length;
}

public int getElementAt(int i) {
return a[i];
}

public int sum() {
int sum = 0;
for ( int e : a ) sum += e;
return sum;
}

public double average() {
return sum()*1.0/length();
}

public IntegerArray getSorted() {
int sorted_a[] = Arrays.copyOf(a, length());
Arrays.sort(sorted_a);
return new IntegerArray(sorted_a);
}

public IntegerArray concat(IntegerArray ia) {
int res_a[] = new int[a.length+ia.a.length];
System.arraycopy(a, 0, res_a, 0, a.length);
System.arraycopy(ia.a, 0, res_a, a.length, ia.a.length);
return new IntegerArray(res_a,true);
}

public String toString() {
return Arrays.toString(a);
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(a);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IntegerArray other = (IntegerArray) obj;
if (!Arrays.equals(a, other.a))
return false;
return true;
}
}

Is there a way to set toast messages in UiAutomator as an object to look for when running automation?

Is there a way to set toast messages in UiAutomator as an object to look for when running automation?


I am doing automation for testing an android app and I have not found any solution to check whether the toast appears or not. I have read on How to test for the appearance of a Toast message that it can be done like



if(someToast == null)
someToast = Toast.makeText(this, "sdfdsf", Toast.LENGTH_LONG);
boolean isShown = someToast.getView().isShown();


but I am not able to make a Toast as an UiObject. Also on google group http://ift.tt/1CMWYTQ


it is mentioned that some API is to launch for that but I have got no update.


DataChannel WebRTC Test Latency and Performance

I would like to run some tests to check the latency and performance of the WebRTC API's , in particular by using an one-to-one and many-to-many network topology, with the use of RTCDataChannel. I would ask which tools i should use and if there is some advice to how do this. Thanks to all.


mock test failing while doing mvn install

I have below test which works successfully while executing in IDE but when I do mvn install it fails with below msg



org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.


Below is the test class:



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = SpringockitoContextLoader.class,locations={"classpath:conf/test-context.xml"})

public class ServiceTest
{
@ReplaceWithMock
@Autowired
private Object1 object1

@Autowired
private Service service;

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

@Test
public void test()
{//below line is failing while doing mvn install
Mockito.when(object1.validate(String validateMe)).thenReturn(true)
}

}


Do I need any other extra configuration to have it work in maven ?


Why it is important to map requirements with integration testing?

I am doing small research about importance of mapping requirements with integration testing. I have read several research papers, but I could not find some good industrial examples. Could you please give some good example, hint or some links to research papers of importance or challenge of mapping (traceability) requirements (software/system) with integration testing? Why is it important to have mapping between them?


Thank you very much in advance.


How to test a service using $resource in angular

I have the following setup (forgive me if you don't use CoffeeScript)


Authentication service



class Authentication
constructor: ($resource) ->
@$resource = $resource

authenticate: (user) ->
response = @$resource('/api/v1/login', { email: user.email, password: user.password }).save()
return response.$promise


Session controller (uses Authentication service)



class SessionController
constructor: (Authentication, $cookieStore, $location) ->
@Authentication = Authentication
@$cookieStore = $cookieStore
@$location = $location

login: ->
promise = @Authentication.authenticate(@user)
promise.then(
(response) =>
# How do I test to validate the following:
@a= true
(response) =>
# And how do I test to validated this:
@a = false
)


My question


What I can't figure out is how to test this? I would like the test to validate the value of @a after calling @Authentication.authenticate(@user)


Thank you.


Angular integration testing

I'm not having much luck googling this, so, here goes...


I've got an Angular application, which talks to an node (express) API, and we've got no integration testing - making it too easy to 'break' the integration between the two parts of the system, having to test by hand is obviously far from ideal.


I wanted to avoid Protractor (we've got a really rich UI in the angular app, and it's proving difficult get protractor to play nice). As it stands, we have a fairly standard structure for an angular app - controllers that feed data to views (using 'Controller as'). The controllers interact with services, services do all the $http calls.


Ideally, I'd test from the controllers 'down'. Is there anything out there to support this kind of approach?


The most promising approach appears to be stopping angular-mocks from injecting it's own mocked $http/$httpbackend. But I'm keen to hear your thoughts on this and alternative approaches.


Thanks, Dave


First step in Mocha Testing

I want to learn Mocha/chai testing. But i'm never test before. i found this tutorial: http://ift.tt/1zXMNvQ


And when i reach "Run Test" and do "mocha" command for the first time. I get an error:



$ mocha

C:\Users\Tomasz\Desktop\Tests\test\test.js:1
(function (exports, require, module, __filename, __dirname) { test.js
^
ReferenceError: test is not defined
at Object.<anonymous> (C:\Users\Tomasz\Desktop\Tests\test\test.js:1:63)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at C:\Users\Tomasz\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:185:27
at Array.forEach (native)
at Mocha.loadFiles (C:\Users\Tomasz\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:182:14)
at Mocha.run (C:\Users\Tomasz\AppData\Roaming\npm\node_modules\mocha\lib\mocha.js:394:31)
at Object.<anonymous> (C:\Users\Tomasz\AppData\Roaming\npm\node_modules\mocha\bin\_mocha:394:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3


What should i do?


I there any straightforward way to backtrack from rpsec to test unit mid project?

I have been weighing up the pro/cons of learning rspec (which I think is pretty good) to using Test unit, which I learned while following Michael Hartls excellent tutorial on building a rails application. I am in the middle of my own project and I have set up rspec but I really want to go back to using test unit (I am a rails newbie). Aside from uninstalling the gems, is there anything else I need to do. Is there an easy automated way to generate all the controller, model and view test files (albeit in blank form) that would have been generated as I built the application.


Not able to locate the text field inside the iframe using protractor


<iframe class="embedded-tax-form" scrolling="no" seamless="seamless" src="http://ift.tt/15Td7KY" id="iFrameResizer1" style="overflow: hidden; height: 3971px;"></iframe>
<input id="input.ReportingParty.Identifiers.TaxFileNumber.Identifier" type="text" ng-model="form.fields['ReportingParty.Identifiers.TaxFileNumber.Identifier'].value" ng-change="run()" class="form-control ng-pristine ng-valid ng-touched" ng-readonly="form.fields['ReportingParty.Identifiers.TaxFileNumber.Identifier'].source === 'calculation'" source-selection="ReportingParty.Identifiers.TaxFileNumber.Identifier">


I have text field embedded inside the Iframe and I'm using the Protractor and written the code as below, as the latest protract we need not have to instantiate the instance:



it('should show the functioning input directive example', function () {
browser.get('http://ift.tt/1uAKIir');
// Ensure that the page is loaded before trying to switch frames.
browser.waitForAngular();
browser.switchTo().frame('embedded-tax-form');
var nameInput = element(by.model("form.fields['ReportingParty.Identifiers.TaxFileNumber.Identifier'].value"));
nameInput.sendKeys('222);
});


when I run this, complete page gets refreshed and says



ReferenceError: iframe is not defined NoSuchFrameError: no such frame



I checked whether element is present writing on console and used elementory:



elementArrayFinder_: { getWebElements: [Function],
actionResults_: undefined,
locator_: { using: 'css selector', value: '.embedded-tax-form' },
click: [Function],


Let me know, how I should handle in protractor latest. Please let me know if you need any more information on this.


Testing Input::hasFile in Laravel

I'm using



if (Input::hasFile('index')) doSomething();


to check if the file was uploaded.


Now I wanna write a PHPUnit test case where the system needs to behave like the "index" file was uploaded.



Input::shouldReceive('hasFile')->andReturn(true)


does not work.


Also there's a note in laravel docs: You should not mock the Request facade. Instead, pass the input you desire into the call method when running your test.


So maybe this isn't such a great idea after all.


I tried mocking \Symfony\Component\HttpFoundation\File\UploadedFile and passing it to my call method but after I define "shouldReceive" for all methods the system is expecting it still doesn't work as I need it to.


Is there any way to test the call so that Input::hasFile would return TRUE without uploading an actual file?


Thank you


How to compare special fields in google mock?

I have got question connected with google test. I would like to ask if while inducing "EXPECT_CALL(*A, some_method(mes1));" in test case there is possiblity to compare fields included in mes1 class.



struct Mes
{
int a;
};

//short section of test case:
Mes mes1 = Mes();
EXPECT_CALL(*A, some_method(mes1));


I would like to ask if in google mock is a possiblity to compare special fields included in Mes. Something like:



EXPECT_CALL(*A, some_method(mes1), compare(Mes.a));//in this case google mock would compare only field "a" from Mes.

executing task on each line of table/matrix in R

I have a matrix looking like:



V1 V2 V3 V4
[1,] 85 11 9 4
[2,] 85 11 11 2
[3,] 85 11 12 0


I would like to combine each line of it in a 2x2 contingency table and perform a fisher.test on each of these contingency table (ideally redirecting results to a file: csv or xlsx).


How to?


Thanks for your help


Testflight app requires iOS8. How do we beta test with iOS7?

Now that Apple have integrated Tesflight into itunesconnect I thought it was time I took a look.


I have fallen at the first hurdle - when you invite a tester to test an app they are told they must have the Testflight app installed on their device, but the Testflight app requires iOS8 or later and if you have iOS7 it seems you can't be a tester.


So my question is...am i missing something and is there a way to use Apple's new Testflight beta testing system with iOS7 users?


How can to test Fragment with Espresso 2?

I have android-project, in it I have one MainActivity (extends ActionBarActivity) and some MyFragments (extends android.support.v4.app.Fragment). In my project: first start: MainActivity, second start: MyFragment1 (for log in), next start: MyFragment2 (after log in, with list some params). And you cannot see MyFragment2 (with some list), before log in by MyFragment1.


How can I to test MyFragment2 without log in MyFragment1? By Espresso 2? (http://ift.tt/19dd9Kv) Now - If I at first to test MyFragment1, I can to test MyFragment2, But If I want to test just MyFragment2.. Help me, please.


Problems trying to mock a Model within Flask-SQLAlchemy

I'm testing a Flask application that have some SQLAlchemy models using Flask-SQLAlchemy and I'm having some problems trying to mock a few models to some methods that receive some models as parameters.


A toy version of what I'm trying to do is like this. Suppose I have a model given by:



// file: database.py
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
birthday = db.Column(db.Date)


That is imported in an app that is built with the app factory pattern:



// file: app.py
from flask import Flask
from database import db

def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db.init_app(app)


And some function that needs a User as parameter:



// file: actions.py
import datetime

SECONDS_IN_A_YEAR = 31556926

def get_user_age(user):
return (datetime.date.today() - user.birthday).total_seconds() // SECONDS_IN_A_YEAR


Moreover there should be a couple of views and blueprints that are imported in app.py and registered in the app that latter call the function get_user_age somewhere.


My problem is: I want to test the function get_user_age without having to create an app, registering with a fake database, etc, etc. That shouldn't be necessary, the function is totally independent from the fact that it is used in a Flask app.


So I tried:



import unittest

import datetime
import mock

from database import User
from actions import get_user_age

class TestModels(unittest.TestCase):
def test_get_user_age(self):
user = mock.create_autospec(User, instance=True)
user.birthday = datetime.date(year=1987, month=12, day=1)
print get_user_age(user)


That raises me a RuntimeError: application not registered on db instance and no application bound to current context exception. So I thought "yeah, obviously I must patch some object to prevent it from checking if the app is registered with the database and etc". So I tried decorating it with @mock.patch("database.SQLAlchemy") and other things to no avail.


Do anyone know what should I patch to prevent this behavior, or even if my test strategy is all wrong?


How to get logs for a video playback.?

I'm new to this android playback testing. My requirement is I want to test the video quality of a various codec in a target android board. When I see the playback manually I'm not getting any glitches it is playing well.But the problem is technically I have to confirm that the video is played correctly. So my question is how to check the video is played correctly.And Is there any tool which gives the decoded,dropped kind of information for android 4.4.2.?.Thanks in advance.?


R test categorical column

I want to create test set using "createDataPartition" in caret (Or other method) which I can do based on label column in my data set. But my additional requirement is that my data has one categorical column (say: ID with values as ID1, ID2....ID10 for examples in data set) I want that all the observations with particular ID should be either in train set or in test set. How to do it. many thanks


How to test method in google test, using std::function?

I would like to test method "methodToTest" in class A:


typedef std::function F_global;



struct A
{
F_global m_F_global;

A(F_global m_F_global) : p_F_global(m_F_global) {}

void methodToTest()
{
m_F_global(5);
}
};


I have got a mock class:


class RunMock { public: MOCK_METHOD1(run, void (int)); };


Below I have got a test case:



class TestClass : public testing::Test
{
protected:
void SetUp();

std::unique_ptr<A> m_aa;
StrictMockPtrMade<RunMock> m_runMock;
};

void UecSimplePortTestSuite::SetUp()
{
m_aa = make_unique<A>(m_runMock->AaSysComMsgForward);//IT DOESN'T WORK I DON'T KNOW HOW TO FORWARD A METHOD run from RunMock to constructor
}

TEST_F(UecSimplePortTestSuite, testForwardMessage)
{
EXPECT_CALL(*m_runMock, run(_));
m_aa->methodToTest();
}


Generally I don't know how transfer a method "run" from Mock class "RunMock" in "UecSimplePortTestSuite::SetUp()". I would like to do this, because I would like to "EXPECT_CALL(*m_runMock, run(_));" in UecSimplePortTestSuite.testForwardMessage to test "methodToTest()". I think that good idea could be to use lmbda, std::boost::bind or something like this.


How to test and debug Cocoa App on different version of OSx using same Mac?

I made an Application using my Mac with Yosemite. On Completion of that I archived it and Then distribute to few friends, one of them have Mavericks. I faced some issues on that Mavericks System. With the occurrence of this thing, following queries raised in my mind,



  • Can I check my application on different OSX version, without running it actually on different MACs?

  • Can I also debug my application with different OSX Versions, using a system having single Osx?


In Nutshell, I want to know, is it Possible to test Cocoa application with multiple versions? something similar like iOS development where I can run app on different iOS versions.


Which is the best performance testing tool for a website developed using MVC and hosted in Microsoft Azure

I am very new to performance testing. We have developed a new website in MVC and deployed in microsoft azure as IaaS(infrastructure as a service). We need to do a performance review of the website.


Please let me know which is the best tool(preferably open source ) for performance testing and what are the parameters to be considered while performing performance testing.


Thank you


How to mock up the EntityManager using jmockit's Mockups API?

I have a problem with mocking up the EntityManager. Everything compiles, the test runs but the mocked method returns null.


When I set the breakpoint inside the mocked 'find' method the app is never suspended there. I managed to successfully mock different class with static methods this way - but with this one I have problems.


I use Jmockit 1.7 along with Java 1.8.0. The class I am trying to mock is: javax.persistence.EntityManager


If there are any more information needed - please ask. I would be very grateful for any help.


Here is my code:



@RunWith(JMockit.class)
public class ShapefileSerializerTest {

@Mocked
private EntityManager em;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
new MockDatabase();
}

@Test
public void testPrepareShapefile() {
String[][] data = new String[][] {{"1", "100"}, {"1", "101"}, {"1", "102"}, {"1", "103"}, {"2", "200"}, {"2", "201"}};

List<Map<String, String>> featuresData = Stream.of(data).map(row -> {
Map<String, String> map = new HashMap<>(2);
map.put("layerId", row[0]);
map.put("id", row[1]);
return map;
}).collect(Collectors.toList());

ShapefileSerializer shapefileSerializer = new ShapefileSerializer("shapefiles");
// if I do not set up the em here - then it will be null inside the tested class
Deencapsulation.setField(shapefileSerializer, em);

Response response = shapefileSerializer.prepareShapefile(featuresData);

assertEquals(Status.OK.getStatusCode(), response.getStatus());
}

public static final class MockDatabase extends MockUp<EntityManager> {
@Mock
@SuppressWarnings("unchecked")
public <T> T find(Class<T> entityClass, Object primaryKey) {
return (T) new ProjectLayer();
}
}
}

mardi 27 janvier 2015

Jacoco specific goal

I use maven and jacoco to build a full report for my projects.


Is it possible to specify a goal to run just the reporting ?


Something like mvn run-test ? And when I launch mvn clean install I don't want maven to build the report.


Thanks you


Testing crates with #![no_std]

I'm writing a runtime for a programming language implementation in rust. I'm planning on linking in this runtime with the compiled code I generate, so I don't want to rely on std to keep the binary small. The problem is, when I try to cargo test my runtime, I get errors saying saying that std::slice::AsSlice can't be found, which after some googling I found out is because some of the test harness requires std library code.


Does anyone have any suggestions for how to go about testing this code? Is there a way to conditionally include the #![no_std] pragma, i.e. still include the std library while testing? I've also tried creating a separate test crate with std library included, extern crateing the runtime crate into it and running my tests there, but that has introduced a whole new set of issues.


C# Testing Asynchronous/Callbacks Visual Studio

I need to write some tests for a whole bunch of C# code similar to the below example. This is one of my first tasks in C# and I've been unlucky enough to get dumped straight into async code :(. Its a web application that makes a bunch of database requests:



namespace Foo.ViewModel
{
public class FooViewModel
{
private ManagementService _managementService;
public int Status { get; set; }
public Foo()
{
Status = 5;
_managementService = new ManagementService();
_managementService.GetCustomerInfoCompleted += new EventHandler<GetCustomerInfoEventArgs>(CustomerInfoCallback);

}

public void GetCustomerInfo(int count)
{
int b;
if (someCondition() || otherCondition())
{
b = 2;
}
else
{
b = SomeOtherAsynchronousMethod();
}
_managementService.GetCustomerInfoAsync(b, count);
//when completed will call CustomerInfoCallback
}

void CustomerInfoCallback(object sender, GetCustomerInfoEventArgs args)
{
Status = args.Result.Result.Total;
UpdateView();
}

}

}


I'd like to be able to run a simple test like this:



[TestMethod]
public void TestExecute5()
{
Foo f = new Foo();
f.GetCustomerInfo(5);
Assert.AreEqual(10, f.Status);
}


but obviously its not that simple with the anynchronous methods.


There are perhaps 40 asynchronous methods in the ManagementService, called by ~15 different ViewModels - this ViewModel calls about 8 of those asynchronous methods. The async calls are implemented through the Event-Based Asynchronous Pattern so we don't have any of the nice 'async' or 'await' functions.


What can I do to get tests working in some kind of way that I can call the GetCustomerInfo method and check the status after the callback has completed?


Assert Is Breaking Async Function in Mocha Test

I'm building a node module and am trying to do my best to unit test the heck out of it. I've setup mocha and chai to do the test handling. I'm having a problem testing my async methods (methods that return promises).


In the following test I am testing a method on an "Upgrade" object.



it('Should return a list of versions for the default git repo', function (done) {
fs.writeFileSync(appSetup.CONFIG_FILENAME, JSON.stringify(appSetup.DEFAULT_CONFIG));

var upgrade = new Upgrade({
quiet: true
});

upgrade.getVersions().then(function (versions) {
assert(versions && versions.length > 0, 'Should have at least one version.');
assert.equal(1, 2); // this throws the exception which causes the test case not even exist
done();
}, done);
});


The getVersions() call returns a promise as the method is async. When the promise resolves I want to test the value returned in the versions variable.


The assert(versions && versions.length > 0, 'Should have at least one version.'); is the actual test. I added assert.equal(1, 2); because I noticed that when the test should fail the test case wouldn't even show up in the test list.


I'm assuming that the assert call is throwing an exception that Mocha should pickup. However it is getting trapped in the promises then handler function.


What is going on here? Why when the assert is going to fail in that method does it not show the test case in the list (it doesn't show as failed; like it doesn't exist)?


Selenium - Get location after clicking on an anchor

I'm trying to check the fact that when I click on an anchor link, some section is really at the top of the browser (I hope I'm making sense here.)


My test looks like that:



class Tests(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(chromedriver)
self.accept_next_alert = True
self.driver.set_window_size(1100, 800)
self.base_url = "http://someurl"

def test_anchor(self):
driver = self.driver
driver.get(self.base_url)
driver.implicitly_wait(1)
location = driver.find_element_by_xpath(
"//section[@id='123123']").location
print location

driver.find_element_by_partial_link_text("anchor_text").click()
location = driver.find_element_by_xpath(
"//section[@id='123123']").location
print location

self.assertTrue(False)


The assertion is just so I can see my prints. What I get from that is that even though I see that the anchor worked, the location dict stays the same. So I guess I'm not using the right feature.


Could you think of another way to check that the click on the anchor had the expected effect? (by either not looking at the location or by looking at the location the right way or else)


Test highlight fonction


internal class ClassHelper
{
internal static string GetPropertyName<TClass, T>(Expression<Func<TClass, T>> propertyExpression)
{
if (propertyExpression == null)
throw new ArgumentNullException("propertyExpression");
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Invalid argument", "propertyExpression");
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == (PropertyInfo)null)
throw new ArgumentException("Argument is not a property", "propertyExpression");
else
return propertyInfo.Name;
}
}


Does this work ? I wanna to get the Embedded code of the one that was generated here.


How to test ServerEndPoint, ClientEndPoint?

I have implemented ServerEndPoint and ClientEndPoint, how can i test it? For example, i have Connection wrappers over Session and i want to test it behavior which depends on session data, also i want to test messaging between client and server. Note that i don't have any war or any of application configuration such as web.xml, web-sockets infrastructure going to be used in another place, all what i have is mapped ServerEndPoint and ClientEndPoint implementations.


Rails: Use Capybara to browse both local and remote pages in a multi-threaded environment

In a Rails app I'm using Capybara with Poltergeist and PhantomJS to take snapshots of assorted URLs defined by the user, and save those snapshots for later comparison. Because the snapshot execution works in the background using Sidekiq, using the default (global) Capybara session will lead to race condition errors, so I've written a helper method to initialize a new Capybara session for each thread:



def new_capybara_session
# When using Capybara / PhantomJS in a threaded environment like Sidekiq,
# each job needs its own separate session to prevent race conditions and
# the consequent bizarre errors.
Capybara::Session.new(:poltergeist)
end


As long as the snapshot code is set up to use this new session exclusively, I don't run into problems when taking multiple snapshots at the same time as long as the URLs are remote.


However, in my test suite I've exercised this snapshot code by visiting a local URL (ie. from Chrome I saved a few random webpages to /public/test_sites/foo.html and so forth). These tests break; tt turns out my new Capybara session object (intialized using the above method) can't load local URLs, even though it can load remote ones fine. However, if I include Capybara::DSL and use the global / default Capybara session object, I can load both remote and local URLs fine.


Why is this? How can I load local URLs when using a manually created Capybara::Session object? If I can't do this, I can't write thorough tests for the snapshot code.