samedi 28 février 2015

Python - How do I create a test function by using another function?

I'm having a hard time trying to use another function into a function that tests the function I added with print statements. For example with this function that reverses a string. I want to use print statements in another function that tests the reverse function, but I'm having a hard time understand how I can incorporate the is_reverse function into the testing function without adding parameters into the testing function.



def is_reverse( st1, st2 ):
if len( st1 ) != len( st2 ):
return False
i = 0
j = len( st2 ) - 1
while j > 0:
if st1[i] != st2[j]:
return False
i += 1
j -= 1
return True

def test_is_reverse( ):
print( "is_reverse( \"hey\", \"yah\" ) == False.\"" )
print( "is_reverse( \"man\", \"nam\" ) == True.\"" )

TeamCity + Xcode 6 - Run Test action fails

I am trying to make a simple Xcode project work with TeamCity. Without running any tests I have succeeded.


I have a basic, Single View Application in Swift with one label on the screen. Both TeamCity (9.0.2) and Xcode (6.1.1) runs on the same machine (Mac mini) with an OS X (10.10.2) Server (4.0.3) installed on it. I have created a Git repository with Server and added as a remote to my sample Xcode project. After that, I've created successfully a working TeamCity project and build.


However when I try to check the Run tests checkmark the build WILL fail no matter what I do.


Configuration (dropbox image) http://ift.tt/1aErRzz


Error message (and the messages right before that)



[02:31:48][FirstTeamCityProjectTests (BUILD)] Touch
[02:31:48][Touch] Touch build/Debug-iphoneos/FirstTeamCityProjectTests.xctest
[02:31:48][Touch] cd /Library/TeamCity/buildAgent/work/55b27ad210b8fe77
[02:31:48][Touch] export PATH="/Applications/http://ift.tt/1aErRPO; ontents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin"
[02:31:48][Touch] /usr/bin/touch -c /Library/TeamCity/buildAgent/work/55b27ad210b8fe77/build/Debug-iphoneos/FirstTeamCityProjectTests.xctest
[02:31:48][FirstTeamCityProjectTests (BUILD)] CodeSign
[02:31:48][CodeSign] CodeSign build/Debug-iphoneos/FirstTeamCityProjectTests.xctest
[02:31:48][CodeSign] cd /Library/TeamCity/buildAgent/work/55b27ad210b8fe77
[02:31:48][CodeSign] export CODESIGN_ALLOCATE=/Applications/http://ift.tt/1dNZgFt
[02:31:48][CodeSign] export PATH="/Applications/http://ift.tt/1aErRPS Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin"
[02:31:48][CodeSign] Signing Identity: "iPhone Developer: *"
[02:31:48][CodeSign] /usr/bin/codesign --force --sign * /Library/TeamCity/buildAgent/work/55b27ad210b8fe77/build/Debug-iphoneos/FirstTeamCityProjectTests.xctest
[02:31:48][Step 1/1] ** BUILD SUCCEEDED **
[02:31:48][Step 1/1] xcodebuild: error: Failed to build workspace FirstTeamCityProject with scheme FirstTeamCityProject.
[02:31:48][Step 1/1] Reason: Xcode cannot run using the selected device.
[02:31:48][Step 1/1] Process exited with code 70
[02:31:48][Step 1/1] Step Xcode Project failed


Main problem I found with this error code and CI that they were trying with ssh and there were no GUI session. Currently I have a valid GUI session with the same user it uses, so it shouldn't be a problem.


The xcodebuild command is the following.



/Applications/http://ift.tt/1cDvaGw -workspace FirstTeamCityProject.xcodeproj/project.xcworkspace -scheme FirstTeamCityProject SYMROOT=/Library/TeamCity/buildAgent/work/55b27ad210b8fe77/build OBJROOT=/Library/TeamCity/buildAgent/work/55b27ad210b8fe77/build clean build test


What is missing here (I suppose) is one or more destinations. I've executed the following command and it worked just fine. (Opened the Simulator, then exited with success.)



xcodebuild test -project FirstTeamCityProject.xcodeproj -scheme FirstTeamCityProject -destination 'platform=iOS Simulator,name=iPhone 6,OS=8.1'


I seem to be alone with this problem, I didn't find any other relevant hits. Looking at this tutorial: http://ift.tt/1GyMvMV, my issue should not be present at all.


I appreciate any idea you have! Thanks in advance!


TeamCity SoapUI Integration

I am new to teamcity and need some help in setting up the parameterized build.We are using jenkins to run regression project written in SoapUI and through paramiterized build options we are able to pass parameter(such as test environment,mercurial banch it has to pool the changes from, test suites in case we have executes only selected ones and tags) to the batch script that executes the testrunnner.bat on command line. How can I do the same stuff in teamcity?


I can see teamcity allows three types of parameters env,system and config.Out of which system parameters are passed to the build script.Can I specify all these required parameters as system parameter?


Also I need to supply these parameters for every build but the values may differ.Does teamcity provides facility same as jenkins that would provide a GUI where I can change these values?


verifying contents of a resolved promise via function call with chai-as-promised

I'm using chai-as-promised in conjunction with sinonjs and I'm unable to work out how to verify a changed password.


I have something like the following code:



it('changes password if old password is valid', function(){

var u = new User({id: '1234567890', email:'user@email.com'});
var encrypted_password = bcrypt.hashSync('newtestPassword', bcrypt.genSaltSync(8), null);
sinon.stub(db, 'executeQuery', function() {
return q.fcall( function() {
return [ {u: { _data: { data: {flake_id: '1234567890', email:'user@email.com', encrypted_password: encrypted_password}}}}];
})

})

return u.ChangePassword('testPassword', 'newTestPassword').should
.eventually.be.an.instanceof(User)
.and.have.property('encrypted_password')
.that.satisfy(bcrypt.compareSync('newTestPassword', this));
});


my problem is the last line of the assertion - I want to be able to extract the encrypted password from the stubbed database response and user bcrypt.compareSync() to check that it is the correct value, but I'm unclear on how to reference the encrypted_password value from the response.


According the the docs, the property() call makes that property the subject of the assertion which is why I tried to use this but I end up with bcrypt throwing an 'Incorrect arguments' error which I presume is due to the this reference.


Does anyone have a suggestion about how to do this properly?


note: I do intend to replace the stub with a mock that checks the query.


Headless Browserify JavaScript Testing with Phantom.js

I'm trying to find a way to execute the following steps.



  • Write Node.js code for the browser

  • Compile the code with browserify

  • Test the browser code in the terminal


I would love to get the console.logs that the browser receives, but within the terminal. This would not only save me time (from creating a HTML file, running a server, opening a browser), it would also allow for cool things like automatic testing before deployment.


I'm trying to make something called headless-test.js a phantomjs script that would get passed an argument using system.args[1] and fs.read can get the contents of any javascript you pass to it.



var content = fs.read(system.args[1])
page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'


That would allow me to do something like this:



phantomjs ./headless-test.js ./bundle.js


I was getting this error SyntaxError: Multiline comment was not closed properly so make sure you uglify your bundle.js.


All of this would be amazing and work if I could get this demo below working. The minimal viable product:



var system = require("system")
var webPage = require('webpage')
var page = require('webpage').create()
page.content = '<html><body><script type="text/javascript">console.log("hello world")</script></body></html>';

page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

page.evaluate(function(){

})

phantom.exit();


The expected results here are:



$ phantomjs ./headless-test.js
hello world


However I'm getting no stdout from phantom.


Security Software Suggestions

I like to keep this question more in terms of suggestions vs. debating, in what is some of the best security scanning software that's currently on the market?


UI automation in instruments 6.1 cannot run through my web application in Safari yosemite os

I am running the UI automation scripts through my application running in Safari. In that I am giving the automation commands starting as "instruments -w ..." to the process which I created in java for running the commands in terminal directly. The simulator is launching but the app is not installed. It's showing the following error. Instruments Usage Error : Could not remove existing output document 'file:///System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/com.apple.WebKit.Plugin.64.xpc/instrumentscli0.trace': Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “instrumentscli0.trace” in the folder “com.apple.WebKit.Plugin.64.xpc”." UserInfo=0x7ff26d117480 {NSFilePath=/System/Library/Frameworks/WebKit.framework/Versions/A/XPCServices/http://ift.tt/1LWg24S, NSUnderlyingError=0x7ff26d132450 "The operation couldn’t be completed. Permission denied"}.


Please suggest how to solve this and run my automation commands through my web application ?


Post data to URL and include session data

In writing a test for a php script, I want to send the tested script post data and also have it receive the $_SESSION data from the sending php test script.


Peter and Burak both showed a way to send the post data in POST data to URL php One used curl and the other html5.


Using either of the two solutions, I get the $_POST data in the tested script, but not the $_SESSION data from the sending php script.


