mardi 31 mars 2015

Scrolling on a number picker using robotium?

Can anyone suggest me how to scroll over a number picker in order to change the number to be selected?Using robotium? i Came across the following but i cant figure out how to use it scrollBy(x,y) i used the following and it dint seem to work


solo.getView(R.id.numberPicker1).scrollBy(0,100);


How to make a job that contains a test in Jenkins

I have a project on github.com. It's placed in one repository: http://ift.tt/1OXwmoq Here is a gulpproject. But there are also some tests:



  • protractor.conf.js

  • karma.conf.js

  • e2e-tests.js


I use Jenkins to make a build pipeline of my project (with the pluginà). I can make a job that builds the whole project but that isn't very useful. So I want to split it up and I want some jobs between my pipeline that can run the tests. So for example first a build of the project. Than run some tests to check there aren't foulds in it, and at least deploying it.


Is there anyone who can explain me how to integrate the tests in different jobs so I can test first before I will deploy?


Any automation tool for testing RFC and ODATA..?

I have been testing the RFC's and ODATA manually and it's taking too long, Can anyone suggest Automation tool for testing RFC and ODATA


Simulate connection errors

We've been using protractor for end-to-end testing for a while.


Now we are trying to cover several corner cases, which involves modifying the response from the API endpoint requests - for this we are using protractor-http-mock which provides an easy-to-use way to replace HTTP responses with pre-defined mocks.


But, what if we want to test a situation when a sudden connection loss happens? What are our options in this case?


In other words, we want to achieve a case when requests to specific endpoints would produce a network connection error and see how our application would react.




