vendredi 26 mai 2017

Is there away to start/stop a mock service via groovy script as one of the groovy test steps?

I'd like to be able to start mock service in SOAPUI on test case setup script and close it through tear down script. I figured out how to start the service in setup script:

def project = null
def projectName = "myproject"
def workspace = testRunner.testCase.testSuite.project.getWorkspace();

//if running Soapui
if(workspace != null){
    project = workspace.getProjectByName(projectName)
}
else {
    log.error("Can't find workspace")
}
if (project != null) {
    log.info("Project " + projectName + " located!")    
    project.getMockServiceByName("myMockService").start(); 
     log.info("Project myMockService started!")
} else {
    log.error("Can't find " + projectName + " project, please start mock service manually") 
}

But having difficulties obtaining a reference to already running mock service in order to stop it. Any suggestion what should I script in tear down script to stop the service? enter image description here

Python mocking logging while retaining log output

I have a series of unit/integration tests which using the python logging module. I would like to test that the right things are logged when appropriate which I can achieve using the mock module as follows:

@mock.patch('logging.Logger.info')

However, when I do this the actual logging is stopped (for obvious reasons!) and this is useful for me to debug why my tests are working etc.

My question is as follows: Is there a way in why I can mock out logging calls so I can assert they have been called with the expected arguments but still keep the logging functionality?

Cheers, Jack

Grunt Karma PhantomJS - SyntaxError: Unexpected token '<'?

I keep getting an error when running this in my terminal (at the location of gruntfile.js):

grunt karma

The solutions here either didn't work or are no longer an option - http://ift.tt/2rYnrgz

Here is the output:

Running "karma:unit" (karma) task
26 05 2017 13:43:15.838:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:8082/
26 05 2017 13:43:15.840:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
26 05 2017 13:43:15.848:INFO [launcher]: Starting browser PhantomJS
26 05 2017 13:43:15.955:ERROR [phantomjs.launcher]: Fontconfig warning: ignoring C.UTF-8: not a valid language tag

26 05 2017 13:43:16.130:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 9TxdacwF4rc7mUB0AAAA with id 76282796

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
SyntaxError: Unexpected token '>'
at app/client/app.js:2


PhantomJS 2.1.1 (Linux 0.0.0) ERROR
SyntaxError: Unexpected token '>'
at app/client/paths/home/homeCtrl.js:2

Here is my code:

karma.config.js

module.exports = function(config) {
    config.set({

    frameworks: ['jasmine'],


    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'app/**/*.js',
    ],

    port: 8082

    browsers: ['PhantomJS'],

    plugins: [
       'karma-phantomjs-launcher',
       'karma-jasmine',
       'karma-ng-html2js-preprocessor'
    ],

    logLevel: config.LOG_INFO,
})};

grunt test block for karma in gruntfile.js

karma: {
    unit: {
        configFile: 'karma.config.js',
        singleRun: true,
    }
}

homeCtrl.spec.js

describe('HomeCtrl', function() {
    beforeEach(module('myApp'));

    var HomeCtrl;
    beforeEach(inject(function($controller){ 
        HomeCtrl = $controller('HomeCtrl');
    }));

    describe('message', function() {
        it('should read hello', function() {
            expect(HomeCtrl.message).toBe('Hello');
        });
    });

});

homeCtrl.js

angular.module('RevisionApp')
    .controller('HomeCtrl', ($scope) => {
        $scope.message = 'hello';    
    })

Here is the folder structure: http://ift.tt/2roRsJ3

Any input would be much appreciated, thanks.

Automating github login through Selenium Webdriver

Hi guys I am trying to automate the github login process through selenium web driver in java , everything is fine and okay except for the very first time when the user does not exist github asks the user to allow the access as shown in the picture

enter image description here

I am trying to find out that if the title of the window is authorize application than run a specific flow and if not run the usual flow but its not finding out the title and the test fails on the authorization screen and if I try to find the authorize green button it says the element is not enabled

The code is below for help

package com.silexica.selenium.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class GitHubLoginTest {

    @Test
    public void githubLogin() {

        // Set our gecko driver
        System.setProperty("webdriver.gecko.driver", "geckodriver");

        // setting up the firefox driver
        WebDriver driver = new FirefoxDriver();

        // Open website
        driver.get("");

        // wait for the google icon button to load
        WebDriverWait githubbuttonwait = new WebDriverWait(driver, 10);
        WebElement githubloginbutton = githubbuttonwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div/div/div/div/div/form/ul/li/a[2]/img[2]")));

        // click the button if present
        githubloginbutton.click();

        // Find the email form field
        WebDriverWait githubemailfieldwait = new WebDriverWait(driver, 10);
        WebElement githubemailfield = githubemailfieldwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[1]")));

        // Type the random email to the form
        githubemailfield.sendKeys("");

        // Find the password form field
        WebDriverWait githubpasswordfieldwait = new WebDriverWait(driver, 10);
        WebElement githubpasswordfield = githubpasswordfieldwait.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[2]")));

        // Type password to the form. This needs not be unique.
        githubpasswordfield.sendKeys("");

        // find the sign up button
        WebDriverWait githubpasswordbutton = new WebDriverWait(driver, 10);
        WebElement passwordfieldsignupbutton = githubpasswordbutton.until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[1]/div/form/div[3]/input[3]")));

        // click the sign up button
        passwordfieldsignupbutton.click();

        // verify that the authorization window has the given text
        if ((new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driverObject) {
                return driverObject.getTitle().equals("Authorize application");
            }
        })) {

            // find the allow access button button in google password window
            WebDriverWait githubpasswordbutton2 = new WebDriverWait(driver, 10);
            WebElement passwordfieldsignupbutton2 = githubpasswordbutton2
                    .until(ExpectedConditions.visibilityOfElementLocated(
                            By.xpath("/html/body/div[4]/div[1]/div[2]/div[1]/div[2]/div[1]/form/button")));

            // click the button
            passwordfieldsignupbutton2.click();

            // verify that we have logged into the dashboard
            (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driverObject) {
                    return driverObject.getTitle().equals("Silexica | Dashboard");
                }
            });

            driver.quit();

        } else {

            // Verify that whether we have logged into the dashboard and
            // continue the normal flow
            (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driverObject) {
                    return driverObject.getTitle().equals("Silexica | Dashboard");
                }
            });

            // close the browser
            driver.quit();

        }

    }

}