I have tried dozens of suggestions found online, but I never get the session data using those suggestions.


Help would be appreciated.


Nodejs API testing

I am new to Nodejs environment. I am using Webstorm as IDE on Ubuntu environment. I want to know a good testing framework for my project. I have checked many of them like Karma-Jasmine, but it looked like for client side testing only. I want something for the Server Side. I tried Jasmine-Node, but not sure if it is the best one.


Please suggest a server side testing framework and if some reference documentation/videos are there, please share.


double click using protractor worked fine in chrome but not working in firefox

Below is the code snippet which i used for double clicking the element which worked fine in chrome browser but its not working in firefox.



browser.actions().doubleClick(element(by.repeater('row in renderedRows').row(0))).perform();


Below is the HTML Snippet:



<div class="ng-scope ngRow even" ng-row="" ng-class="row.alternatingRowClass()" ng-click="row.toggleSelected($event)" ng-repeat="row in renderedRows" ng-style="rowStyle(row)" style="top: 0px; height: 30px;">
<!-- ngRepeat: col in renderedColumns -->
<div class="ngCell col0 colt0" ng-class="col.colIndex()" ng-repeat="col in renderedColumns" ng-style="{ }" ng-click="showDetail(row.entity)" ng-dblclick="viewBothPanes()">
<div class="ngVerticalBar ngVerticalBarVisible" ng-class="{ ngVerticalBarVisible: !$last }" ng-style="{height: rowHeight}" style="height: 30px;"/>
<div ng-cell="">
<div class="ngCellText ng-scope col0 colt0" ng-class="col.colIndex()">
</div>
</div>
<!-- end ngRepeat: col in renderedColumns -->
<div class="ngCell col1 colt1" ng-class="col.colIndex()" ng-repeat="col in renderedColumns" ng-style="{ }" ng-click="showDetail(row.entity)" ng-dblclick="viewBothPanes()">`


My scenario is:


We have ng-grid which has many row i need to double click on a row, which worked fine as expected, but when the same tescase ran in firefox identified the row but didnt double click on the row.


vendredi 27 février 2015

How to get x:Class property of Page in Windows Phone 8.1?

I have an app. I want to get x:class of a page to distinguish pages. How to get it? Please help me. Thank for your help!


How to set up a test environment for linked data

I'm wondering how to set up a stage/test environment for a linked-data infrastructure.


Indeed, in my organization we have the prerequisite to always have test env together with a prod env. Until here nothing abnormal. However, this can be complicate for linked-data where the data are identified by URI. The URI is central to linked-data.


How can you set up a test environment with the same uri(s) as the production environment ?


The only thing that i see are:


A sort of private network where to set some DNS rules that says that when in that environment, the uri should redirect to that test machine IP.


While outside of the that VPN, the machine should be the one that an internet DNS point to.


The other solution is having a reverse proxy like ngnix which does url rewrite. Hence you would adress the test machine with a local url and this url, will be re-injected in the response by the reverse proxy with a rewrite. But that's just too heavy and could only work with rdfa. I don't know if a reverse proxy can pasrse a full turtle file.


final solution, changing the base uri of your data each time.


Please any suggestion ?


Mocking dependency that has setListener(...)

My class under test has a few dependencies. All of these provide setListener() as a way to receiving notification from their non-blocking operations.


I implemented a blocking method that aggregates the results from all the non-blocking ops. Which mean I have to register the listeners using such setListener() methods, and wait for the callbacks.


How should I mock/fake these dependencies in my unit test? I could subclass them and implement setListener() and fire the callbacks as necessary. But let's say some of these deps are final class. Also, I think there might be something I could use from Mockito?


Conceptual code (untested):



public void blockingMethod() {
CountDownLatch signal = new CountDownLatch(2);

dep1.setListener(new Dep1Listener() {
@Override public onResult(int result) {
signal.countDown();
}
});
dep1.calculateValue1();

dep2.setListener(new Dep2Listener() {
@Override public onResult(int result) {
signal.countDown();
}
});
dep2.calculateValue2();

signal.await();
return combinedResult;
}

Testing tab navigation order

In one of our tests, we need to make sure that the tab keyboard navigation inside a form is performed in the correct order.


Question: What is the conventional way to check the tab navigation order with protractor?




Currently we are solving it by repeating the following step for as many input fields existing in a form (code below):



  • check the ID of the currently focused element

  • send TAB to the currently focused element


Here is the example spec:



it("should navigate with tab correctly", function () {
var regCodePage = new RegCodePage();
browser.wait(protractor.ExpectedConditions.visibilityOf(regCodePage.title), 10000);

// registration code field has focus by default
expect(regCodePage.registrationCode.getId()).toEqual(browser.driver.switchTo().activeElement().getId());

// focus moved to Remember Registration Code
regCodePage.registrationCode.sendKeys(protractor.Key.TAB);
expect(regCodePage.rememberRegistrationCode.getId()).toEqual(browser.driver.switchTo().activeElement().getId());

// focus moved to Request Code
regCodePage.rememberRegistrationCode.sendKeys(protractor.Key.TAB);
expect(regCodePage.requestCode.getId()).toEqual(browser.driver.switchTo().activeElement().getId());

// focus moved to Cancel
regCodePage.requestCode.sendKeys(protractor.Key.TAB);
expect(regCodePage.cancelButton.getId()).toEqual(browser.driver.switchTo().activeElement().getId());

// focus moved back to the input
regCodePage.cancelButton.sendKeys(protractor.Key.TAB);
expect(regCodePage.registrationCode.getId()).toEqual(browser.driver.switchTo().activeElement().getId());
});


where regCodePage is a Page Object:



var RegCodePage = function () {
this.title = element(by.css("div.modal-header b.login-modal-title"));
this.registrationCode = element(by.id("regCode"));

this.rememberRegistrationCode = element(by.id("rememberRegCode"));
this.requestCode = element(by.id("forgotCode"));

this.errorMessage = element(by.css("div.auth-reg-code-block div#message"));

this.sendRegCode = element(by.id("sendRegCode"));
this.cancelButton = element(by.id("cancelButton"));
this.closeButton = element(by.css("div.modal-header button.close"));
};

module.exports = RegCodePage;


It is working, but it is not really explicit and readable which makes it difficult to maintain. Also, another "smell" in the current approach is a code duplication.


If the current approach is how you would also do it, I would appreciate any insights about making it reusable.


Javascript Mocha Tests - Testing function expressions inside function expressions

I haven't used Mocha before, so I am a real novice when it comes to testing. However, I wanted to know if it's possible to test a function expression inside of a function expression? I know there are other posts on how you cannot access function expressions inside function declarations and so on.


So, is it possible to access function expressions inside function expressions and test with Mocha? For example, I have the following code:



var masterFunction = function() {

var siGogglin = functionDeclaration(putSomethingHere);

function functionDeclaration(code) {
var yoyo = [];

//some stuff I don't want you to see

return yoyo;
};
};


Is it possible to test the function functionDeclaration from the variable siGogglin within masterFunction? If so, could you give me an example of how it could be done?


Thanks.


Selenium Firefox Driver reading from Hosts file

I'm trying to avoid running this particular selenium script in a production environment. When this test is ran manually, I change my /etc/hosts file accordingly.



xx.x.xxx.xx www.url.com


What is a practical way of passing the test environment IP to the driver? Or perhaps have the driver read from the host file?


How to test AJAX call was made?

I'm testing a Django site using Selenium. I have added a function to report javascript errors via Google Analytics, how can I write a test that checks that when there is a javascript error an AJAX call is made to Analytics?


AngularJS Jasmine Factory test

I'm trying to test a Factory with Jasmine but I'm getting:


Error: [$injector:unpr] Unknown provider: Provider <- <- RecaptchaFactory


Here is my factory:



(function() {
'use strict';

angular
.module('app')
.factory('RecaptchaFactory', Recaptcha);

Recaptcha.$inject = [''];

function Recaptcha() {
return {
passwordAttempts: passwordAttempts,
};

var passwordAttempts = 0;

}
})();


And my test:



describe("RecaptchaFactory", function(){
beforeEach(module("app"));

var factory;

beforeEach(inject(function(RecaptchaFactory){
factory = RecaptchaFactory;
}));

describe("init", function(){
it("should init passwordAttempts with 0", function(){
expect(factory.passwordAttempts).toBe(0);
});
});
});

How can I detect if my express (4.0) node.js app is using a specific piece middleware?

For the purposes of Unit testing I'd like to be able to work out if some middleware is in use.


For example


app.js



var express = require('express');
var morgan = require('morgan');

module.exports = function(options) {
var app = express();

if (options.logRequests) {
app.use(morgan('dev'));
}

return app;
}


app.test.js (run via mocha)



describe('app', function(){
it('should log requests when initialized with the `log requests` option', function() {
var app = require('./app)({ logRequests: true });

// Something to establish whether or not morgan is in use
})
})


I believe middleware is pushed to the seemingly undocumented express "stack", which can be accessed via the app._router.stack array, but this looks like a pretty horrible way to get to what I'm after.


Is anyone aware of a better way to this my assertion?


Thanks


How to properly clean up after using an HttpClient in a unit test

In a unit test using an Apache HttpClient to fire requests, I have seen the following setup and cleanup code:



private HttpClient httpClient;
private HttpRequestBase httpRequest;


@Before
public void setUp() throws Exception {
httpClient = new DefaultHttpClient();
}

@After
public void closeRequests() {
if (httpRequest != null) {
httpRequest.releaseConnection();
httpRequest = null;
}
}


The tests than e.g. send get requests and check the response:



@Test
public void getSomething() throws Exception {
httpGet = new HttpGet("http://some/url");
HttpResponse response = httpclient.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_OK));
}


Now my question is: Do these tests properly clean up after themselves? From what I understand, the releaseConnection() call only hands back the connections to the client's connection manager but doesn't actually close it.


So shouldn't the tests rather do this:



@After
public void closeConnections() {
httpClient.getConnectionManager().shutdown();
}


And would this properly close all connections even without calling releaseConnection() on the http request instances?


Test Manager: Extract test case names from all iterations

Is there a tool or utility to extract all the test case names with suite and iteration names from TFS 2013? I tried this tool (http://ift.tt/1vGamIc) but it doesn't work with 2013. Thanks


Rails doesn't load fixtures when working with STI

I have these models:



class Company < ActiveRecord::Base
end

class Enterprise < Company
has_many :establishments
end

class Establishment < Company
belongs_to :entreprise
end


and these fixtures:



#enterprises.yml
johns_enterprise:
owner: John
name: John & co..
trade: John s Enterprise
cnpj: 11222333000111

#establishments.yml
josephs_establishment:
owner: Joseph
name: Joseph & co..
trade: Josephsss
cnpj: 99888777000122


When I run



rake db:fixtures:load


just establishments data are loaded. Anybody knows why?


C# Running concurrent requests using WebTestRequest

When writing coded web tests using the Web Performance Test API. Can you write test that send requests at the same time i.e. concurrent ones, that is with one user of the load test, fire off concurrent web requests?


Android Studio 1.1.0 + Robolectric 2.4 causes java.lang.annotation.AnnotationFormatError

I'm trying run Robolectric tests within my projects.


I'm using Andriod Studio 1.1.0 with unit testing support (http://ift.tt/1KkPIk8) and I'm doing everything similar to http://ift.tt/P74Jyz project.


When I try to run tests from within Android Studio I'm getting following error:


Exception in thread "main" java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class org.robolectric.annotation.Config.application() at java.lang.reflect.Method.getDefaultValue(Method.java:747) at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:117) at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:84) at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:221) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70) at java.lang.Class.initAnnotationsIfNecessary(Class.java:3178) at java.lang.Class.getAnnotation(Class.java:3137) at com.intellij.junit4.JUnit4TestRunnerUtil.buildRequest(JUnit4TestRunnerUtil.java:199) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:39) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)


Any idea about the reason?


How to start SMS Center Mock with ruby-smpp

I'd like to start SMS Center Mock based on ruby-smpp. All I need is correct bind, delivery reports and message body. I guess it's pretty easy with ruby-smpp. I try to modify sample_gateway.rb but without success. Receiver_test.rb looks handy but I can't run it since test/unit used there is obsolete. Thank you for your help.


selenium python check hide error

So, i need to create some test for check login/registration. I trying to catch hide error when user enter email incorrect. Steps: 1. Enter not valid email. 2. Press button "Login". 3. Should show error what "password or email is not correct".


Below i wrote 2 function. How i can combine this two function? Second function always show me "OK" status.



def test_login_user(self):
driver = self.driver
driver.get("http://ift.tt/1ybKKlM")
driver.find_element_by_name('email').send_keys("email24")
driver.find_element_by_name('password').send_keys('12345678')
driver.find_element_by_name('signin').click()

def test_error(self):
driver = self.driver
driver.get('http://ift.tt/1ybKKlM')
error = driver.find_element_by_css_selector('div.status.submission-error')
if error.is_displayed():
return True
else:
return False

How click in necessary coordinate x,y by Espresso in test?

I need click by Espresso testing in x, y.


I have view:



<view xmlns:android="http://ift.tt/nIICcg" class="uk.co.senab.actionbarpulltorefresh.extras.actionbarcompat.PullToRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top"
android:id="@+id/pull_to_refresh_layout">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/date_param"
android:textSize="@dimen/default_text_size"
android:textColor="@color/palette_light_gray"
android:layout_marginTop="25dp"
android:layout_marginLeft="28dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<example.ui.view.UnderlinedTextIndicator
android:id="@+id/tab_indicator"
android:paddingLeft="@dimen/field_padding"
android:paddingRight="@dimen/field_padding"
android:layout_below="@+id/date_param"
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_marginBottom="7dp"
android:layout_height="wrap_content"/>

<android.support.v4.view.ViewPager
android:id="@+id/tabbed_content"
android:layout_above="@+id/btn_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tab_indicator"
android:layout_marginTop="10dp"/>

<example.ui.BigButton
android:id="@+id/btn_item"
android:text="@string/btn_convert_rates"
style="@style/BigButton"
android:layout_marginTop="10dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</view>


So, in panel view: in top drawing date, under strings: text1 and text2 on one line, under some content, under - button. I draw text1 and text2 on canvas. I need click on text1 and text2 by Espresso. But, if I write: onView(withText(String.valueOf(R.string.text1))).perform(click()); - I have android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "2131492993", So, I want click in coordinate x,y:



private static ViewAction clickXY(final int x, final int y) {
return new GeneralClickAction(
Tap.SINGLE,
new CoordinatesProvider() {
@Override
public float[] calculateCoordinates(View view) {

final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);

final float screenX = screenPos[0] + x;
final float screenY = screenPos[1] + y;
float[] coordinates = {screenX, screenY};

return coordinates;
}
},
Press.FINGER);
}
}


But, I do not know - which must be are x,y? How can to get x,y for test1 and x,y for test2?


PHPunit to test catch block

I have a code like this one:



public function one()
{
try {
$this->two();
} catch (Exception $E) {
$this->three();
}
}


How can i test that $this->three() function is called?


I've tried to "mock by code" $this->two() and throw error instead of it's original code, but that ends up with error caught by phpunit itself.


Tried setExpectedException, but it also doesn't solve the problem - catch runs inside phpunit again and just ignored.


Function $this->three() never called in both cases.


Thanks!


jeudi 26 février 2015

Expect item in array

One of my test expects an error message text to be one of multiple values. Since getText() returns a promise I cannot use toContain() jasmine matcher. The following would not work since protractor (jasminewd under-the-hood) would not resolve a promise in the second part of the matcher, toContain() in this case:



expect(["Unknown Error", "Connection Error"]).toContain(page.errorMessage.getText());


Question: Is there a way to check if an element is in an array with jasmine+protractor where an element is a promise?


In other words, I'm looking for inverse of toContain().




As a workaround, I can resolve the promise with then():



page.errorMessage.getText().then(function (text) {
expect(["Unknown Error", "Connection Error"]).toContain(text);
});


I'm not sure if this is the best option. I would also be okay with a solution based on third-parties like jasmine-matchers .




As an example, this kind of assertion exists in Python:



self.assertIn(1, [1, 2, 3, 4])

Excel Test Simulator

I have seen a number of test simulator but have no clue which software to purchase or use to be able to create my own. I would like to create and excel test where users actually use the simulator to answer rather than multiple choice questions


Skip Windows Authentication with Selenium / Jenkins

I use Selenium IDE to create my tests I integrate these tests with selenium modules in Jenkins and all is OK.


My problem is that on my test site there is an authentication "windows" impossible to manage directly with selenium commands.


I try to change my base URL http://ift.tt/181Gk6H But it does not work (I use Firefox)


What would be the solutions to this problem? A JS solution perhaps? In my user-extensions.js ?


Thank you for help !


Service virtualization

While SV vendors provide guides, they are more of sales brochures on the benefits. I am trying to understand how Service Virtualization works behind the scenes.


If there is a production version of the service/component/app you are trying to virtualize, analyzing real-time traffic and generating a set of request-response behaviors is understandable.


However, if the dependent component is not developed yet, how can SV help? In other words, what do the SV tools do under the hood?


How to restore database before executing test in protractor

I have written E2E tests in Protractor which uses node to run through webdriver.


Now I have some inserts tests which will insert the data and create user.


Now if I run the case for the first time it will pass but when I will rerun the test it will fail as it will already present.


Expected : I need to restore my MSSQL DB when ever the tests in protractor start.


Present : I am doing manually by restoring the test.


Is there any way that I can restore the DB through protractor or Node ?


How to restore database before executing test in protractor

I have written E2E tests in Protractor which uses node to run through webdriver.


Now I have some inserts tests which will insert the data and create user.


Now if I run the case for the first time it will pass but when I will rerun the test it will fail as it will already present.


Expected : I need to restore my MSSQL DB when ever the tests in protractor start.


Present : I am doing manually by restoring the test.


Is there any way that I can restore the DB through protractor or Node ?


How to use Galen framework in Windows for chrome browser

I am trying to implement Galen framework, but I could not find any document for Galen to be used in Windows for Chrome browser.


Can any one help me..If not can any one suggest me any framework for Responsive Design Testing.


Thanks in advance.


How to use Galen framework in Windows for chrome browser

I am trying to implement Galen framework, but I could not find any document for Galen to be used in Windows for Chrome browser.


Can any one help me..If not can any one suggest me any framework for Responsive Design Testing.


Thanks in advance.


Testing background color espresso Android

Is it possible to check if the background color matches a given color with espresso?


Exception while running testNG reports

I am getting the below exception while running my testNG test cases.



[TestNG] Reporter org.uncommons.reportng.HTMLReporter@527740a2 failed
org.uncommons.reportng.ReportNGException: Failed generating HTML report.
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:122)
at org.testng.TestNG.generateReports(TestNG.java:1115)
at org.testng.TestNG.run(TestNG.java:1074)
at com.flipkart.cid.cs.Trigger.run(Trigger.java:98)
at com.flipkart.cid.cs.Trigger.main(Trigger.java:135)
Caused by: java.lang.NullPointerException
at org.uncommons.reportng.TestResultComparator.compare(TestResultComparator.java:29)
at org.uncommons.reportng.TestResultComparator.compare(TestResultComparator.java:25)
at java.util.Collections.indexedBinarySearch(Collections.java:332)
at java.util.Collections.binarySearch(Collections.java:320)
at org.uncommons.reportng.HTMLReporter.sortByTestClass(HTMLReporter.java:243)
at org.uncommons.reportng.HTMLReporter.createResults(HTMLReporter.java:193)
at org.uncommons.reportng.HTMLReporter.generateReport(HTMLReporter.java:114)
... 4 more

Test Program for Date class

I have written a Date class, which adds/subtracts days/months/years taking into consideration leap years. I now need to write a test program with hard coded data to test my implementation. The easiest way would be to create a "reference" date and then have a loop which takes it forward one day at a time, over say a 3 year period (including a leap year) and then print out the reference date together with some other dates constructed relatively from it. I haven't got a lot of java experience so I am wondering how I would actually do this?


How to separate business logic from web framework for testing?

For testing web applications, many sources suggest keeping your business logic as free from the web framework as possible to make it possible to test without needing to use the web framework. How can this be done?


If I have a registration page, I need to validate the HTTP POST data (e.g. making sure date of birth is a date and required fields are given), then I'd need to persist the validated data to the database. I'm not sure how I can separate the parts related to the web framework from the business logic, as it's quite a simple piece of functionality. Same applies to login pages, account deletion pages, etc.


I imagine the web framework wouldn't be doing much other than passing the HTTP data to the business logic function, which would then do everything (validation, persistence) that the web framework function was doing before this refactoring. So I don't see what I'm gaining. For example it would become



businessLogicRegister(
request.data['email'],
request.data['birthday'],
request.data['username']
);


Could someone give some examples of what such basic functions like registration/login might look like in a basic Node JS framework like Express or Koa and a good way to separate business logic from the web framework? And how that would help to make the code more unit-testable?


Is unit testing/code-review a part of QA or development?

I am fairly new to the IT-industry and I am very confused about QA and testing. As they are supposed to test and assure the quality, why do many programmers write unit tests and do code-review? Should not this be passed on to the test-department?


Why/why not?


How can I intercept emails being sent by my node application for testing

I am currently trying to get my Test coverage up on a MEAN stack application and I am looking for a way to intercept and verify emails sent by my application.


I am currently using nodemailer to send the emails through an internal corp smtp server, and we are getting blocked as either not valid email addresses or being flagged as spam. I have tried configuring it to work with capto and mailcatcher as a step in the right direction so the emails are successful in terms of the application but not actually going any further then the local machine. Ideally I would like to eventually be able to compare emails in my tests and to get things like links for reset password or referral links


Can anyone suggest a framework/tutorial or process that might assist in this?


Test html against schema

I have a task to perform html markup test on stage server before deploying project on production.


First of all I was thinking about using xml-schema, which is rather flexible tool, but it works only with well-formed xml documents. So the chain of actions is:



  • get piece of html

  • pass to php

  • use tidy to get xhtml

  • match against xml-schema

  • return human-readable errors (if any have occured)


Are there any solutions better than above? Thank you.


Different sqlite databases for testing and actual use in android app

Disclaimer - I have used GreenDAO ORM for creating and managing the sqlite db from within my android app.


For my android app, while writing unit tests, I wish to tell the app to switch to using a certain db which is different from the normal one in order to make sure that the tests do not contaminate the real db. Correspondingly I have used appropriate functions to create new db and switch to it like this



public class DbTests extends ApplicationTestCase<MyApp> {
private static final String TAG = "DbTests";
private MyApp mApplication;
private Context mContext;

public DbTests() {
super(MyApp.class);
}

@Override
protected void setUp() throws Exception {
Log.d(TAG, "in setUp");
super.setUp();
createApplication();
mApplication = getApplication();
Log.d(TAG, "setUp done");
}

@Override
public void tearDown() throws Exception {
super.tearDown();
}


private void setUpFreshInstallNoDataCase(boolean val) {
assertNotNull(mApplication);
LocalDataHelpers.setupLocalData(mApplication, InitialConditions.FreshInstallNoData);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public void testFreshInstallNoDataCase() {
Log.d(TAG, "testFreshInstallNoDataCase");
setUpFreshInstallNoDataCase(true);

mContext = mApplication.getApplicationContext();
assertEquals(0, PersonRepository.getAllPersons(mContext).size());
}
}



public class LocalDataHelpers {
public static final String TAG = "LocalDataHelpers";

static MyApp globalApplication;

public static void setupLocalData(MyApp app, String condition) {
globalApplication = app;
if(globalApplication.daoSession != null){
Log.d(TAG, "daoSession not null");
globalApplication.daoSession.clear();
globalApplication.setupDatabase(condition);
}
}
}


In my application onCreate and setupDatabase are like this



public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
EventBus.getDefault().register(this);
EventBus.getDefault().post(new PersonEvents.FetchPersonsFromServer());
setupDatabase(InitialConditions.DefaultSetUp);
}

private void setupDatabase(String condition) {
DaoMaster.DevOpenHelper helper = null;
SQLiteDatabase db = null;
DaoMaster daoMaster = null;
if (condition.equals(InitialConditions.DefaultSetUp)) {
helper = new DaoMaster.DevOpenHelper(this, "example-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
}
else if (condition.equals(InitialConditions.FreshInstallNoData)) {
helper = new DaoMaster.DevOpenHelper(this, "freshInstallNoData-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
//clear all possible data here by dropping all tables and recreate
Log.d(TAG, "Dropping all tables and recreating them");
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
}
if (helper != null && db != null && daoMaster != null) {
daoSession.clear();
daoSession = daoMaster.newSession();
}
else {
Log.e(TAG, "setupDatabase Error : condition " + condition + ", either helper or db or daomaster is null");
}
List<Pair<String, String>> dbs = getDaoSession().getDatabase().getAttachedDbs();
for (Pair<String, String> pair : dbs) {
Log.d(TAG, "setupDatabase <" + pair.first + ", " + pair.second + ">");
}
}


The onEvent for FetchPersonsFromServer gets a list of persons and saves them to the db using PersonDao.


Now If I clear all app data from my device and run the test directly, as expected the test passes. However if I run the app normally, and then run tests, the assert statement fails at



assertEquals(0, PersonRepository.getAllPersons(mContext).size());


with the size as that of the default db value.


I am going crazy trying to figure out why. The log statements in setupDatabase show that the correct db name is showing up ie freshdbinstall-db...


Are two dbs not allowed in android? Logically there should be no issues? Is it GreenDao which doesn't allow it? Am I making some basic mistakes...


Please help.


mercredi 25 février 2015

How do I organize structure of my testSuite using beforeClass, afterClass, afterSuite in testNG?

I m confused about using annotations @beforeClass,afterClass, beforeSuite,afterSuite in testNG.


I understand test structure below:



package mytestNG.learning.it ;

public class sample_not_working {
@Test
//take action - click on links, input data etc
public void main() {
}
@BeforeMethod
//do stuff like setup browser etc
public void beforeMethod() {
}

@AfterMethod
//close browser
public void afterMethod() {
}
}


But what do you do in beforeclass,afterClass and test? What file is it? Is it a class that runs other classes?


Next, afterSuite, beforeSuite and @test :



public class sample_not_working {
@Test

public void main() {
//WHAT KINDA CODE YOU PUT HERE?
}
@BeforeSuite
//WHAT KINDA CODE YOU PUT HERE?
public void beforeMethod() {
}
@AfterSuite
public void afterMethod() {
//WHAT KINDA CODE YOU PUT HERE?
}
}


My question is about semantics, the meaning, not actual code. I read the testNG docs - did not help.


Checking two boundaries with Jasmine (between matcher)

In Jasmine, there are toBeGreaterThan and toBeLessThan matchers.


What if I want to check an integer value in a specific range? Is there anything like toBeInBetween matcher?


Currently, I can solve it in two separate expect calls:



var x = 3;

expect(x).toBeGreaterThan(1);
expect(x).toBeLessThan(10);

How do I identify checkbox value with given HTML element? angularjs-e2e

I need some advice with issue below. When checkbox = checked, there will be attribute value checked=checked and for the unchecks, attribute will not be there and I can't uniquely identify. On a page, there will be checked and unchecked checkboxes. Dev refuses to add additional attribute for me and saying that there must be a way to identify (exist or not exist).


So on my my test page, I have 10 checkboxes with 3 checked and 7 unchecked.


HTML for uncheck checkboxes



<input type="checkbox" disabled="disabled" ng-checked="item.unread">


HTML for checked checkboxes



<input type="checkbox" disabled="disabled" ng-checked="item.unread" checked="checked">


My attempt at counting - it will returned exact number and will fail eventually as number may change.



expect(element.all(by.css('input[checked="checked"]')).count()).toBe(2);


No issue with identifying checked items with attribute - checked="checked"



expect(element.all(by.css('input[checked="checked"]')).isSelected()).toBeTruthy();


but fails when I check for unchecked item.



expect(element.all(by.css('input[type="checkbox"]')).isSelected()).toBeFalsy();


Failed result for unchecked item - 7 unchecked and 3 checked



[ false false false false true true false false true false]


Thanks


API tests server side vs. functional tests

What are some of the server side tests that can be performed on REST based APIs . Are functional tests on API considered server side tests? I was trying to search but couldn't get any direct related answers so thought of asking here. Thanks in advance.


How to make route method works in Play 2.x sub-project?

I have a Play 2.3 project with a sub-project inside. Following this tutorial, I am writing a test for sub-project's controller with route method:



"Get Action" in new WithApplication {
val Some(result) = route(FakeRequest(GET, "/sub/bob/11"))

status(result) mustEqual OK
}


Assumed in routes.conf, the sub-project routes is configured like this:



-> /sub sub.Routes


And in sub.Routes, it contains:



GET /bob/:id controllers.sub.BobController.get(id: Int)


However the route() method always returns None. Using route(FakeRequest(GET, "/bob/11")) doesn't work too.


Currently I can only solve the problem by direct call to the Controller's method:



val result = BobController.get(11)(FakeRequest(GET, "/bob/11"))


In this case, the "11" parameter in the "/bob/11" become useless as it's unused.


So anyone know how to make the route() works for sub-project?


How to efficiently test the performance of a web application?

The web application I am currently testing is running on an apache2 server with a large chunk of html/css/js files. I have been mostly trying to test the



  • load time

  • Number of http requests (without data base64 encoded uri image requests which apparently add up to the total number of requests)

  • Some information about the performance of JS scripts and Stylesheets

  • ANY other useful information.


I have checked out this answer but I am looking for a free online tool which would give me more accurate analysis. I have been testing with



However, all of them give me different results even without cache. I mean, even the page size differs, not only the total requests, load time , etc. This makes me feel there must be something more efficient and accurate that I could use without paying a dime? Any suggestions would be helpful.


Select -> option abstraction

In Python, Java and several other selenium bindings, there is a very convenient abstraction over select->option HTML constructions, a Select class.


For example, imagine there is the following select tag:



<select id="fruits" class="select" name="fruits">
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>


Here is how we can operate it in Python:



from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id('fruits'))

# get all options
print select.options

# get all selected options
print select.all_selected_options

# select an option by value
select.select_by_value('1')

# select by visible text
select.select_by_visible_text('Mango')


In other words, it is a very transparent and easy to use abstraction.


Is is possible to manipulate select tag in protractor in a similar manner?




This is not a duplicate of How to select option in drop down protractorjs e2e tests or How to click on option in select box in Protractor test?.


InteliJ IDEA - Order of Execution JUnit Tests

How can I order the execution of my test methods at InteliJ IDEA in the same order that it appears in the testing class? I only found the button to "sort alphabetically"


Insert value to div

I have HTML + Angular looks like this:



<div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell ng-scope ui-grid-coluiGrid-15T" ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader }" ui-grid-cell="">
<div class="ui-grid-cell-contents ng-binding ng-scope ui-grid-cell-focus" tabindex="-1">33</div>
</div>


and it looks like:


enter image description here


And I need to add / change value whihch is between divs (in this example it's number 33) How ever i try to sendkey that it's not helping. I double check if my XPATH is correct but still...



var pkValue = "11";
element(by.xpath('(/html/body/div[2]/div/div/div[2]/form/fieldset[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[3]/div)')).sendKeys(pkValue);


Is there something I'm missing or if I need to do something else for this?


Unable to Fetch the Growl Message if we have an interval to get hide after 5 sec

I am writing test cases in protractor E2E. I want that when I run the case, and when I press save, then a Growl message is shown with success or error.



this.growlMessage = function () {
return element(by.css("div[ng-bind='message.text']")).getText();
}


Now I am able to fetch the message if we are having error because it stays there as long it is closed. But the success message disappears after some time automatically. In Protractor, the case keeps waiting for the Growl to disappear and then perform the next execution. I think protractor is waiting for the growl to finish it work.


How can we wait for this and get the text ?


How to count total number of option of drop-down in protractor

I am trying to verify number of options of drop-down but it is not working. I have used the following code:



campaignManagementPage.statusDropDown().Count();
this.statusDropDown = function () {
return element(by.model('campaign.lifeStage'));
}


HTML for drop down is following:



<select class="form-control ng-pristine ng-valid ng-touched" data-ng- model="campaign.lifeStage">
<option value="design">Design</option>
<option value="preview">Preview</option>
<option value="live">Live</option>
<option value="completed">Completed</option>
</select>`