I'm open to any suggestions, I am currently thinking of the following strategies:



  • see if there are third-party nodejs libraries similar to protractor-http-mock

  • fire up a proxy and somehow control it during the tests (grunt-connect-proxy looks pretty mature though I'm not sure if it is possible to dynamically change the behavior of the proxy from spec to spec)

  • control it on a browser level - e.g. with a Network Throttling google chrome feature (though I'm pretty sure it is something that selenium cannot control, Network throttling with chrome and selenium)


How can I get Jasmine to wait for a Meteor method call to complete without resorting to setTimeout?

I'm writing a client integration test to verify a particular user can change roles on other users via the front-end.



it('should be able to change user roles', function(done) {
var newUser = Meteor.users.findOne({ emails: { $elemMatch: { address: 'devon@radworks.io' } } });
$('#user-' + newUser._id + '-roles').val('manage-users').change();
expect(Roles.userIsInRole(newUser, 'manage-users')).toBe(true);
expect(Roles.userIsInRole(newUser, 'edit-any')).toBe(false);
done();
});


The change() event is bound to a function that calls a Meteor method to change the roles.



Template.users.events({
'change .change-roles': function(e) {
e.preventDefault();
var newRoles = $(e.target).val() || [];
Meteor.call('changeRoles', this._id, newRoles);
}
});


Here's the Meteor method:



Meteor.methods({
'changeRoles': function (userToChangeId, newRoles) {
check(this.userId, String);
check(userToChangeId, String);

if (!Roles.userIsInRole(this.userId, 'manage-users')) {
throw new Meteor.Error('Not authorized to manage user roles');
}

// If the current logged in user is the one we are changing, add manage-users back to
// the list of new roles.
if (userToChangeId === this.userId) {
newRoles.push('manage-users');
}

if (Meteor.users.find(userToChangeId).count() !== 1) {
throw new Meteor.Error('invalid', 'Unable to find the user you want to change');
}

Roles.setUserRoles(userToChangeId, newRoles);
}
});


My test fails even though I can run the test manually and get the expected results. I believe it fails because Roles.setUserRoles has not yet completed by the time I run the expect in my test. I want to wait on the method to complete without simply putting the expect behind a setTimeout. What's the pattern for doing this?


How to have a fixture loaded for Django tests in the test runner?

I have a large set of Django test cases, all of which subclass either TestCase or TransactionTestCase. I need to add a fixture to all test cases (to handle a new way of handling settings in the database).


I could of course add the fixture to the fixtures attribute of every test case. Or I could change the test cases to subclass from a custom test case subclass that sets this fixture -- and then change all existing test case fixture settings to extend rather than override the parent class fixture settings.


Either of the above would be tedious and error prone in this particular case.


So -- is there any way to get the test runner to always add a fixture to each test case as it's run?


Simulating iOS opening an app fresh in the background

I have a crash in an iOS app that I believe it triggered from iOS opening the app in the background. I'd like to be able to test this hypothesis, but am not sure if I can trigger iOS to open a closed app in the background for testing purposes.


I am specifically looking to have iOS open this app fresh - i.e. not when the app is still active and placed in the background, but when the app is fully closed and iOS triggers a re-open.


Is this possible?


angular chained orderby not updating when running protractor tests in browser

I am currently facing an issue with angular's ng-repeat directive containing multiple, piped filters when running it during a Protractor test suite. Although I can see Protractor click the sort/toggle button, the list does not change as it should. I expect it to sort the list and only show some items when clicking special toggle buttons.


However, when I execute all the commands manually (in the same browser!), it works just fine!


Please find how I call Protractor:



element(by.id('customers_sort_id')).click();
browser.driver.sleep(500);
browser.waitForAngular();
expect(element.all(by.repeater('c in list.customers')).get(0).all(by.tagName('td')).first().getText()).toEqual('500');


I have built in the sleep() command as well as the waitForAngular() call just for debugging reasons, but they also change nothing.


This is the HTML:



<tr class="clickable" ng-repeat="c in list.customers | filter : list.companyFilter.visible | filter : list.searchFilter | orderBy : list.orderBy : list.reverse" ng-click="detailOn(c.id)">


This is how the filter variable is set:



$scope.toggleSort = function(column) {
if($scope.list.orderBy == column) {
$scope.list.reverse = !$scope.list.reverse;
}
$scope.list.orderBy = column;
};


Neither the orderBy nor the reverse filter do anything.


Does anyone have an idea, why?? Thanks for any input!


How to generate test coverage report in Meteor / Velocity?

The Velocity documentation mentions test coverage as a primary feature of the framework, but I'm having a hard time finding specific instructions for getting started.


Is there support for test coverage reporting in Meteor / Velocity (either directly or via a third-party package)?


How do you test/spoof a users geolocation in MVC.NET?

I'm working with a .NET team who have created a site that serves up different content based on a users location.


How would I go about testing/spoofing the geolocation so I can debug the front-end?


Trouble with ant compiler

Today I am using Fedora 21 and I installed ant compiler, but when I am trying to test, this issue comes.





[mhernandez@localhost practica1]$ ant test
Buildfile: /home/mhernandez/Estructuras de Datos/practica1/build.xml

compile.practica1:

practica1.jar:

test:

BUILD FAILED
/home/mhernandez/Estructuras de Datos/practica1/build.xml:63: Problem: failed to create task or type junit
Cause: the class org.apache.tools.ant.taskdefs.optional.junit.JUnitTask was not found.
This looks like one of Ant's optional components.
Action: Check that the appropriate optional JAR exists in
-/usr/share/ant/lib
-/home/mhernandez/.ant/lib
-a directory added on the command line with the -lib argument

Do not panic, this is a common problem.
The commonest cause is a missing JAR.

This is not a bug; it is a configuration problem


Total time: 0 seconds



The problem is that I don't know how to put that missing jar in that folder. I already download the .zip from ant.apache.org and I have all the jars, I just want to put them in the correct folder.


Javascript Unit test

I have a javascript app within 250 lines and want to add tests to that. Whenever i make a tiny change, i have to run tests for atleast 10 cases manually, which i want to automate.


I could have gone for frameworks as suggested in different posts, but the solution i want is minimum friction and codebase. Something like a single file for unit testing may work.


Is there a way for using JS testing without any frameworks ? I want to write Unit tests / functional tests both. Or if Frameworks is the only option, what frameworks are preferred in terms os ease of plugin to existing code + learning curve.


Jasmine test not firing 'click' event in test

I'm trying to create a test for Google Analytics but it looks like the event 'click' doesn't get fired.


Here's my code



trackEvent: function() {

$eventID = $('[data-trigger="click"]');

$eventID.on('click', function() {
var element = $(this);
var eventCategory = element.data('category') ? element.data('category') : '',
eventAction = element.data('action') ? element.data('action') : '',
eventLabel = element.data('label') ? element.data('label') : '',
eventSocialNetwork = element.data('socialNetwork') ? element.data('socialNetwork') : '',
eventSocialAction = element.data('socialAction') ? element.data('socialAction') : '',
eventSocialTarget = element.data('socialTarget') ? element.data('socialTarget') : '';

if(eventCategory !== '' && eventAction !== '' && eventLabel !== '') {

ga('send', {
'hitType': 'event',
'eventCategory': eventCategory,
'eventAction': eventAction,
'eventLabel': eventLabel
});
}

if(eventSocialNetwork !== '' && eventSocialAction !== '' && eventSocialTarget !== '') {

ga('send', {
'hitType': 'social',
'socialNetwork': eventSocialNetwork,
'socialAction': eventSocialAction,
'socialTarget': eventSocialTarget
});
}

});
},


Here's my test


it('should fire social interaction event', function() {



var theDiv = sandbox({
'id': 'social-facebook',
'data-trigger': 'click',
'data-socialNetwork': 'facebook',
'data-socialAction': 'share',
'data-socialTarget': 'url'
});


$(document.body).append(theDiv);

eventTracker.trackEvent();
var event = jQuery.Event('click');
event.target = jQuery('#social-facebook')[0];

jQuery('#social-facebook').trigger('click');

expect(window.ga).toHaveBeenCalledWith('send', {
'hitType': 'social',
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': 'url'
});

});

git workflow: local, test and prod server

Here is my git workflow:


git workflow


Explanation :



  1. In local, I develop one feature Feat1 and I push it to the Dev branch once it's done. Same thing for Feat2.

  2. On the test server, I pull the Dev branch (the 2 features are now on the test server).

  3. Once the 2 features are tested and approved, I push the Dev branch to the Master branch.

  4. On the production server, I pull the Master branch (the two features are now on the production server).


The problem is: what if I want to push only Feat1 on the production server? Only Feat2? In this case, is the current workflow a good workflow?


Testing promises and sync functions that throw errors

I'm trying to build and test a function at the same time. Testing makes sense and I love it in theory, but when It comes down to it it always is a pain in the behind.


I have a function that takes a string and throws errors when something goes awry if all goes well it's going to return the original text argument and therefore a truthy value, if not it should be caught by the promise it's either in or itself as the promise.


This is the test / what I actually want to do (which doesn't work).



var main = require("./index.js")
var Promise = require("bluebird")
var mocha = require("mocha")
var chai = require("chai")
var chaiPromise = require("chai-as-promised")
chai.use(chaiPromise)

var shouldThrow = [
"random", // invalid non-flag
"--random", // invalid flag
"--random string", //invalid flag
"--wallpaper", // invalid flag w/ match
"--notify", // invalid flag w/ match
"wallpaper", // valid non-flag missing option(s) image
"wallpaper image.jpg" // invalid flag value
"wallpaper http://ift.tt/1G3L9LT", // invalid flag value
"wallpaper //cdn.shopify.com/s/files/1/0031/5352/t/28/assets/favicon.ico?12375621748379006621", // invalid flag value
"wallpaper http://ift.tt/1FecoQO", // invalid flag value
"wallpaper http://ift.tt/1G3L9LV", // invalid flag value
"wallpaper http://ift.tt/1Fecqs1", // invalid flag value
"wallpaper http://ift.tt/1G3L76O --queue", // invalid flag value
"wallpaper http://ift.tt/1G3L76O --queue "+moment().subtract(1, "month").format("YYYY-MM-DD-HH-mm"), // invalid flag value
"wallpaper http://ift.tt/1G3L76O --queue "+moment().add(1, "month").format("YY-MM-DD-HH"), // invalid flag value
"wallpaper --image http://ift.tt/1G3L9LT", // invalid flag value not https
"wallpaper --image //cdn.shopify.com/s/files/1/0031/5352/t/28/assets/favicon.ico?12375621748379006621", // invalid flag no protocol
"wallpaper --image http://ift.tt/1FecoQO", // invalid flag value not https
"wallpaper --image http://ift.tt/1G3L9LV", // invalid flag value not valid image
"wallpaper --image http://ift.tt/1Fecqs1", // invalid flag image not found
"wallpaper --image http://ift.tt/1G3L76O --queue", // invalid subflag queue missing value
"wallpaper --image http://ift.tt/1G3L76O --queue "+moment().subtract(1, "month").format("YYYY-MM-DD-HH-mm"), // invalid subflag queue date value is past
"wallpaper --image http://ift.tt/1G3L76O --queue "+moment().add(1, "month").format("YY-MM-DD-HH"), // invalid subflag queue date value format
"--wallpaper --image http://ift.tt/1G3L76O", //no action non-flag
"--wallpaper --image http://ift.tt/1G3L76O --queue "+moment().add(1, "month").format("YYYY-MM-DD-HH-mm"), //no action non-flag
"notify", // valid non-flag missing option(s) message, open
'notify --message "Hello world"', // valid flag missing params open
'notify --open "https://www.holstee.com"', // valid flag missing params message
'notify --message "Hello world" --open "http://www.holstee.com"', // invalid subflag value `open` should be https
'notify --message "Hello world" --open "https://www.holstee.com" --queue', // invalid subflag queue missing value
'notify --message "Hello world" --open "https://www.holstee.com" --queue '+moment().subtract(1, "month").format("YYYY-MM-DD-HH-mm"), // invalid subflag queue date value is past
'notify --message "Hello world" --open "https://www.holstee.com" --queue '+moment().add(1, "month").format("YY-MM-DD-HH"), // invalid subflag queue date value format
'--notify --message "Hello world" --open "https://www.holstee.com"', //no action non-flag
'--notify --message "Hello world" --open "https://www.holstee.com --queue "'+moment().add(1, "month").format("YYYY-MM-DD-HH-mm"), //no action non-flag
]

var shouldNotThrow = [
'notify --message "Hello world" --open "https://www.holstee.com"',
'notify --message "Hello world" --open "https://www.holstee.com --queue "'+moment().add(1, "month").format("YYYY-MM-DD-HH-mm"),
"wallpaper --image http://ift.tt/1G3L76O",
"wallpaper --image http://ift.tt/1G3L76O --queue "+moment().add(1, "month").format("YYYY-MM-DD-HH-mm"),
]

describe('Process Text', function(){
return Promise.each(shouldThrow, function(option){
it('throw error', function(){
return main.processText(option).should.throw()
})
})
return Promise.each(shouldNotThrow, function(option){
it('throw error', function(){
return main.processText(option).should.not.throw()
})
})
})


Here's a snapshot of the non-working* function I'm trying to test.



main.processText = function(text){
// general validation
var args = minimist(text.split(" "))
var argKeys = _.chain(args).keys().without("_").value()
var topLevelFlags = _.keys(flags)
var topLevelActions = _.chain(flags).keys().without("queue").value()
var allFlags = _.chain(flags).map(function(subFlags, key){
return subFlags.concat(key)
}).flatten().value()

var accidental = _.intersection(allFlags, args._)
var correct = _.map(accidental, function(flag){
return "--"+flag
})
if(accidental.length) throw new Error("non-flag data present / "+ accidental.join(",") + " should be: " + correct.join(","))
if(!args._.length) throw new Error("invalid non-flag data present")

var difference = _.difference(allFlags, argKeys)
var intersection = _.intersection(allFlags, argKeys)
var invalid = _.without.apply(_, [argKeys].concat(intersection))
if(intersection.length !== argKeys.length) throw new Error("invalid flags / "+ invalid)
var topLevelIntersection = _.intersection(topLevelActions, argKeys)
if(topLevelIntersection.length > 1) throw new Error("too many top-level flags")
if(args.wallpaper){
// wallpaer validation
var parsedUrl = url.parse(args.wallpaper)
if(!parsedUrl.hostname) throw new Error("hostname is missing, might be local file reference")
if(parsedUrl.protocol !== "https") throw new Error("image protocol should be https")
var fileExtension = path.extname(parsedUrl.path)
if(!_.contains([".png", ".jpg", ".jpeg"], fileExtension)) throw new Error("wallpaper image is invalid file type")
}else if(args.notify){
// notify validation
if(args.notify !== true) throw new Error("notify shouldn't have value")
var notifyIntersection = _.intersection(args.notify, flags.notify)
var missing = _.without.apply(_, [args.notify].concat(notifyIntersection))
if(missing) throw new Error("notify missing required param: "+ missing.join(","))
}
}


Note its not a promise and doesn't return any promises yet. One of the validation features I want is to check a if a url responds in a 200 status code, that's gonna be a request promise. If I update this function then does all of the function contents need to be nested within a Promise.resolve(false).then()? Perhaps the promise shouldn't be in this block of code and all async validation operations should exist somewhere else?


I don't know what I'm doing and I'm a little frustrated. I'm of course looking for some golden bullet or whatever that will make sense of all this.


Ideally I could use some help on how to test this kind of function. If I make it into a promise later on I still want all my tests to work.


I am trying to pass my junit test but keep getting the error nullpointerexception


error: java.lang.NullPointerException at StoryTests.testSaveToDB(StoryTests.java:57)



I am not sure what the error is but do need my test to pass, if anyone has any idea please let me know.



public class StoryTests {

public StoryTests() {
}

ITmagazineSystem testStory;

/**
*
*/
@BeforeClass
public static void setUpClass() {
ITmagazineSystem testStory = new ITmagazineSystem();
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}

@Test
public void testSaveToDB() {
String title = "";
String StoryID = "s200";
String StoryTitle = "ASE";
String StoryType = "Computing";
String StoryContent = "aaaa";
testStory.saveToDB(StoryID, StoryTitle, StoryType, StoryContent);

try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/magazine", "root", ""); // database connection

Statement stmt = (Statement) con.createStatement();

//String searchTitle = "Select StoryTitle from stories where StoryTitle = '" + txtstoryTitle.getText();
String searchTitle = "Select StoryTitle from stories where StoryTitle = '" + StoryTitle + "'";

ResultSet rs = stmt.executeQuery(searchTitle);
while (rs.next()) {

title = rs.getString("StoryTitle");
}
}
catch (Exception e) {
}
assertTrue(title.equals(StoryTitle));
}
}

how to detect if keyboard is showing or no?

I am showing and hiding the keyboard after certain events. Now i want to know how to detect from code if the keyboard is up/showing or no. I tried the following but none work?



InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.isAcceptingText();
imm.isActive();

Testing push application in emulators

I have a lot of experience in web automated testing but right now i've started to test mobile applications as well I'd like to automatize a product by using emulators, which is basically a tool that manage push/pull notifications Do You think it's possible and also that the result may satisfy us ?


Testing primary task

I would like to solve the following testing problem. If there is an error i.e. (=1/0) in a cell, the additional tests will not run after that. I would like to know how to solve this issue in the testing primary task part.



Private Sub ts_NoBlank(TsCn, STST, LsSt, LsIn, TsRw, MsCo, MsIC, MsSt)
Dim TsCl, StRw, LsRw, TsSh
TsCl = ColNrOfField(TsCn)
StRw = FsRwOfField(TsCn) + 1
LsRw = LsRwOfField(TsCn)
TsSh = SheetOfField(TsCn)

' Setting up Status Updates
PLcSt = -1 'Starting previous local status is set to -100% to show eitherways
rws = LsRw - StRw
'this part has to be copied to whenever showing the status (Value of LcSt has to be added each time by function)
LcSt = 0
If LcSt - PLcSt >= LsIn Then
Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
PLcSt = LcSt
End If

' Testing primary task
ErrNr = 0
For Rw = StRw To LsRw 'ToDo speed up with fromrow torow
If Len(ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl)) = 0 Then
ThisWorkbook.Sheets(TsSh).Cells(Rw, TsCl).Interior.ColorIndex = 46
ErrNr = ErrNr + 1
End If

'Showing Local Status
LcSt = 0.1 + ((Rw / LsRw) * 0.75)
If LcSt - PLcSt >= LsIn Then
Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
PLcSt = LcSt
End If

Next Rw
' Updating Test Results on 'Testing' Page

TRRg = "test" & TsRw & "_results"
If ErrNr = 0 Then 'If Results are Positive
ThisWorkbook.Worksheets("Testing").Range(TRRg) = MsCo
ThisWorkbook.Worksheets("Testing").Range(TRRg).Interior.ColorIndex = 51
Else 'If Errors are found
ErrMS = NumberizeMessage(MsIC, "SP_textvers", "S_textvers", "P_textvers", ErrNr)
ThisWorkbook.Worksheets("Testing").Range(TRRg) = ErrMS
ThisWorkbook.Worksheets("Testing").Range(TRRg).Interior.ColorIndex = 3
End If

'Showing Local Status
LcSt = 0.1
If LcSt - PLcSt >= LsIn Then
Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
PLcSt = LcSt
End If

' Highlighting erroneous cells (if not done during testing)
If ErrNr > 0 Then

End If
'Showing Local Status 100%
LcSt = 1
If LcSt - PLcSt >= LsIn Then
Call ShowStatus(MsSt & " (" & Application.WorksheetFunction.Text(LcSt, "0%") & ")", ThisWorkbook.Worksheets("Calculations Running").Range("Started"), STST + (LsSt - STST) * LcSt)
PLcSt = LcSt
End If

End Sub

greenmail server not receiving the mail



  • My Unit Test for class for email through Greenmail


    @Before public void testSmtpInit() { greenMail = new GreenMail(ServerSetupTest.SMTP); greenMail.start(); messageTemplateService = mock(MessageTemplateService.class); emailProperties = mock(EmailProperties.class); emailService.setEmailProperties(emailProperties); }


    @Test public void testEmail() throws InterruptedException, IOException {



    String to = "abc@localhost.com";
    String from = "test@localhost.com";
    String subject = "subject";
    String contentType = "text/html";
    String user = "test@localhost.com";
    String login="test@localhost.com";
    String password = "12345";
    String body = "msgbody";
    greenMail.setUser(login,user, password);
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", ServerSetupTest.SMTP.getPort());
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);

    try {
    msg.setFrom(new InternetAddress(to));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    msg.setSubject(subject);
    msg.setText(body);
    msg.setSentDate(new Date());
    Transport t = session.getTransport("smtp");
    t.connect(user, password);
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
    } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    MimeMessage[] messages = greenMail.getReceivedMessages();
    assertNotNull(messages);
    assertEquals(1, messages.length);
    MimeMessage m = messages[0];
    try {
    assertEquals(subject, m.getSubject());
    assertTrue(String.valueOf(m.getContent()).contains(body));
    assertEquals(to, m.getFrom()[0].toString());//
    } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    }




  • I used this code to test the email server on junit.




  • But the server does not return any message




  • what i did wrong.