Any suggestions or improvements

How to test a function call from a different module

There are probably lots of similar questions here but I still don't understand how it's done.

Let's say I have the following trivial module:

defmodule ModuleOne do

  def do_something(argument) do
    argument
    |> do_first_thing()
    |> do_second_thing()
    |> ModuleTwo.do_something()
  end

end

Now, I have ModuleTwo covered with tests so it doesn't make sense to duplicate that testing logic. Also it's not Twitter API module or something of the kind so I dont think it's a good idea to come up with a compile-time mock module ( as far as I can see, it's a good idea in case cases, like HTTP calls but doing that for every external module call will obviously turn into a mess ) and also I don't want to pass a function as an argument just for the sake of testing ( especially if I have calls to multiple external modules ) because it messes up the interface with unnecessary things.

Also people suggest not to use mocks, like the meck library, which is the most obvious decision here, but I don't understand why ...

Anyway, what would be a good way to test this module considering all the suggestions above?

Thank you

Node testing - rewire and fakeredis on object oriented app

So I'm attempting to test an app that uses a redis backend and an OO type framework. Using models in the format below for various objects. I've provided a very cut down version of one of the models below.

class Tld {

/**
 * Creates an instance of Tld
 * @constructor
 * @param {string} tld The tld name
 */
constructor(tld) {
    this.identifier = tld
}


/**
 * Returns a promise that is fulfilled with an array of
 * tlds from redis tlds(zset) key
 *
 * @static
 * @param {Integer} [limit=-1] Number of tlds to return
 * @returns {Promise<Array>}
 *
 * @memberof Tld
 */
static getAll(limit = -1) {
    return new Promise((resolve, reject) => {
        redisClient.zrange("tlds", 0, limit, (err, tlds) => {
            resolve(tlds)
            reject(err)
        })
    })
}
/**
 * Add tld to the list of tlds
 *
 * @static
 * @param {String} tld
 * @returns {Promise<void>}
 *
 * @memberof Tag
 */
static addToList(tld, weight){
    return new Promise((resolve)=>{
         redisClient.zadd(`tlds`, weight, tld, ()=>{
             resolve()
        })
    })
}
}

This app is bootstrapped on load to populate redis with data from various APIs and other things, with a function similar to

Tld=require('../models/tld')
// tlds = loadDummyData()
// // tlds schema retreived from the dummy file
for(tld of tlds){
    tld = new Tld(tld)
    promises.push(Tld.addToList(tld.identifier, weight))
}

return Promise.all(promises)

It's all functional and cool, so I'm currently writing tests for the app, with mocha and chai. With a live redis instance, all is well, however I want to implement CI and I don't want to run redis on my build/test server, so I am looking to replace the redis instance using rewire and fakeredis.

My efforts so far include attempting to rewire the redis client on the bootstrap file and on the model, and bootstrapping (with dummy data) to a fake redis instance.

// Import testing modules
var assert = require('assert');
var chai = require('chai');
var expect = chai.expect;
chai.use(require('chai-ajv-json-schema'))
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);


// rewire redis to mocked  redis
var rewire = require("rewire");
var client = require("fakeredis").createClient();
var bootstrap = rewire('../bin/bootstrap')

var Tld = rewire('../models/tld')

bootstrap.__set__('redis', client)
Tld.__set__('redisClient', client)

bootstrap() // Would move this to a before() function in reality.


describe('Tld', function() {  
  describe('getAll', function() {
    it('should get all TLDs', function() {
        var results = Tld.getAll()

    return(expect(results).to.eventually.be.validWithSchema(
       tld_getall_schema))

    });
  });
})

However, in this case the TLD model is using the fake redis instance (Which is empty of data) but (I assume?) because the bootstrap function is including the Tld Model itself (Which will not be rewired at the point of including?) it's attempting to bootstrap to a live redis instance and is obviously erroring out.

1) Uncaught error outside test suite - Uncaught Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

so i threw a horrific attempt at a hack on:

bootstrap.__set__('redis', client)
Tld.__set__('redisClient', client)
// Inject rewired Tld model back into bootstrap:
bootstrap.__set__('Tld', Tld)
// bootstrap it.
bootstrap()

Which did basically no good at all.

So, How can I either replace the entire redis connection with rewire (without modifying my app code with a redis wrapper for example, because testing should be code-independant) Or, How can I fix what i'm doing here with regards to the bootstrapping to fake-redis.

Thanks for reading, hopefully you clever people can help me with a simple way to test the app :)

Would testing my Java Servlet be neccessary?

I just wanted to ask if it is necessary to test the java servlet that calls another java method (in another file I might add) to do the bulk of the work.

Like for instance, my java servlet currently only is being used to get parameters and displaying the results of the method that was called in html format. So I am only planning on testing my main java file that does all the work!

I am not very familiar with testing so if there would be specific ways to test this simple Java servlet, please let me know!