QTP - Checking dynamic pages





I'm trying to check if a value is contained in the innertext of a webelement but I'm having a little problem: frames seem to change at every refresh of the pages.



These are the steps I've recorded:



Browser("SystemPage").Page("SystemP").Frame("dme2_header").Image("Gestione Anagrafiche").Click Browser("SystemPage").Page("SystemP").Frame("dme2_appl").WebEdit("pdrBean.pdrPod").Set parameter("POD") Browser("SystemPage").Page("SystemP").Frame("dme2_appl").WebButton("Cerca").Click Browser("SystemPage").Page("SystemP").Frame("dme2_appl_2").Image("show_files").Click Browser("SystemPage").Page("SystemP").Frame("dme2_appl_6").Image("Lente").Click cctype = Browser("SystemPage").Page("SystemP").Frame("dme2_appl_7").WebElement("arrow_down").GetROProperty("innertext") DataAct = Browser("SystemPage").Page("SystemP").Frame("dme2_appl_7").WebElement("arrow_down_2").GetROProperty("innertext") Browser("SystemPage").Page("SystemP").Frame("dme2_header").Image("Gestione Anagrafiche").Click



The frames "dme2_appl6" and "dme2_appl7" changes at every refresh of the two pages.

The question is simple: how can I rewrite these two actions to make them universal?