How to capture JS varible value sin a different java program

I have a JS program handling the communication from iframe to its parent. I am logging the different states on browser window (Inspect element's) console. How could i fetch these state values into my java program for validating/testing. The values are passed from JS in html file. Or if anyone can suggest any other way to validate the communication between parent and iframe.


Any suggestion or guidance will be helpful to move forward, I am stuck. Thanks alot!!


assert which layout is loaded?

i am setting two different layouts,one for landscape mode and one for portrait mode. now i want to assert which one is set public void testOrienationChange() {



getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getInstrumentation().waitForIdleSync();
assert which one is visible/set
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
assert which one is visible/set


how to test which layout is set or visible from test class?


Test DataBinding PropertyPaths

I would like to somehow ensure, that all my bindings in xaml binds to existing property.


Every view has specified type of datacontext using d:DesignInstance and every DataTemplate uses DataType attribute if it cannot be inherited from context (e.g ListBoxItem template).


In visual studio xaml designer, invalid properties are underlined and at runtime I get binding errors in output window.


is there any tool, that could check those errors? I was thinking about some automated UI test, that would go trough entire application and check debug output, but it's quite hard to setup.


if visual studio can parse xaml and identify invalid bindings, at least theoretically it should be possible to do it in unit tests.


How to use casperjs testing frame work in spookyjs?

I'm trying to use casperjs's testing framework in spookyjs with the casperjs test command but it is not working.


findViewById() returns null while using it in test clas?

I have a layout (main_layout) that i inflate in the fragment. Now when i try to access it from test class using the following:



View testLayout=getActivity().findViewById(R.layout.main_layout);


It returns to me null? Can anyone tell me whats the wrong thing i am doing?


How can i compare the arrays userResponse and correctAnswers in the gradeAnswers function. It is the only pary not functioning properly


def main():

correctAnswers = ['B','D','A','A','C',
'A','B','A','C','D',
'B','C','D','A','D',
'C','C','B','D','A']

userResponse = userAnswers()
correct = gradeAnswers(correctAnswers, userResponse)
passFail(correct)


#function to obtain the users input for answers and put in an array
def userAnswers():

answers = 1

userResponse = ['','','','','','','','','','',
'','','','','','','','','','',]

for answers in range (20):
print('What is the answer to number ',\
answers + 1, '? ',sep='',end='')
userResponse[answers] = str(input())


print(userResponse)
return userResponse




#function to calculates the amount of correct answers and displays such
def gradeAnswers(correctAnswers, userResponse):
correct = 1
incorrect = 0
index = 1
for correct in range (20):

if userResponse[correct] == correctAnswers[index]:
index += 1
correct += 1**




print('You answered',correct, 'out of 20 questions correctly')

return correct***


#function to determine and display wether the user passed or failed
def passFail(correct):

if correct >= 15:
print('You passed. Good Job')
else:
print('You failed. Do Better')



main()

lundi 30 mars 2015

How to Use Eval Method

I'm having a problem trying to get evaluating a String. My evaluation method is correct so I'm not going to share it, but I can't seem to get the method actually get to the point of evaluation. I've been trying just about everything and it seems like I'm either getting object references, or it want's identifiers, or different types (static vs non-static).


What I want is to know how to get the method eval() to work.


Anyway, here's the code:



public class Postfix
{
String expr;

public Postfix(String e)
{
expr = e;
}

public double eval()
{
stuff;
}
}

Robotium - How can we find the exact index of an element in activity

I ask this question in case we are working in Black box testing.

I have researched about Robotium for few day. I learn by myself from Internet.

I also wrote some simple testcase and run it successfully. But when I search the index element (ex: an Edittext, I have to try index by index form 0 to x and get my expect index id).

Can we have another way to get form name, I have the ID name (txtEd1, btnLogin...), which we can access it form R class in White box testing, but i just ask about Black box in this case.

So can we have another way to get element by id or how can we get exact index number of an element in the activity.

I also used Hierarchy Viewer from DDMS and SDK tool to get index ID but it didn't work.



TextView tw = (TextView) solo.getText(<index>); << how can get exact index number?


Hierarchy Viewer from DDMS Hierarchy Viewer from SDK tool


How can I test an iOS application starting from different initial states?

How can I test an iOS app starting from different initial states? I can fake any initial data for my app (like existing files, data stored in NSUserDefaults, KeyChain, connection availability and so on) and use protocols to avoid dependencies. But my question is how can I pass these parameters to application before it was launched when I run tests from Xcode, since Xcode tests are injected into running app? Ideally I'd like to have an ability to tell Xcode "run these tests from state A and run those tests from state B". Is that possible?


Testing functions that throw exceptions

I'm using tape and I'm trying to test a couple of functions. My functions throw errors and validate objects. I like throwing errors because then later my promises can catch them. I'm trying to run simple tests and establishing the data argument in all the scenarios to hit each error in the stack. How can I test this function without putting it in a try / catch every time? I see there's two functions in the API t.throws() and t.doesNotThrow() , I've tried them both and even added the extra params like t.throws(myFunc({}), Error, "no data") but nothing seems to work as expected.



var test = require('tape')
var _ = require('underscore')

function myFunction(data){
if(!data) throw new Error("no data")
if(_.size(data) == 0) throw new Error("data is empty")
if(!data.date) throw new Error("no data date")
if(!data.messages.length == 0) throw new Error("no messages")
data.cake = "is a lie"
return data
}

test("my function", function(t){
t.throws(myFunction({}))
t.end()
}


I have no loyalty to tape, and I have no clue what I'm doing. I just want to simply test functions synchronous that throw exceptions, without a ton of overhead. So if there's a better unit-testing framework for this use case I'd be glad to use it. If tape has this ability I'd love to use it.


Is this how it should be done?



test("my function", function(t){
try{
myFunction({})
t.fail()
}catch(e){
t.pass(e.message)
}
t.end()
})

How to change the default setting '-DskipTests=true' during Heroku deployment?

I am trying to deploy a Java project from Beanstalk using Heroku. But during the deployment process, the tests are skipped by default. I am aware that the default settings for Dskiptests is true. Is it possible to run tests using Heroku? Where do I change the settings to overwrite the default settings. Here is how the build is started by default:


output -----> Java app detected


output -----> Installing OpenJDK 1.8... done


output -----> Executing: mvn -B -DskipTests=true clean install


Android: Accessing test classes of project A from project B test classes

I have a common library project that could be extended from other lib projects. In my main lib project I have some instrumentation tests and a common class to share code for testing. If I try to use this common class on the tests of the other lib projects, Android Studio does not return any error but gradle does "Cannot find symbol...". Is there any way to share code amongst tests classes of different projects without leaving it on the main source code?


Thanks!


view doesn't load when I mock backend

I'm trying to test one particular element of user interface. To do so I need particular request to my backend to respond with predefined data, but all other requests should pass through. Here's how I do it (coffee for more readability):



describe 'select2 combobox widget', ()->
httpBackendMock = () ->
angular.module 'httpBackendMock', ['ngMockE2E', 'fmAppApp']
.run ($httpBackend)->
dummyCategories = [
{id: 1, name: 'foo', icon: '', user_id: 5},
{id: 2, name: 'bar', icon: '', user_id: 5},
{id: 3, name: 'baz', icon: '', user_id: 5},
{id: 4, name: 'quax', icon: '', user_id: 5}
]

$httpBackend.whenGET '/api/categories'
.respond ()->
[200, dummyCategories]
$httpBackend.whenGET /.*/
.passThrough()
$httpBackend.whenGET /^\/views\//
.passThrough()
$httpBackend.whenGET /^\/scripts\/.*/
.passThrough()
$httpBackend.whenGET /^\/scripts\//
.passThrough()
$httpBackend.whenGET /^\/bower_components\//
.passThrough()
$httpBackend.whenGET(/\.html$/).passThrough()

browser
.addMockModule 'httpBackendMock', httpBackendMock


so basically what I do here is create new module on top of my application module fmAppApp and angular ngMockE2E and tell Protractor about it.


And for the sake of completeness I'll show here one simple statement inside this describe block:



it 'should allow user to type in anything', ()->
browser.get 'http://localhost:9000/#/'
element By.model 'category.selected'
.click()
input = element By.css '.ui-select-search'
input.sendKeys 'newtestcategory'
expect input.getAttribute('value')
.toBe 'newtestcategory'


when I run grunt protractor it opens browser, navigates to specified url (http://localhost:9000/#/) as it should and then I see blank page and spec failures with this error: NoSuchElementError: No element found using locator: by.model("category.selected")


Unfortunately this message is all I have since I can't open firebug and see what went wrong for obvious reasons. I guess I could redirect logging from browser console somehow and see what is root of evil here but I don't know how. Maybe someone encountered that as well and knows what it might be?


Regex pattern for URL in casperjs

In casperJS I'm writing a test to open a URL in popup.


URL be like this [http://ift.tt/1CE7e11{facility_id}/assessments/{assessment_id}/print_preview][1]


I want to get regex for above URL to be use with withPopup(Mixed popupInfo, Function then)


I have tried these regex patterns



  • /assessment/

  • /assessment$/

  • /print_preview/

  • /$print_preview$/


Anyone, please help me in creating right regex for above mentioned URL. Thanks in advace.


How to automatically run tests when running Django runserver?

I'd like to know immediately when I've broken a test in Django. Instead of always running manage.py test separately, is there a way to run tests in the background when running manage.py runserver and report them to that same terminal? The tests would ideally be re-run when a file is saved, just like how the server is reloaded normally.


This would be great to detect mistakes sooner. And even better that it'd be right in your face instead of hiding behind a manual test step.


Is this possible?


What is the process of trace equivalence verification for given 2 FSMs?

Category: Software testing.


Used in the LTSA (Labelled Transition System Analyser) tool for model based verification of web service composition: http://ift.tt/1G8UArH


Also, what is meant by trace equivalence verification?


To my knowledge, trace is a log of execution of a process. In trace equivalence, do we directly compare the trace obtained for both FSMs?


Testing multiple HTML pages with CasperJS?

I'm working with CasperJS on a webpage that has a search box. Using Casper, I'm successfully able to perform a search and see that the form is filled and execute the search, however I'm having trouble specifically getting the number of results to test that it's valid.


When I look at the source of the webpage, I have the XPath of the element and it's nested in a few divs.


But when I try to either do assertExists() on that path, or even return the result of getElementByXPath to a var, it doesn't work.


This is the XPath:



//*[@id="total"]


Here is what the snippet of source looks like:



<div id="pgContent"><div id="results_pagination1_container">
<span style="float: right; font-size: .9em">
Found <span id="total">721</span> item(s)</span>
</div>


This is the CasperJS code, relevant to here.


`



casper.test.begin(

'Testing that we get the right amount of results for a search query',

2, function suite(test) {
casper.start(catapult, function() {
test.assertTitle("Search", "Search"); // Good
test.assertExists('#input-searchbox'); // Good
this.fillSelectors('form#inputForm', {
'input[name="queryStr"]' : 'airplane'
}, true);

//this.click('input#btnSearch');
});
casper.then(function() {
var resultsNum = __utils__.getElementByXPath('//*[@id="total"]');
this.echo(resultsNum);
test.assertExists('//*[@id="total"]');



});`

Testing a Rails Application with Multiple Databases

I have a rails application which uses two databases in production environment, Users and Process. The Users model uses this customized ActiveRecord class:



class UserActiveRecord < ActiveRecord::Base
establish_connection "#{Rails.env}_users_db"
end

class User < UserActiveRecord
...


Notice that the connection to a specific database is established depending on the environment. To simplify things, in the testing environment I have a single database with all the tables from the two production databases, and my database.yml file looks something like this:



test:
adapter: postgresql
database: db_test
host: localhost
pool: ...
timeout: ...
username: ...
password: ...

test_users_db:
adapter: postgresql
database: db_test <--- Notice that this is the same database only in test env
host: localhost
pool: ...
timeout: ...
username: ...
password: ...


The application runs fine in production, but when I run any test that refers to the User class, the test blocks at the exact point where User is used and nothing happens, it doesn't show any error, it doesn't exit, it just keeps waiting.


I double-checked and the table USERS exists in the test database, in fact if I delete it manually I get the error that the table doesn't exists and when I create it again I get the same behavior reported in the previous paragraph.


I don't have a clue why this is happening, any idea on how can I solve this issue? or how can I debug it so that I can get to the root of the problem? Any additional details will be posted as required.


dbfit - How to assert that an item is not returned in the results

I am creating dbfit test cases and I encountered a scenario where I need to check that an item is not included in the results returned by the query. How can I do that?


Thanks,


How to call one script to another script in monkey talk automation tool for iOS

Is there any Solution for: How to call one script to another script in monkey talk automation tool for iOS


Thanks, Arihant


Mocha/Chai Test linkTo Function Returning AssertionError

I'm trying to find & correct the Javascript code in challenge.js so that it passes the Mocha & Chai tests as specified in spec.js.... Nothing I try will get it to pass the tests when I run the command $ mocha spec.js in the Terminal.... To provide more information, the resulting error message that is continually returned in the Terminal regardless of any changes I make to challenge.js is shown underneath.


Challenge.js



module.exports.linkTo = function(text, address) {
return "<a href='" + text + "'>" + address + "</a>"
};


Spec.js



var expect = require("chai").expect;
var challenge = require("./challenge.js");

describe("linkTo", function() {
it("should be defined", function() {
expect(challenge.linkTo).to.exist;
});

it("should return a valid link for Bloc", function() {
expect(challenge.linkTo("Bloc", "http://www.bloc.io")).to.eql("<a href='http://www.bloc.io'>Bloc</a>");
});
});


Error Message as returned in Terminal



linkTo
✓ should be defined
1) should return a valid link for Bloc


1 passing (11ms)
1 failing

1) linkTo should return a valid link for Bloc:

AssertionError: expected '<a href=\'Bloc\'>http://ift.tt/1bILdnv;' to deeply equal '<a href=\'http://www.bloc.io\'>Bloc</a>'
+ expected - actual

+<a href='http://www.bloc.io'>Bloc</a>
-<a href='Bloc'>http://ift.tt/1bILdnv;

at Context.<anonymous> (/home/vagrant/frontend-javascript-exercises/02-reading-mocha-tests/00-a-tested-function/spec.js:10:63)
at callFn (/usr/local/lib/node_modules/mocha/lib/runnable.js:266:21)
at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:259:7)
at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:387:10)
at /usr/local/lib/node_modules/mocha/lib/runner.js:470:12
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:312:14)
at /usr/local/lib/node_modules/mocha/lib/runner.js:322:7
at next (/usr/local/lib/node_modules/mocha/lib/runner.js:257:23)
at Object._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:289:5)
at processImmediate [as _immediateCallback] (timers.js:336:15)