Error: Could not get the Java version. Is Java installed?

I run Appium server:



➜ ~ appium
info: Welcome to Appium v1.3.5 (REV a124a15677e26b33db16e81c4b3b34d9c6b8cac9)
info: Appium REST http interface listener started on 0.0.0.0:4723
info: Console LogLevel: debug
info: --> POST /wd/hub/session {"desiredCapabilities":{"appPackage":"com.grindrapp.android","appActivity":".activity.SplashActivity","platformVersion":"4.4.2","browserName":"","platformName":"Android","deviceName":"10.0.0.9:5555"}}
info: Client User-Agent string: Apache-HttpClient/4.3.4 (java 1.5)
info: [debug] Didn't get app but did get Android package, will attempt to launch it on the device
info: [debug] Creating new appium session 090abe0c-36d9-4f9b-987a-f3b665045928
info: Starting android appium
info: [debug] Getting Java version
info: [debug] Cleaning up android objects
info: [debug] Cleaning up appium session
error: Failed to start an Appium session, err was: Error: Could not get the Java version. Is Java installed?
info: [debug] Error: Could not get the Java version. Is Java installed?
at /usr/local/lib/node_modules/appium/lib/devices/android/android-common.js:1040:17
at ChildProcess.exithandler (child_process.js:735:7)
at ChildProcess.emit (events.js:110:17)
at maybeClose (child_process.js:1008:16)
at Socket.<anonymous> (child_process.js:1176:11)
at Socket.emit (events.js:107:17)
at Pipe.close (net.js:476:12)
info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Could not get the Java version. Is Java installed?)","origValue":"Could not get the Java version. Is Java installed?"},"sessionId":null}
info: <-- POST /wd/hub/session 500 316.738 ms - 222