Can anyone PLEASE point out the correction(s) needed in challenge.js in order for the tests to pass when I run $ mocha spec.js in the Terminal???


Thanks in advance Lex


How to write a Test for c# Delegate to a StoredProc?

How to write tests for delegate methods? or Beware of 2 open connections both with 'hooks' onto the same SQL table .... .


This was not straight forward to diagnose, test and prove is not a problem with my current solution.


How could I have TDD'd or written unit/integration tests to have trapped this? Redesign suggestions ...



  1. Create a connection to the table 'TransferWebTransmit' to process all rows.

  2. Execute a Reader to loop through 'old' records, (ID=1)

  3. Call a delegate method to process the 'old' record. (NB keep current connection open until all rows are processed i.e. have called the delegate).


Delegate method:



  1. Opens a new connection, executes a Stored Proc 'TransferWebTransmitUpdate'

  2. which -> Updates the table 'TransferWebTransmit' row (ID=1), then does a SELECT on (ID=1) row ----> cursor lock! ----> .Net throws "System.Data.SqlClient.SqlException (0x801 31904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding". ----> Connections are locked. ----> Have to Kill processes to recover


Here's the delegate method:



public int Update(int transferID)
{
var obj = new TransferWebMessage();

using (SqlConnection conn = base.GetNewConnection())
{
using (SqlCommand sp_cmd = new SqlCommand())
{
sp_cmd.CommandText = "TransferWebTransmitUpdate";

sp_cmd.CommandType = CommandType.StoredProcedure;
sp_cmd.Parameters.AddWithValue("TransferID", transferID);

sp_cmd.Connection = conn;
conn.Open();
SqlDataReader rdr = sp_cmd.ExecuteReader();
int roweffected;
while (rdr.Read())
{
roweffected = rdr.GetInt32(0),
}
}
}
return roweffected;
}


Here's the call to get the rows to process and call the delegate:



public void WatchForDataTransferRequests(_delegateMethod callback)
{
using (SqlConnection conn = new SqlConnection(_insol_SubscriberConnectionString))
{
// Construct the command to get any new ProductReview rows from the database along with the corresponding product name
// from the Product table.
SqlCommand cmd = new SqlCommand(
"SELECT [TransferID]" +
" FROM [dbo].[TransferWebTransmit]" +
" ORDER BY [TransferID] ASC", conn);

cmd.Parameters.Add("@CurrentTransferID", SqlDbType.Int);
conn.Open();

SqlDataReader rdr = cmd.ExecuteReader();

// Process the rows
while (rdr.Read())
{
Int32 transferID = (Int32)rdr.GetInt32(0);
callback(transferID);
}
}
}

why is @Parameterized.Parameters called twice?

I have this code:



@RunWith(ParallelParameterized.class)
public class RoutingResponseShortRegressionOneByOne {

...

@BeforeClass
public static void oneTimeSetUp() {
routingUrlHttpClientWithReRun = injector.getInstance(IRoutingUrlHttpClientWithReRun.class);
System.out.println("in RoutingResponseRegressionOneByOne:: oneTimeSetUp");
}

@AfterClass
public static void oneTearDown() {
// if (globalSettings.isSaveNewResponses) {
assertE2eCheckers();
stateSaver.save(e2EResultShort);
//}
}

//takes the next matrix row from OrganizeTestParameterizedInput()
public RoutingResponseShortRegressionOneByOne(String routingRequest, CompleteRoutingResponseShort
routingResponse) {
initNonStaticFromInjector();
this.routingRequest = routingRequest;
this.routingResponse = routingResponse;
}


//This is called before @BeforeClass !
@Parameterized.Parameters
public static Collection getRequests() throws IOException {
injector = Guice.createInjector(new MainModule());
initStaticFromInjector();
initTestInput();
e2EResultShort = new E2EResultShort();
return OrganizeTestParameterizedInput();
}


And it runs like this:



@Parameterized.Parameters

@Parameterized.Parameters

@BeforeClass

public RoutingResponseShortRegressionOneByOne --> ctor

@Test


why is @Parameterized.Parameters called twice in a row?


In addition, how can I know @RunWith(ParallelParameterized.class) really works? meaning how can I check if the run is in parallel?


libraries for end to end testing or api testing in clojure?

hey guys i am planning to add test suit for my web-project and some mobile api. I finalise Midje and clojure.test to test each line of code basically for (Unit Testing),


but i am not able to figure out test libraries to test end-to-end api.


what about clj-webdriver or any other better option..?


thanks and appreciation for any help.


Unable to create an Android project with specific name in eclipse

I am trying to implement Facebook Login integration in my android app. However before I could do that, I was trying to test the code. So I created a new Android project in Eclipse by the name " FaceBookTesting "



  1. Min SDK : Android 2.2

  2. Target SDK : Android 4.4