^C
➜ ~ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_76.jdk/Contents/Home


I try to run this code to post to Appium server:



public class AndroidTest {

private AppiumDriver driver;

@Before
public void setUp() throws Exception {
// File classpathRoot = new File(System.getProperty("user.dir"));
// File appDir = new File(classpathRoot, "../../../data/app/");
// File app = new File(appDir, "Facebook.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability("deviceName","10.0.0.9:5555");
capabilities.setCapability("platformVersion", "4.4.2");
capabilities.setCapability("platformName","Android");
//capabilities.setCapability("app", app.getCanonicalPath());

capabilities.setCapability("appPackage", "com.grindrapp.android");
capabilities.setCapability("appActivity", ".activity.SplashActivity");
driver = new AndroidDriver(new URL("http://ift.tt/1eWSHgW"), capabilities);
}


but as you can see I get this error:



info: [debug] Error: Could not get the Java version. Is Java installed?


how can I fix this?


I'm trying to automatically open an app which i downloaded from the google play and I don't have its apk.


Can the following test conditon be simplified

I have a variable a, if I echo it it gives me.



lrwxrwxrwx 1 root root 23 May 16 2014 ggo -> /export/s1/home/ggo


The following code checks if the owner or group is a number or root. If either the owner or group is a number or root, then it will print the name of directory, in this case ggo.



if [[ $(echo $a|awk "{print \$3}") =~ ^[0-9]+$ ]] || [[ $(echo $a|awk "{print \$3}") == root ]] || [[ $(echo $a|awk "{print \$4}") =~ ^[0-9]+$ ]] || [[ $(echo $a|awk "{print \$4}") == root ]] ; then echo $(echo $a | awk "{print \$9}"); fi;


However can it be simplified?


For example cant the following section be condensed:



[[ $(echo $a|awk "{print \$3}") =~ ^[0-9]+$ ]] || [[ $(echo $a|awk "{print \$3}") == root ]]

How to perform sql injection test on an iOS app on a non-jail broken iphone 5?

I have been involved in security testing of iOS apps lately. The app is running on iOS on iphone 5. This app is similar to "bookmyshow" app, where user can book events occurring at various places in the city.


I need to perform sql injection testing & report security bugs if any. I am literally clueless about this task. Any help would be greatly appreciated.


Note: The device is a normal iphone 5 & jail-broken device is not available.


Thanks in advance,


Novice_Student


Jquery not loading on ipad

I have created a wordpress theme for a website I'm working on http://learntosmile.net which works fine on firefox, chrome and IE (IE badly but enough) but when I test it on ipad (original, only one I have at hand to test on) it seems that the jquery is not loading in correctly. The burger icon top doesn't load and the scroll to top does not load in at the bottom either.


Is there a way to output an error on ipad that I can test to see what the problem is?


GUI testing by click x,y

I want to ask for help to deal with GUI testing of Web Application.


I'm looking for software where I can write script which will do this:



  • Click (x,y)

  • Write data (like login, password)

  • Check radio and checkboxes

  • Validate output data


And it'd be very big + if it can change between windows.


I was trying to testing GUI by:



  • Selenium

  • JAutomation

  • Sahi


However I couldn't test it by xpath because application:



  • doesn't have unique id

  • classes are changing every reloading

  • absolute xpath depends on sequence of steps performed


Thanks in advance for your help!


jmeter - how to run jmeter for port other than 8080

I have a web app to test whose running port is 9080. So when I set the proxy in the mozilla to localhost and port 8080, and set the port in jmeter 8080, jmeter is unable to fetch data from the port 9080.


I have also tried using the port 9080 in jemter.


Please help !!


A Data Driven Test library for node.js

I was trying to get ddt module ("http://ift.tt/18k84V1") working on my web app I have tried the example they gave on their npm page. what I am looking for is to implement this on my web service. the web service returns JSON object as an API so can I use the ddt module to test if the web service is functioning properly?


if so can you please give me sample how I can do that on express framework


Thanks!


How do I change browser page when ATUreporter does not take screenshos on failed tests

I failed test intentionally just to see if it takes screenshot, the element password_field can't be located on the webpage,


because I gave it wrong xpath - passwordqqq(look up comment in the code below)


when test fails it must take screenshot, but it does not,


so I want to change browser page using setCaptureScreen method, how to call it?


I looked up the api here, but it s poorly documented.



package erjan.testNG.personal_cabinet_login;

//import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.firefox.FirefoxProfile;

import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;

import atu.testng.reports.ATUReports;
import atu.testng.reports.utils.Utils;
import atu.testng.reports.listeners.ATUReportsListener;
import atu.testng.reports.listeners.ConfigurationListener;
import atu.testng.reports.listeners.MethodListener;
import atu.testng.reports.logging.LogAs;
import atu.testng.selenium.reports.CaptureScreen;
import atu.testng.selenium.reports.CaptureScreen.ScreenshotOf;

@Listeners({ ATUReportsListener.class, ConfigurationListener.class,
MethodListener.class })

public class Login_test_no_user {

{
System.setProperty("atu.properties",
"C:\\Users\\www\\ERJAN_NAIMIKZ_ALL\\erjan_2_naimikz_test\\ATUReporter_Selenium_testNG_5.5 BETA");
}

WebDriver firefox ;
@Test
public void main() {
setAuthorInfoForReports();
setIndexPageDescription();

WebElement phone_field = null ;
WebElement password_field = null ;

//setCaptureScreenBrowserpage

ATUReports.add("checking phone, password fields are displayed", "--", "--", "--", LogAs.INFO,null);

try{
phone_field= firefox.findElement(By.xpath("//*[@id=\"login-form\"]/div[1]/span/input"));
//I FAILED THE TEST HERE, the element password_field can't be located on the webpage, because I gave it wrong xpath - passwordqqq
/when test fails it must take screenshot, but it does not
password_field= firefox.findElement(By.xpath("//*[@id=\"login-form\"]/div[2]/span/input[@name=\"passwordqqq\"]"));

Assert.assertNotNull(phone_field);
Assert.assertNotNull(password_field);

Assert.assertTrue(phone_field.isDisplayed());
Assert.assertTrue(password_field.isDisplayed());
}
catch(Exception e){
ATUReports.add("a field is invisible or not available", LogAs.FAILED, new CaptureScreen(
ScreenshotOf.BROWSER_PAGE));
}

ATUReports.add("phone, password are visible",LogAs.PASSED,null);


ATUReports.add("inputting number", "0009999999", "--", "--", LogAs.INFO,null);
phone_field.clear();
phone_field.sendKeys("0009999999");



ATUReports.add("inputting password", "bad_password!!!22222", "--", "--", LogAs.INFO,null);
password_field.clear();
password_field.sendKeys("bad_password!!!22222");

ATUReports.add("click LOGIN button", "--", "--", "--", LogAs.INFO,null);
firefox.findElement(By.cssSelector("input.button.blue")).click();

String newUrl = firefox.getCurrentUrl();

ATUReports.add("check URL", "astana/login", "astana/login", "--", LogAs.INFO,null);

/*
(java.lang.String stepDescription,
java.lang.String inputValue,
java.lang.String expectedValue,
java.lang.String actualValue,
LogAs logAs, CaptureScreen captureScreenshot)*/
try{
Assert.assertEquals("http://ift.tt/19BNkbL", newUrl);
}catch(Exception e ){
ATUReports.add("webpages are not same!", LogAs.FAILED, new CaptureScreen(
ScreenshotOf.BROWSER_PAGE));
}

ATUReports.add("page is same",LogAs.PASSED,null);

// WebDriverWait wait = new WebDriverWait(firefox,3);
// wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='error-text']")));
// WebElement wrong_message = firefox.findElement(By.xpath("//div[@class='error-text']"));

}

private void setAuthorInfoForReports() {
ATUReports.setAuthorInfo("NAIMI.KZ AUTOTEST", Utils.getCurrentTime(),"1.0");
}

private void setIndexPageDescription() {
ATUReports.indexPageDescription = "erjan runs ATUreport";
}


@BeforeMethod
public void beforeMethod() throws IOException {

firefox = new FirefoxDriver();
ATUReports.setWebDriver(firefox);


firefox.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
firefox.get("http://ift.tt/19BNkbL");

}

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

}

mardi 24 février 2015

How to test for finding sensitive information in code?

We have a requirement like , we need to avoid sensitive information from code. Like passwords saved in comments , hard-coded passwords like that. Now i want an approach to find these kind of data in code. We are using shell script. Can anyone suggest a tool or a method for this purpose. Thanks in advance.


Cucumber-JVM Maven Integration issue

I was able to run Cucumber-JVM tests using @RunWith & @CucumberOptions tags.But I am unable to execute the tests using Maven. Can somebody point me in the right direction ?


I am trying to use maven sure fire plugin, after scouring the internet.I do think, I am making a mistake, which I dont't know abt.


UI Appearance testing tool?

I am looking for tools to web applications UI testing. I know that there are many tools like Selenium and similar, but I am looking something for testing UI appearance, not UI behavior. I do not want to test if correct form shows in correct moment. I would like to test charts, graphics and animations.


Example Let assume that I have web application with complex animations created using d3.js. I would like to test appearance with accuracy at the level of individual pixels: size, distance, colors of individual elements, transitions time and even singular frames.


I do not know if it is sensible approach? Do you know of such a tool?


Selenium tests - Everything is printed all the time no matter what

This might sound like a very silly question but here it is:


I'm writing selenium tests in python, and basically my base test class looks like that:



chromedriver = "../selenium-tests/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver

class TestsFoo(unittest.TestCase):
base_url = None
language = None

def setUp(self):
self.driver = webdriver.Chrome(chromedriver)
self.verificationErrors = []
self.accept_next_alert = True
self.driver.set_window_size(1100, 800)


Then all of my other test classes extend from that class. Example:



class TestsFooChild(TestsFoo):
def test_something(self):
driver = self.driver
driver.get("{}{}/myurl.html".format(
self.base_url,
self.language)
)
# do stuff

print driver.current_url
self.assertTrue(somethingTrue)

def tearDown(self):
self.driver.close()
self.driver.quit()


language and url are defined thanks to this:



if __name__ == "__main__":
TestsFoo.base_url = os.environ.get('URL')
TestsFoo.language = os.environ.get('LANGUAGE')
unittest.main()


So that's a lot of informations for a very very tiny question: When doing unittest, if you let a print somewhere, it'll only be printed if the test fails.


Then why in my case, are every prints printed no matter what the result of the test is? I only want to print my current_url when the test fails.


Also, I'm just looking at why it does that. I'm actively working on finding a way to only print it when my test fails. So that part is taken care of. But I'm curious..


Hsqldb Sotred Procedure

I am trying to setup a stored procedure in my in memory Hsqldb database for testing purposes. The stored proc I am working from is developed in MySql so I want to set it up with HSqlDb to fit in with my testing suite


I am trying to create a simplified version of the procedure but having no joy as of yet


The procedure is



CREATE PROCEDURE p_recordTaskExecution(IN userTaskId INT, IN isSuccess BOOLEAN, IN statusMessage VARCHAR(2000), IN operationsPerformed INT, INOUT procedureStatus BOOLEAN)
BEGIN ATOMIC
IF userTaskId = 1 Then
set procedureStatus = true;

ELSE
set procedureStatus = false;

END IF;

END;


The error I am getting when running my tests is as follows



Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement at line 3 of resource class path resource [databaseTesting/inMemory/createInMemoryDatabase.sql]: CREATE PROCEDURE p_recordTaskExecution(IN userTaskId INT, IN isSuccess BOOLEAN, IN statusMessage VARCHAR(2000), IN operationsPerformed INT, INOUT procedureStatus BOOLEAN) BEGIN ATOMIC if userTaskId = 1 Then set procedureStatus = true; nested exception is java.sql.SQLSyntaxErrorException: unexpected end of statement: required: ;
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:475)
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:229)
at org.springframework.jdbc.datasource.init.CompositeDatabasePopulator.populate(CompositeDatabasePopulator.java:60)
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:48)
at org.springframework.jdbc.datasource.init.DataSourceInitializer.execute(DataSourceInitializer.java:108)
at org.springframework.jdbc.datasource.init.DataSourceInitializer.afterPropertiesSet(DataSourceInitializer.java:93)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 40 more
Caused by: java.sql.SQLSyntaxErrorException: unexpected end of statement: required: ;
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.execute(Unknown Source)
at com.jolbox.bonecp.StatementHandle.execute(StatementHandle.java:254)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:460)
... 47 more
Caused by: org.hsqldb.HsqlException: unexpected end of statement: required: ;


I have tried a few things but with no joy


Any help on this would be appreciated


Can't find method attach to controller with angular mock

I'm trying to implement a test with jasmine. But I have issue with the scope of my controller, I'm using the this syntax and not the $scope syntax.


It looks like this:



TeamMemberCtrl = (teamMemberService) ->
this.getMembersInfos = () ->
self = this
teamMemberService.getMembersInfos().then (response) ->
self.members = response.data.members


TeamMemberCtrl.$inject = ["teamMemberService"]
angular.module("allsquareApp").controller "TeamMemberCtrl",TeamMemberCtrl


In my test I try to call getMembersInfos like this:



beforeEach(module('allsquareApp'))

beforeEach inject (_$httpBackend_, _$compile_, $rootScope, $controller, $location, $injector, $timeout, assetService) ->
@scope = $rootScope.$new()
@assetService = assetService
@http = _$httpBackend_
@compile = _$compile_
@location = $location
@controller = $controller
@injector = $injector
@timeout = $timeout
@model = (name) =>
@injector.get(name)
@eventLoop =
flush: =>
@scope.$digest()
@sandbox = sinon.sandbox.create()

afterEach ->
@http.resetExpectations()
@http.verifyNoOutstandingExpectation()


describe 'TasksController', ->
self = @
beforeEach ->
self.teamCtrl = @controller('TeamMemberCtrl')
console.log(self.teamCtrl)
@response = {
"members": [
{
"imageLink": "landing/patrick_rahme.jpg",
"memberName": "Patrick Rahme",
"memberTitle": "Co-founder/CEO",
"memberLocation": "Luxembourg / San Francisco",
"memberEmailLink": "mailto:patrick@allsquaregolf.com",
"memberDescription": "Patrick's passion for golf, curiosity for technology and attention to detail are at the heart of All Square. As a past national golf champion who speaks 5 languages fluently, Patrick loves to engage with people on and off the golf course.",
"memberEmail": "patrick[at]allsquaregolf.com",
"memberTwitter": "http://ift.tt/1ae9Tng",
"memberLinkedin": "http://ift.tt/1A3LpC2",
"memberGooglep": "http://ift.tt/1ae9Rf9"
}
]
}
# console.log(@assetService.getTeamMembersInfosPath())
@http.whenGET(@assetService.getTeamMembersInfosPath()).respond(200, @response)


describe 'load', ->
it 'sets up the list of current tasks', ->

console.log(self)
self.teamCtrl.getMembersInfos()
@http.flush()


The console log of the teamCtrl, it doesn't contain the definition of my method attached to this in my controller:



function () {
var self;
self = this;
return teamMemberService.getMembersInfos().then(function(response) {
return self.members = response.data.members;
});
}


My error is:



TasksController load sets up the list of current tasks
TypeError: 'undefined' is not a function (evaluating 'self.teamCtrl.getMembersInfos()') in file:///Users/francklavisse/Documents/workspaces/rails-app/spec/javascripts/tmp/assets/app/controllers/teamMemberCtrl_spec.js (line 60)
TypeError: 'undefined' is not a function (evaluating 'self.teamCtrl.getMembersInfos()')


EDIT1


We find that the controller is evaluating self.getMembersInfos, so it return it, that's not what we want



TeamMemberCtrl = function (teamMemberService) {
var self;
self = this;
return self.getMembersInfos = function () {
self = this;
return teamMemberService.getMembersInfos().then(function (response) {
return self.members = response.data.members;
});
};
};

'equal' is not defined : Ember-qunit does not seem to be importing

It appears the Qunit test methods aren't available even though I'm pretty sure I am importing them correctly.


I get the following errors:



unit/models/friend-test.js: line 11, col 3, 'ok' is not defined.
unit/models/friend-test.js: line 17, col 3, 'equal' is not defined.
unit/models/friend-test.js: line 23, col 3, 'equal' is not defined.
unit/models/friend-test.js: line 31, col 3, 'equal' is not defined.
unit/models/friend-test.js: line 32, col 3, 'equal' is not defined.