  3. Complie With : Android 4.4


As soon I create this project, Eclipse gives me a cyclone of errors :



[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:202: error: Error retrieving parent for item: No resource found that matches the given name 'android:ThemeOverlay.Material'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:212: error: Error retrieving parent for item: No resource found that matches the given name 'android:ThemeOverlay.Material.Light'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:205: error: Error retrieving parent for item: No resource found that matches the given name 'android:ThemeOverlay.Material.Dark'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:219: error: Error retrieving parent for item: No resource found that matches the given name 'android:ThemeOverlay.Material.ActionBar'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:223: error: Error retrieving parent for item: No resource found that matches the given name 'android:ThemeOverlay.Material.Dark.ActionBar'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:81: error: Error: No resource found that matches the given name: attr 'android:colorAccent'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:83: error: Error: No resource found that matches the given name: attr 'android:colorControlActivated'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:84: error: Error: No resource found that matches the given name: attr 'android:colorControlHighlight'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:82: error: Error: No resource found that matches the given name: attr 'android:colorControlNormal'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:79: error: Error: No resource found that matches the given name: attr 'android:colorPrimary'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:80: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:118: error: Error: No resource found that matches the given name: attr 'android:colorAccent'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:120: error: Error: No resource found that matches the given name: attr 'android:colorControlActivated'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:121: error: Error: No resource found that matches the given name: attr 'android:colorControlHighlight'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:119: error: Error: No resource found that matches the given name: attr 'android:colorControlNormal'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:116: error: Error: No resource found that matches the given name: attr 'android:colorPrimary'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:117: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:155: error: Error: No resource found that matches the given name: attr 'android:colorAccent'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:157: error: Error: No resource found that matches the given name: attr 'android:colorControlActivated'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:158: error: Error: No resource found that matches the given name: attr 'android:colorControlHighlight'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:156: error: Error: No resource found that matches the given name: attr 'android:colorControlNormal'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:153: error: Error: No resource found that matches the given name: attr 'android:colorPrimary'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:154: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:192: error: Error: No resource found that matches the given name: attr 'android:colorAccent'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:194: error: Error: No resource found that matches the given name: attr 'android:colorControlActivated'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:195: error: Error: No resource found that matches the given name: attr 'android:colorControlHighlight'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:193: error: Error: No resource found that matches the given name: attr 'android:colorControlNormal'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:190: error: Error: No resource found that matches the given name: attr 'android:colorPrimary'.
[2015-03-30 12:17:36 - FaceBookTesting]
[2015-03-30 12:17:36 - FaceBookTesting] D:\workspace\appcompat_v7\res\values-v21\themes_base.xml:191: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.
[2015-03-30 12:17:36 - FaceBookTesting]


When I go under the MainActivity the R is underlined with red !



setContentView(R.layout.activity_main);


I don't have any idea why is it giving me this ! I even tried cleaning my project, building my workspace again, closing and re-opening eclipse but without luck !


The funniest part, it has happened with this project name only. Have been working on other Android projects. i never faced this issue ! Anyone ny ideas ?


dimanche 29 mars 2015

what bundle do i pass to getInstrumentation().callActivityOnCreate(Activity, bundle);

i am trying to test my mainActivity of the android app and i cant figure out what to pass to callActivityOnCreate method right now i have tried



getInstrumentation().callActivityOnCreate(getActivity, null);


but it gives me a nullpoint exception,probably i am sending null


Android Studio Gradle 1.1 and Roboeletric

i'm having a hard time to make AS with gradle 1.1 work with Roboeletric. I've readed a few tutorials e try some things but none seen to work.


This is my Project build.gradle file:



buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}


The robo eletric got download and all and here is my module build.gradle:



android {
compileSdkVersion 21
buildToolsVersion "21.1.2"

defaultConfig {
applicationId "br.com.boozeprice"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

apply plugin: 'org.robolectric'

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:21.0.3'

compile project(':androidcore')
compile project(':persistencecore')

testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:2.4'
}


The gradle compiles and all but it seens that i don't have the library in project, i can't import the roboeletric classes neither their annotations.


Am i missing something?


Thank you in advance.


How to test an ES7 async function using mocha/chai/chai-as-promised

I have the following function to test:



// ...
const local = new WeakMap();

export default class User {

// ...

async password(password) {
if (!password) return local.get(this).get('hash'); // remove this for security reasons!
if (password.length < 6) throw new Error('New password must be at least 6 characters long');
if (!password.match(passwordPattern)) throw new Error(`New password must match ${passwordPattern}`);
local.get(this).set('hash', await Password.hash(password));
}

// ...

}


Now I want to test this function with mocha, chai and chai-as-promised doing this test-case:



import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';

import User from '../../../server/User';

chai.use(chaiAsPromised);
const expect = chai.expect;

describe('.password()', () => {

const testuser = new User({username: 'Testuser', password: '123abc'});

// FINDME
it(`should throw when too short`, () => {
return expect(testuser.password('1a')).to.eventually.throw();
});

// ...

});


Look for the // FINDME comment in the above code to get the context I'm referring to.


So what happens is that the test(s) do not wait for the async password() function to finish. As I found out ECMAScript7 async functions immediatelly return a thenable, so it should be fine since chai-as-promised use exactly this feature. My guess is, that async functions don't throw errors into this said promise rather than throwing it into the enclosing function itself, not being able to capture it through expect().


For the eager folks: I transpile this code on-the-fly with babel using the following command:


babel-node --experimental node_modules/mocha/bin/_mocha --watch --recursive -R spec --check-leaks


Any thoughts?


how to unit test view returned b onCreateView method of fragment class?

I am trying to unit test an android fragment class. I want to know how can I unit test the View returned by onCreateView method of a fragment class. Please share any examples.


Protractor basic fundamental questions - low on the learning curve

After working with Eclipse/JUnit/webdriver for few months, and now, trying to come up to speed with Protractor, I am forced to fall back and submit some basic questions for you java/js experts.




  1. Why in Protractor, do I have to invoke direct reference of "browser.driver." when testing Non-Angular web pages versus in Eclipse/Junit/weddriver I just instantiate the webdriver object?




  2. In Protractor, when referencing the "browser.driver" directly, do I always have to use the element finder method "browser.driver.findElement"(by." or is the method overloaded such that "browser.driver.element(By." will also work?




RSPEC test NAME ERROR - Undefined Local variable or method

I'm a beginner in ruby on rails and programming in general. I have an assignment where I have to test my rspec model Vote, and as per instructions the test should pass.


When I run rspec spec/models/vote_spec.rb on the console, I receive the following error:



.F

Failures:

1) Vote after_save calls `Post#update_rank` after save
Failure/Error: post = associated_post
NameError:
undefined local variable or method `associated_post' for #<RSpec::ExampleGroups::Vote::AfterSave:0x007f9416c791e0>
# ./spec/models/vote_spec.rb:22:in `block (3 levels) in <top (required)>'

Finished in 0.28533 seconds (files took 2.55 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/models/vote_spec.rb:21 # Vote after_save calls `Post#update_rank` after save


Here is my vote_spec code:



require 'rails_helper'
describe Vote do
describe "validations" do
describe "value validation" do
it "only allows -1 or 1 as values" do

up_vote = Vote.new(value: 1)
expect(up_vote.valid?).to eq(true)

down_vote = Vote.new(value: -1)
expect(down_vote.valid?).to eq(true)

invalid_vote = Vote.new(value: 2)
expect(invalid_vote.valid?).to eq(false)

end
end
end

describe 'after_save' do
it "calls `Post#update_rank` after save" do
post = associated_post
vote = Vote.new(value: 1, post: post)
expect(post).to receive(:update_rank)
vote.save
end
end
end


And here is my post_spec code:



require 'rails_helper'

describe Post do
describe "vote method" do


before do
user = User.create
topic = Topic.create
@post = associated_post
3.times { @post.votes.create(value: 1) }
2.times { @post.votes.create(value: -1) }
end

describe '#up_votes' do
it "counts the number of votes with value = 1" do
expect( @post.up_votes ).to eq(3)
end
end

describe '#down_votes' do
it "counts the number of votes with value = -1" do
expect( @post.down_votes ).to eq(2)
end
end

describe '#points' do
it "returns the sum of all down and up votes" do
expect( @post.points).to eq(1) # 3 - 2
end
end
end

describe '#create_vote' do
it "generates an up-vote when explicitly called" do
post = associated_post
expect(post.up_votes ).to eq(0)
post.create_vote
expect( post.up_votes).to eq(1)
end
end

end

def associated_post(options = {})
post_options = {
title: 'Post title',
body: 'Post bodies must be pretty long.',
topic: Topic.create(name: 'Topic name',description: 'the description of a topic must be long'),
user: authenticated_user
}.merge(options)

Post.create(post_options)
end

def authenticated_user(options = {})
user_options = { email: "email#{rand}@fake.com", password: 'password'}.merge(options)
user = User.new( user_options)
user.skip_confirmation!
user.save
user
end


I'm not sure if providing the Post and Vote models code is necessary. Here is my Post model:



class Post < ActiveRecord::Base
has_many :votes, dependent: :destroy
has_many :comments, dependent: :destroy
belongs_to :user
belongs_to :topic

default_scope { order('rank DESC')}


validates :title, length: { minimum: 5 }, presence: true
validates :body, length: { minimum: 20 }, presence: true
validates :user, presence: true
validates :topic, presence: true



def up_votes
votes.where(value: 1).count
end

def down_votes
votes.where(value: -1).count
end


def points
votes.sum(:value)
end

def update_rank
age_in_days = ( created_at - Time.new(1970,1,1)) / (60 * 60 * 24)
new_rank = points + age_in_days

update_attribute(:rank, new_rank)
end



def create_vote
user.votes.create(value: 1, post: self)
# user.votes.create(value: 1, post: self)
# self.user.votes.create(value: 1, post: self)
# votes.create(value: 1, user: user)
# self.votes.create(value: 1, user: user)

# vote = Vote.create(value: 1, user: user, post: self)
# self.votes << vote
# save
end

end


and the Vote model:



class Vote < ActiveRecord::Base
belongs_to :post
belongs_to :user

validates :value, inclusion: { in: [-1, 1], message: "%{value} is not a valid vote."}

after_save :update_post



def update_post
post.update_rank
end

end


It seems like in the spec vote model, the method assosicated_post can't be retrieved from the post spec model?


CasperJS - How to Skip to next test suite?

Quoting this example - http://ift.tt/1NrO8yD


While executing the first test suite in this example, How do I skip to the test suite "Casperjs.org is first ranked"?


I have tried out http://ift.tt/1Ekg5qG and the given documentation doesnt give me ideas on how to achieve the above.


Retrieve object type in string form in robot-framework


a = {}
b = str(type(a))


How can one migrate the python code to robot framework. I tried this,



${type_obj}= Evaluate type(${a})
${type_str}= Evaluate str(${type_obj})


But it just broke with a syntax error as,



Evaluating expression 'str(<type 'dict'>)' failed: SyntaxError: invalid syntax (<string>, line 1)

samedi 28 mars 2015

Can gradle execute multiple TestNG suite xml files in parallel (forked jvm)?

I am using suiteXmlFiles within useTestNG() {...} to specify all TestNG test suites that should run and I want to execute them in parallel, is this possible?


Retaining items created during setup of a python test

I'm writing a test suite for a custom manager in Django, and want to test a large number of items.


Essentially, it requires creating several thousand items, due to a combinatorial explosion.


What I need is a way to create a lot of django objects in the database and have them retained through the whole test class instead of recreating them.


I have the following code:



class CustomConceptQuerySetTest(TestCase):
def setUp(self):
pass #make lots and lots of items.

def test_is_public(self):
pass # check if returned items in the object.public() queryset are actually "public"
def test_is_editable(self):
pass # check if returned items in the object.viewable() queryset are actually "viewable" only to certain users.


Unfortunately, setUp is called before each test, but the content is not changed during tests, only read, and is the same each time.


Is there a way in Django to keep the database, or prevent rollbacks or destruction within a test Class?


symfony : how to use the crawler to test the response of each page

I am starting to get interested in unit tests and I understood we do almost what we wanted.


How can I test a page's response (make sure it returns a 200 code) ? I get lost in all the many options. Does someone have a simple example ?


I know how to generate a list of all my pages, now I want to test each of them and make sure the response is not a 500.


Testing private functions using eval

I'm writing a node module and I want to be able to unit test all my functions, however I have not exposed many of them (shown below).



module.exports = function() {
var privateFunction = function() {
// Do Stuff Here
};
return {
publicFunction: function() {
// do stuff
privateFunction();
}
}
}


I read on another stack question that eval could be used if my private functions were moved to the global scope, that way my functions would be interpreted and could be tested. Despite eval being generally considered bad practice, I can't really see another method of testing these functions.


Does anyone know of a better method to test these.


Test website performance

I have a PHP and MySQL website using the XAMPP server.


I was just wondering is there any software, online websites etc that can test (network performance, load balance, stress tests etc) for websites that are running on a localhost (local environment)?


Thanks for any help


Google Test develop several Test Suites

I would like to develop several test suites with Google Test framework.


All these test suites should share same test fixture.


I would like to have une .cpp file per test suite. One of the cpp file, contains the fixture and the test suite number 1.


Could you hint at the right architecture to do so?


Wait Fails on Selendroid tests

I'm working on a set of tests using Selendroid with python, the question is: Is there a wait to made selendroid wait for some elements or condition to continue executing the test?. Here is an example i'm talking about



def test_google_login(self):
self.driver.get('and-activity://com.package.name.MainActivity')
self.driver.get('and-activity://admin.ConfigActivity')
#self.driver.implicitly_wait(10)
ivAppIcon = self.driver.find_element_by_id('ivAppIcon')
try:
lv = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "lvProviders")))
except Exception:
self.driver.quit()


On this example i'm trying to give some time to animation to finish and then look for the list view, But for some estrange reason the test fails or made app to fail.


Thanks


How to integrate nock-vcr-recorder-mocha with Meteor?

I need to mock HTTP calls when testing my Meteor app using http://ift.tt/1ELI7Gv


I found http://ift.tt/1OIUX09 but including it in my app using http://ift.tt/13IeydK and with the following test code gives me an error...



vcr = Meteor.npmRequire('nock-vcr-recorder-mocha')
log "VCR!",vcr

describe "Interpret data", ->
vcr.it "should work", ->
chai.expect(->
# http call
).not.to.throw()


W20150327-17:25:33.820(1)? (STDERR) TypeError: Cannot read property 'test' of undefined W20150327-17:25:33.821(1)? (STDERR) at getCassetteName (/Users/fredrikbranstrom/Sites/kaus/.meteor/local/isopacks/npm-container/npm/node_modules/nock-vcr-recorder-mocha/lib/it.js:30:24) W20150327-17:25:33.821(1)? (STDERR) at /Users/fredrikbranstrom/Sites/kaus/.meteor/local/isopacks/npm-container/npm/node_modules/n


gradle test raise error: java.lang.NoClassDefFoundError: Could not initialize class groovy.lang.GroovySystem

I try to run "gradle test", and get error


My test is



class HelperTest extends ro.gd.Test {
Plugin o;

void setUp() {
o = new Plugin();
}

void testGetIdeaDeps() {
def r = o.ideaDeps
asrHaveVal r
}
}


when i run gradle test, it raise:



junit.framework.AssertionFailedError: Exception in constructor: testGetIdeaDeps (java.lang.NoClassDefFoundError: Could not initialize class groovy.lang.GroovySystem
at org.codehaus.groovy.reflection.ClassInfo.isValidWeakMetaClass(ClassInfo.java:221)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassForClass(ClassInfo.java:191)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:236)
at ro.gd.idea.HelperTest.$getStaticMetaClass(HelperTest.groovy)
at ro.Test.<init>(Test.groovy)
at ro.gd.Test.<init>(Test.groovy)
at ro.gd.idea.HelperTest.<init>(HelperTest.groovy)
...


Here is my full code


Structure of Node.js app for convinient testing

I'm developing a Node.js service/app, but I am kind of stuck how to structure it to be suitable for easy testing with mocha and sinon. I have a couple of endpoints and everyone of them is structured in the following way:



controllers:
controllerA:
index.js
validate.js
process.js
doSomething1.js
doSomething2.js
controllerB:
index.js
validate.js
process.js
doOther1.js
doOther2.js
...
utils:
someUtil.js
otherUtil.js


Every file exports a function that is used by other function(ex. process.js exposes a function process(req, res) {...} than internally calls doOther1() {...}. On the other hand function doOther1() {...} calls function doOther2() {...} which uses someUtil).


Unfortunately when it comes to testing it's hard to isolate parts of the service. For example I want to test doOther1 isolating someUtil, but it seems impossible to stub someUtil with sinon, because require('utils/someUtil') returns a function.


What is a more test-friendly way to layout my app? While I was writing it seemed ok to have small separate functions to deal with specific things, but it's hard to write nice tests on every single function. Happy to link me to articles on the subject.


vendredi 27 mars 2015

golang example won't run

I'm trying to add an example to a package, and run the example via go test, however the example is never run.


For example, see this gist: http://ift.tt/1EKIy3K


The gist has example_test.go:



package cow_test

import (
cow "http://ift.tt/1EKIy3M"
)

func Example() {
cow.Poke()
}


Yet when I run this:



# go test -v example_test.go
testing: warning: no tests to run
PASS
ok command-line-arguments 0.002s


However other packages from stdlib work just fine:



# cd /usr/lib/go/src/errors
# go test -v example_test.go
=== RUN: Example
--- PASS: Example (0.00s)
PASS
ok command-line-arguments 0.002s


What is wrong with my example?


Needing VB to read from a txt file or any other file and do a specific action

So I am building a blocker program for my own family's personal use.


So lets say I have a txt file listing these websites: http://ift.tt/1Bv16TA www.fake.net


I want it to find the txt file that has that information, then pull it and use it and since my program is a web browser I want it to block those websites I defined.


I ONLY WANT IT TO BLOCK THE WEBSITE IN MY APPLICATION NOT OVER THE WHOLE COMPUTER (meaning I don't want it to be blocked in Chrome, Firefox, Internet Explorer, Safari, ECT.)


Can't mock return from ember-data destroyRecord for testing

I'm trying to test deleting a user account using fauxjax and ember-data. I am getting this error back: Assertion Failed: Expected an object as 'data' in a call to 'push' @model:user: , but was undefined


I can't find what to do in this case with testing. Here is my test and code:


Test:



test('delete user account', function(assert) {
loginUser();
$.fauxjax.new({
request: {
type: 'GET',
url: ENV.apiDomain.concat('/users/1'),
dataType: 'json',
headers: {Authorization: 'abc123'}
},
response: {
content: {}
}
});

visit('/account/delete');

click('#yes');
andThen(function() {
assert.equal(currentPath(), 'index');
});
});


and my action:



confirmDelete: function() {
var controller = this;
this.store.find('user', localStorage.userId).then(function(user){
user.destroyRecord();
controller.send('logout');
});
},

I enter an invalid result for a while loop it works, but after a few times the while loop keeps repeating in time_taken()


client_dict = {"NeQua":"High","EmVol":"Moderate","RiVam":"High","EdLis":"Moderate"}
Intensity_sports = {"High":["swimming","aerobics"],"Moderate":["Basketball","Hiking"]}
def activity_recorder():
def clientID_choice():
global clientid,intensity
clientid = input("What client would you like to edit?:")
while clientid not in client_dict:
clientid = input("\nPlease enter the correct client\nWhat client would you like to edit?:")
intensity = client_dict[clientid]
print("\n"+clientid,"has a",intensity,"intensity\nThe reccomened sports are:")
for sports in Intensity_sports[intensity]:
print("//",sports)

**def time_taken():
global time_spent
time = [] #The variable time is equal to an empty array
for sport in Intensity_sports[intensity]:
try:
time_spent = int(input("\nPlease select the minutes spent on "+sport+":"))
while not 0 <= time_spent <= 120:
time_spent = int(input("\nPlease select the minutes spent on "+sport+" between 0 and 120:"))
except:
print("Please enter a number\nYou will be asked to re enter all your times")
time_taken()
time.append(time_spent)
total_time = 0
for time_spent in time:
total_time += time_spent
print("\n"+clientid+"'s total time spent is",total_time,"minutes")**

def again():
anotherRecord = input("\nDo you wis to enter another record? Type yes or y or no or n:")
while anotherRecord.lower() != "yes" and anotherRecord.lower() != "y" and anotherRecord.lower() != "no" and anotherRecord.lower() != "n":
anotherRecord = input("Please answer again. Yes or No?")
if anotherRecord.lower() == "yes" or anotherRecord.lower() == "y":
print("You will now enter a new client record")
activity_recorder()
else:
print("Thank you")
clientID_choice()
time_taken()
again()
activity_recorder()


Can you test it to check for any errors and help me


How can generic programs in C++11 be properly tested

I usually use Boost.Test for writing unit tests for my code. My tests cover not only the positive path, but also I write tests to be certain exceptions will be thrown when needed.


Since C++11 introduced Concepts and noexcept I had been developing more advanced generic program expressions to detect errors at compile time when possible.


How can I test my generic programming functions are catching the right problems? So far, I'm using a SH script running a set of programs that are expected to fail compilation and collecting the results in a file.


Is there any better approach? Is any Testing tool including support for testing code wrote to fail compilation?


how to turn non-parallel junit parameterized tests into parallel run

I write a parameterized junit test.


Is there any built-in way to make it run in parallel? any @annoation for example?


If not, and my only way is to write this manually -


how would you manage a thread pool in junit, java?


Speclj not working with lighttable?

Today I had a look on speclj and added it to my project.clj according to the documentation. After I finished my first spec, I hit crtl+enter after (run-specs) and got following exception:



Failed trying to require overseer.parse-spec with:
java.lang.ClassNotFoundException: speclj.platform.SpecFailure
URLClassLoader.java:372 java.net.URLClassLoader$1.run
URLClassLoader.java:361 java.net.URLClassLoader$1.run
(Unknown Source) java.security.AccessController.doPrivileged
URLClassLoader.java:360 java.net.URLClassLoader.findClass
DynamicClassLoader.java:61 clojure.lang.DynamicClassLoader.findClass
ClassLoader.java:424 java.lang.ClassLoader.loadClass
ClassLoader.java:357 java.lang.ClassLoader.loadClass
(Unknown Source) java.lang.Class.forName0
Class.java:340 java.lang.Class.forName
RT.java:2065 clojure.lang.RT.classForName
Compiler.java:978 clojure.lang.Compiler$HostExpr.maybeClass
Compiler.java:756 clojure.lang.Compiler$HostExpr.access$400
Compiler.java:2540 clojure.lang.Compiler$NewExpr$Parser.parse


Afterwards I used leiningen on the command line and with lein test it's working smoothly. Is there anything I have to take care of when I use speclj with lighttable?


Smooth shutdown for activeMQ after running integrat

I am using ActiveMQ to run my integration tests using mvn build. My pom.xml triggers activemq first and then triggers the integration tests so that they can use the above activeMQ instance to transfer messages.


Its working correctly but does not shut down smoothly.. When the mvn build is over and all tests are successful, the build looks good. But activemq spits out the following error while shutting down :-



'[INFO] Apache ActiveMQ 5.7.0 (localhost, ID:LB3290FPF-54398-1427490319466-0:1) is shutting down
Exception in thread "ActiveMQ ShutdownHook" java.lang.NoClassDefFoundError: org/apache/activemq/transport/vm/VMTransportFactory
at org.apache.activemq.broker.BrokerService.stop(BrokerService.java:750)
at org.apache.activemq.xbean.XBeanBrokerService.stop(XBeanBrokerService.java:91)
at org.apache.activemq.broker.BrokerService.containerShutdown(BrokerService.java:2303)
at org.apache.activemq.broker.BrokerService$6.run(BrokerService.java:2270)
Caused by: java.lang.ClassNotFoundException: org.apache.activemq.transport.vm.VMTransportFactory
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:259)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:235)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:227)
... 4 more
[INFO] Connector tcp://localhost:61616?useJmx=true&persistent=false Stopped'