I have this test file unit/models/friend-test:



import Ember from 'ember';
import { moduleForModel, test } from 'ember-qunit';


moduleForModel('friend', 'Friend', {
needs: ['model:article']
});

test('it exists', function() {
var model = this.subject();
ok(model);
});

test('fullName concats first and last name', function() {
var model = this.subject({firstName: 'Syd', lastName: 'Barrett'});

equal(model.get('fullName'), 'Syd Barrett');

Ember.run(function() {
model.set('firstName', 'Geddy');
});

equal(model.get('fullName'), 'Geddy Barrett', 'Updates fullName');
});

test('articles relationship', function() {
var klass = this.subject({}).constructor;

var relationship = Ember.get(klass, 'relationshipsByName').get('articles');

equal(relationship.key, 'articles');
equal(relationship.kind, 'hasMany');
});


I'm working through "Ember CLI 101"


Manifest and setup issues getting Robolectric working with Android Studio 1.1.0

I am trying to get Robolectric tests up and working in our current project, and not having a lot of luck. My preference would be to get these to run within Android Studio 1.1.0+. This is my project structure:


enter image description here


and here is my test:



import android.widget.Button;

import com.mycompany.android.app.R;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertNotNull;

@Config(manifest = "AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class SplashActivityTest {

private SplashActivity splashActivity;

@Before
public void setup() {
splashActivity = Robolectric.buildActivity(SplashActivity.class).create().start().resume().get();
}

@Test
public void shouldNotBeNull() {
Button signUpButton = (Button) splashActivity.findViewById(R.id.sign_up_button);
assertNotNull(signUpButton);

Button loginButton = (Button) splashActivity.findViewById(R.id.login_button);
assertNotNull(loginButton);
}

}


No matter what I do to try and get the framework to find the test by changing the path to the manifest, it cannot find it - either I get WARNING: No manifest file found at ./AndroidManifest.xml.Falling back to the Android OS resources only. messages, or API Level XX is not supported - Sorry! messages. In the end, I think this is the reason I'm getting the following errors when the test runs:



android.content.res.Resources$NotFoundException: unknown resource 2130903074


I do have the experimental option turned on, have the right Gradle plugin configured (unit tests work fine), but I'm not sure what I'm missing to get instrumentation tests up and running.


App-level build file:



apply plugin: 'org.robolectric'

testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.9.5'
testCompile 'org.robolectric:robolectric:2.4'
testCompile 'org.hamcrest:hamcrest-core:1.1'
testCompile 'org.hamcrest:hamcrest-library:1.1'
testCompile 'org.hamcrest:hamcrest-integration:1.1'


Top-level build file:



dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.0'
}

Symfony2 testing: Why should I use fixtures instead of managing data directly in test?

I'm writing some functional tests for an API in Symfony that depend on having data in the database. It seems the generally accepted method for doing this is to use Fixtures and load the fixtures before testing.


It seems pretty daunting and impractical to create a robust library of Fixture classes that are suitable for all my tests. I am using the LiipFunctionalTestBundle so I only load the Fixtures I need, but it only makes things slightly easier.


For instance, for some tests I may need 1 user to exist in the database, and other tests I may need 3. Beyond that, I may need each of those users to have slightly different properties, but it all depends on the test.


I'd really like to just create the data I need for each test on-demand as I need it. I don't want to pollute the database with any data I don't need which may be a side effect of using Fixtures.


My solution is to use the container to get access to Doctrine and set up my objects in each test before running assertions.


Is this a terrible decision for any reason which I cannot foresee? This seems like a pretty big problem and is making writing tests a pain.


Another possibility it to try and use this port of Factory Girl for PHP, but it doesn't seem to have a large following, even though Factory Girl is used so widely in the Ruby community to solve this same problem.


Flask test_client can't handle HTTP 204 No data

I have delete endpoint, returning HTTP 204



@blueprint.route('/foo', methods=['DELETE'])
def delete_tag(id):
# ....
return '', 204


and I want to test it



def test_delete_tag(self):
resp = self.client.delete(url_for('tags.delete_tag', id=1))
self.assertEqual(resp.status_code, 204)


but I got exception



Traceback (most recent call last):
File "tests/tags_test.py", line 31, in test_delete_tag
resp = self.client.delete(url_for('tags.delete_tag', id=1)})
File ".virtualenvs/...site-packages/werkzeug/test.py", line 799, in delete
return self.open(*args, **kw)
File ".virtualenvs/...site-packages/flask/testing.py", line 108, in open
follow_redirects=follow_redirects)
File ".virtualenvs/...site-packages/werkzeug/test.py", line 742, in open
response = self.run_wsgi_app(environ, buffered=buffered)
File ".virtualenvs/...site-packages/werkzeug/test.py", line 659, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File ".virtualenvs/.../site-packages/werkzeug/test.py", line 885, in run_wsgi_app
buffer.append(next(app_iter))
StopIteration


with response status 200 it works all fine. Is there way how to fix the test?


R: How to test/validate unlabeled data in association rules in R?

I produced association rules by using the arules package. I'm left with +/- 250 rules. I would like to test/validate the rules that I have, like answering the question: How do I know that these association rules are true? How can I validate them? What are common practice to test it?


I thought about cross validation (with training data and test data) as I read that it's not impossible to use it on unsupervised learning methods..but I'm not sure if it makes sense since I don't use labeled data.


I uploaded an example of the data that I use here: http://ift.tt/1BMgl0c


If someone has a clue, even if it's not specifically about association rules (but testing other unsupervised learning methods), that would also be helpful to me.


How to change the display order of properties within an object passed to a method (WCF)

I have a couple of service methods that take an object as a parameter. In the WCF Test Client, the object's properties are displayed in alphabetical order. It would be expedient if we could list certain properties together. Is there a way to do this with an attribute or such like?


Google Test pre-build VS 2013

I have a solution which was compiled with compiler VS2008. It was working perfect. It is instrumented with Google Test and the Google Test library is linked to the solution. the gtest.lib should be compiled with the same compiler as the solution itself, as far as I know.


Now, I have to compile this same solution with VS2013. I get this compilation error



Error 3 error LNK2038: mismatch detected for '_MSC_VER':
value '1700' doesn't match value '1800'


I think that I should get the library for Google Test compiled with Visual Studio 2013.


I cannot find such thing. Could you give me a hint at the Google Test library I should go for ?


How to inject "application_id" in some test endpoint "/v1/random-session/{id}/submit"?

I am reading endpoints from xls file for testPlan creation and i have to do series of test on various endpoints to check the functionality. But the application_id is generated only after the first request and then it is available by the static util class. How should i structure end points in my xls which have the application_id generated at the session start? What is the best java API that i can use to inject application_id in place of {id} in the end-point?


Thanks in advance for your help!


Merge test reports from different test runs (Protractor, Karma)

I'm looking for a tool which is able to join my reports which are generated from different test runs. Let's say I have a certain build which runs my E2E from Protractor on 20 VM's how can I join those reports and create one summary out of it automatically.


lundi 23 février 2015

how to enter text in an edittext and press done using robotium

i have an edittext in my activity view i tried adding text into it using solo.entertext().this method enters the text into the edittext correctly then i need to click on done/enter which is not happening i tried various methods but none worked here are some which i tried for key done/enter



editText.onEditorAction(EditorInfo.IME_ACTION_DONE);
solo.sendKey(KeyEvent.FLAG_SOFT_KEYBOARD);
solo.pressSoftKeyboardNextButton();
solo.sendKey(KeyEvent.ACTION_DOWN);
solo.sendKey(KeyEvent.KEYCODE_ENTER);


when i run the test menu items are clicked.


EmberJS no model was found but it's there

I'm writing an ember-cli app. I have the following model:



// app/models/school.js
export default DS.Model.extend({
name: DS.attr('string', { defaultValue: '' })
});


It was generated using an ember generator like all my other models. It has a functioning unit test as well that tests for the default value of it's name attribute. All tests are green until another model belongs to school like this:



// app/models/professor.js
export default DS.Model.extend({
name: DS.attr('string', { defaultValue: '' }),
email: DS.attr('string', { defaultValue: '' }),

courses: DS.hasMany('course'),
posts: DS.hasMany('post'),
school: DS.belongsTo('school')
});


This test is totally green until I add the school attribute. It's even green with 'model:school' defined in the needs array of the moduleForModel helper:



// tests/unit/models/professor-test.js
// this is green w/o belongsTo('school') in the model
moduleForModel('professor', {
// Specify the other units that are required for this test.
needs: ['model:school', 'model:post', 'model:course']
});


The error I'm getting is:



Error: No model was found for 'school'


Here's the models directory



$ ls app/models/
course.js post.js professor.js school.js student.js


Why is it not finding my model?