Is there a way I enable Maven to shut activeMQ smoothly without above Exceptions when the maven build finishes? Here are some associated details :-



  1. activeMQ uri : tcp://localhost:61616?useJmx=false&persistent=false

  2. fork : true

  3. activeMQ-core : 5.7.0

  4. maven-activemq-plugin : 5.7.0


Running Rspec fails if variables can be passed to a class in Puppet

Problem


If variables can be passed to a Puppet class, e.g.:



class module_name (
$variable='hello_world'
) {
package { 'package_name': }
}


and rspec is run it fails, i.e.:



[user@host module_name]$ rspec
...............................FFFFFFFFFFFF..........................................

Failures:

1) opsview should contain Class[module_name]
Failure/Error: it { should contain_class('module_name') }
Puppet::Error:
Error from DataBinding 'hiera' while looking up 'module_name::variable':
FileSystem implementation expected Pathname, got: 'Hash' on node host
# /usr/share/ruby/vendor_ruby/puppet/resource.rb:393:
in `rescue in lookup_with_databinding'
# /usr/share/ruby/vendor_ruby/puppet/resource.rb:387:
in `lookup_with_databinding'
# /usr/share/ruby/vendor_ruby/puppet/resource.rb:381:
in `lookup_external_default_for'


Main issue



Error from DataBinding while looking up FileSystem implementation expected Pathname,
got: 'Hash' on node


Configuration


Versions



[vagrant@vm-one opsview]$ puppet --version
3.7.5
[vagrant@vm-one opsview]$ rspec --version
3.2.2


Spec_helper



[vagrant@vm-one opsview]$ cat spec/spec_helper.rb
require 'rspec-puppet'
require 'hiera-puppet-helper'

fixture_path = File.expand_path(File.join(__FILE__, '..', 'fixtures'))

RSpec.configure do |c|
c.module_path = File.join(fixture_path, 'modules')
c.manifest_dir = File.join(fixture_path, 'manifests')
c.hiera_config = '/etc/puppet/hiera.yaml'
end

at_exit { RSpec::Puppet::Coverage.report! }


Attempt



  1. According to this Q&A hiera-puppet-helper is causing the issue. Rspec-puppet seems to support testing of hiera and 'hiera-puppet-helper' could be replaced. Ok perhaps this solves the issue, but what is causing the issue?

  2. This post contains the same issue, but not a solution to solve the issue

  3. This post indicates that removing the class parameters solves the issue, but this class is used by multiple modules and therefore this is not a solution.