vendredi 31 août 2018

Best practices for testing a web app based on http calls

I've built a web app that aggregates trading and blockchain data from several API's and displays them in a React frontend(node backend)

What is the best way to implement tests to check for data integrity or when there are issues?

I am extremely new to testing and would appreciate any guidance/direction. Have gone through several testing frameworks and libraries, and am kind of dumbfounded.

Regression testing tool for Voice XML applications?

I'm leading the dev charge at my job to prototype a regression testing tool for our VXML applications. Because manual testing is expensive and error prone. I've heard this idea mentioned at recent conferences/meetups but can't find anything online.

The ask: what OS projects, or vendor tools do you recommend checking out? Any thought leaders in this area worth connecting with?

(more context: I'm a software dev at Revel Health in MN, and some back of the napkin math put our labor expenses for manual VXML testing between $50-100k annually, and as we scale rapidly that number is becoming untenable. We'd also like to open source this tool as we grow it so that it can be forked for different use cases, as conversational interface continues to boom.)

please redirect if this is wrong spot for this question.

confirm and test if data receiving on bad internet from server on android studio

I have an application that relies mostly on communication with the server ... The application contains a book that the customer can buy parts of it and there are several other things (such as small game and coins and in_app_billing). The problem is that in the Internet is not good will happen to communicate with The server. In your opinion what is the solution to this problem, so how can I make sure that the information has arrived and in case you did not arrive to return the ball until the information arrives or for example after 30 seconds of the attempt showed him a message that it is impossible to reach Network.

using:

{Runnable runnable = new Runnable() URL insertUserUrl = new URL(url); HttpURLConnection result; InputStreamReader resultStreamReader = new InputStreamReader(insertConnection.getInputStream()); BufferedReader resultReader = new BufferedReader(resultStreamReader); result = resultReader.readLine();} Please reply and thank you very much

Google Cloud Functions test with mocha - stubbing firebase instance problem

I'm creating my mocha tests using sinon for stubbing just as recommended in official docs.

I have my functions splitted in different files. For this question let's assume I only have one: userSignup. So the file structure would be like this:

functions // root folder
  src
    index.ts // all function exports
    app.ts // Firebase instantiation
    userSignup.ts // Cloud function
  tests
    index.spec.ts // tests file (will be splitted later)

This is the code of the index.spec.ts: https://pastebin.com/qZDgZ8gK

The problem is that, the first test passes correctly and the second doesn't because adminInitStub is using the same commit result from the previous test's firebaseObject, so it's expecting an "ok" again.

I tried by stubbing initializeApp inside a beforeEach and also using afterEach to restore/clear everything. Didn't work.

What am I missing here?

Angular Test Error - not a known element - Only appearing when I run all tests

I have seen lots of questions telling of solutions by simply adding my component to the declaration of my .spec file, but this error only seems to appear when I have run all app tests. Running the component tests only doesn't seem to bring up a problem.

Just FYI - My app and HTML work fine. It just appears that the test hates me.

Chrome 68.0.3440 (Mac OS X 10.13.6) AppComponent should create the app FAILED
    'app-load-spinner' is not a known element:
    1. If 'app-load-spinner' is an Angular component, then verify that it is part of this module.
    2. If 'app-load-spinner' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("/div>
        <button *ngIf="!hidden" class="pa-button" id="loginBtn" type="submit">Log in</button>
        [ERROR ->]<app-load-spinner button *ngIf="hidden"></app-load-spinner>
      </form>
    </div>
    "): ng:///DynamicTestModule/LoginComponent.html@17:4
    Error: Template parse errors:
        at syntaxError node_modules/@angular/compiler/fesm5/compiler.js:1016:1)
        at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse node_modules/@angular/compiler/fesm5/compiler.js:14813:1)
        at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate node_modules/@angular/compiler/fesm5/compiler.js:24000:1)
        at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate node_modules/@angular/compiler/fesm5/compiler.js:23987:1)
        at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:23930:48
        at Set.forEach (<anonymous>)
        at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents node_modules/@angular/compiler/fesm5/compiler.js:23930:1)
        at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:23848:1
        at Object.then node_modules/@angular/compiler/fesm5/compiler.js:1007:33)
        at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndAllComponents node_modules/@angular/compiler/fesm5/compiler.js:23846:1)

login.html

<div class="container">
   ...html code
   <spinner></spinner>
</div>

login.spec.ts

TestBed.configureTestingModule({
      declarations: [LoginComponent, StageComponent, LoadSpinnerComponent],
      imports: [FormsModule, HttpClientTestingModule, RouterTestingModule.withRoutes(fakeRoutes)],
      providers: [{provide: AuthService, useValue: mockAuthService}],
    });

spinner.ts

export class LoadSpinnerComponent implements OnInit {
   // code here
}

What would be the best way to run daily automated tests for a web scraper?

I maintain a REST API built with Django REST that, internally, scrapes several webpages to retrieve a bunch of information.

I have tests for every endpoint that check whether the scrapers are still working. They actually connect with the pages and check that the sources remain unchanged and that everything is still fine basically.

I would like to run these tests several times per day, and be notified when any of these scrapers fail. I'm not sure how should I approach this.

I've been looking at CI tools, but I'm not even sure if that's what I want.

I'm looking for something that allows me to:

1) Run tests automatically every X hours 2) Notify me of the results

What's the best tool for this?

NightwatchJS code generated in Snaptest.io not working in Nightwatch NPM test framework

I used snaptest.io chrome extension to record and automate a simple test to go to google , input a search . The test automates good using Snaptest chrome extension and NightwatchJS code is generated in the code section.

However this NightwatchJS code is not working when i use it as a homepage.js file in Nightwatch NPM framework .

This is the code generated in Snaptest chrome extension .

const TIMEOUT = 10000;
const random = "" + parseInt(Math.random() * 1000000);
const random1 = "" + parseInt(Math.random() * 1000000);
const random2 = "" + parseInt(Math.random() * 1000000);
const random3 = "" + parseInt(Math.random() * 1000000);

module.exports = {
  "Unnamed test": function(browser) {

    bindHelpers(browser);
    bindComponents(browser);

    var baseUrl = browser.launchUrl || `https://www.google.com`;


    browser
      .url(`${baseUrl}/`, 1366, 662, `Load page...`)
      .changeInput(`#lst-ib`, `CSS`, `cypress`, `Change input`)
      .click(`.tsf-p`, `CSS`, `Click element`)
      .click(`[name=btnK]`, `CSS`, `Click element`)
      .pathIs(`/search`, `Path is...`)
      .click(`div > div > div > div > div > div:nth-of-type(2) > div > div > h3 > a`, `CSS`, `Click element`)
      .pathIs(`/`, `Path is...`)
      .click(`ul > :nth-child(3) .header-left-nav-link`, `CSS`, `Click element`)
      .pathIs(`/dashboard/`, `Path is...`)
      .end();
  }
};

/*
 * Components 
 */

function bindComponents(browser) {

  browser.components = {};


}

/*
 * Auto-Generated helper code 
 */





function bindHelpers(browser) {


  var oldUrl = browser.url;
  var oldBack = browser.back;
  var oldForward = browser.forward;
  var oldRefresh = browser.refresh;
  const POLLING_RATE = 1000;

  var snptGetElement =
    `(function() {

      var w = window, d = w.document;

      function xp(x) { var r = d.evaluate(x, d.children[0], null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); return r.snapshotItem(0) };

      return w["snptGetElement"] = function(s, t) {
        try {
          return t === "XPATH" ? xp(s) :
                 t === "ID" ? d.querySelector("#" + s) :
                 t === "ATTR" ? d.querySelector("[" + s + "]") :
                 t === "NAME" ? d.querySelector("[name=\\"" + s + "\\"]") :
                 t === "TEXT" ? xp("//*[contains(text(), '" + s + "')]")
                 : d.querySelector(s); }
        catch(e) {
          return null
        }

      }

    })();`

  function prepStringFuncForExecute(funcToExecute) {
    return 'var passedArgs = Array.prototype.slice.call(arguments,0); return ' + funcToExecute + '.apply(window, passedArgs);';
  };

  function stringFormat(string) {
    var replacers = Array.prototype.slice.call(arguments, 1)

    replacers.forEach((replacer) => {
      string = string.replace("%s", replacer);
    });

    return string;

  };

  function noop() {};

  browser.url = function(pathname, width, height, description) {
    browser.perform(() => comment(description));
    oldUrl(pathname);
    browser.resizeWindow(width, height);
    return this;
  };

  browser.back = function(description) {
    browser.perform(() => comment(description));
    browser.pause(5);
    oldBack();
    return this;
  };

  browser.refresh = function(description) {
    browser.perform(() => comment(description));
    oldRefresh();
    return this;
  };

  browser.forward = function(description) {
    browser.perform(() => comment(description));
    oldForward();
    return this;
  };

  browser.pathIs = function(pathname, description, timeout) {

    var techDescription = stringFormat(" (Path matches '%s')", pathname);

    var attempts = parseInt((timeout || TIMEOUT) / POLLING_RATE);
    var currentAttempt = 0;

    function checkForPageLoadWithPathname(pathname) {
      browser.execute(prepStringFuncForExecute(`function() {
        return {
          pathname: window.location.pathname,
          readyState: document.readyState
        };
      }`), [], function(result) {
        if (result.value.readyState === "complete" && (pathname instanceof RegExp ? pathname.test(result.value.pathname) : result.value.pathname === pathname)) {
          this.assert.ok(true, description + techDescription)
        } else if (currentAttempt === attempts) {
          this.assert.ok(false, description + techDescription)
        } else {
          currentAttempt++;
          browser.pause(POLLING_RATE);
          checkForPageLoadWithPathname(pathname);
        }
      });
    }

    checkForPageLoadWithPathname(pathname);

    browser.execute(prepStringFuncForExecute(`function() {
      window.alert = function() {};
      window.confirm = function() {
        return true;
      };
    }`), []);

    return this;

  };

  browser.executeScript = function(description, script) {
    browser.perform(() => comment(description));
    browser.execute(script, [], function(result) {
      if (result) {
        browser.assert.ok(result, description)
      }
    });

    return this;
  };

  browser.switchToWindow = function(windowIndex, description) {
    browser.perform(() => comment(description));

    browser.windowHandles(function(result) {
      this.switchWindow(result.value[windowIndex]);
    });

    return this;
  };

  browser.scrollWindow = function(x, y, description) {
    browser.perform(() => comment(description));
    browser.execute(prepStringFuncForExecute(`function(x, y) {
      window.scrollTo(x, y);
    }`), [x, y], function(result) {});

    return this;
  };

  browser.scrollElement = function(selector, selectorType = "CSS", x, y, description, timeout) {

    var techDescription = stringFormat("(Scrolling element at '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType, x, y) {

      ${snptGetElement}

      (function(el, x, y) {
        el.scrollLeft = x;
        el.scrollTop = y;
      })(snptGetElement(selector, selectorType), x, y);
    }`), [selector, selectorType, x, y], function(result) {});

    return this;
  };

  browser.scrollWindowToElement = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(Scrolling window to el '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType, value) {

      ${snptGetElement}

      (function(el) {
        if (el) {
          var elsScrollY = el.getBoundingClientRect().top + window.scrollY - el.offsetHeight;
          window.scrollTo(0, elsScrollY);
        }
      })(snptGetElement(selector, selectorType), value);
    }`), [selector, selectorType]);

    return this;
  };

  browser.click = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(Click '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element to click. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

      ${snptGetElement}

      (function(element) {

        function triggerMouseEvent(node, eventType) {
          var clickEvent = document.createEvent('MouseEvents');
          clickEvent.initEvent(eventType, true, true);
          node.dispatchEvent(clickEvent);
        }

        triggerMouseEvent(element, "mouseover");
        triggerMouseEvent(element, "mousedown");
        triggerMouseEvent(element, "mouseup");
        triggerMouseEvent(element, "click");

      })(snptGetElement(selector, selectorType));

    }`), [selector, selectorType], function(result) {
      if (result.state === "success") {
        this.assert.ok(description + "; " + techDescription);
      }
    });

    return this;

  };

  browser.changeInput = function(selector, selectorType = "CSS", value, description, timeout) {

    var techDescription = stringFormat("(Change input '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType, value) {

      ${snptGetElement}

      (function(el) {
        function triggerKeyEvent(node, eventType) {
          var keydownEvent = document.createEvent( 'KeyboardEvent' );
          keydownEvent.initEvent( eventType, true, false, null, 0, false, 0, false, 66, 0 );
          node.dispatchEvent( keydownEvent );
        }

        if (el) {
          triggerKeyEvent(el, "keydown");
          el.focus();
          el.value = value;
          el.dispatchEvent(new Event('change', {bubbles: true}));
          el.dispatchEvent(new Event('input', {bubbles: true}));
          triggerKeyEvent(el, "keyup");
          triggerKeyEvent(el, "keypress");
        }
      })(snptGetElement(selector, selectorType), value);

    }`), [selector, selectorType, value], function(result) {
      if (result.state === "success") {
        this.assert.ok(description + "; " + techDescription);
      }
    });

    return this;

  };

  browser.elStyleIs = function(selector, selectorType = "CSS", style, value, description, timeout) {

    var techDescription = stringFormat("(Style is '%s' at '%s' using '%s')", value, selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    var attempts = parseInt((timeout || TIMEOUT) / POLLING_RATE);
    var currentAttempt = 0;

    function checkforStyle(selector, selectorType, style, value) {
      browser.execute(prepStringFuncForExecute(`function(selector, selectorType, style) {
        ${snptGetElement}
        var el = snptGetElement(selector, selectorType);
        return window.getComputedStyle(el, null).getPropertyValue(style);
      }`), [selector, selectorType, style], function(result) {
        if (value instanceof RegExp ? value.test(result.value) : value === result.value) {
          this.assert.ok(true, description + techDescription)
        } else if (currentAttempt === attempts) {
          this.assert.ok(false, description + techDescription)
        } else {
          currentAttempt++;
          console.log("Attempt %s: Actual %s, Expected %s", currentAttempt, result.value, value)
          browser.pause(POLLING_RATE);
          checkforStyle(selector, selectorType, style, value);
        }
      });
    }

    checkforStyle(selector, selectorType, style, value);

    return this;

  };

  browser.inputValueAssert = function(selector, selectorType = "CSS", value, description, timeout) {

    var techDescription = stringFormat("(Assert value '%s' at '%s' using '%s')", value, selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    var attempts = parseInt((timeout || TIMEOUT) / POLLING_RATE);
    var currentAttempt = 0;

    function checkforValue(selector, selectorType, value) {
      browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

        ${snptGetElement}

        var el = snptGetElement(selector, selectorType);

        if (el) {
          if (el.type === 'checkbox' || el.type === 'radio') {
            return el.checked ? "true" : "false";
          } else {
            return el.value;
          }
        } else return null;
      }`), [selector, selectorType], function(result) {
        if (value instanceof RegExp ? value.test(result.value) : value === result.value) {
          this.assert.ok(true, description)
        } else if (currentAttempt === attempts) {
          this.assert.ok(false, description)
        } else {
          currentAttempt++;
          browser.pause(POLLING_RATE);
          checkforValue(selector, selectorType, value);
        }
      });
    }

    checkforValue(selector, selectorType, value);

    return this;

  };

  browser.elementPresent = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(Element exists' at '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("'%s' - Couldn't find element. %s", description, techDescription));
    }, () => {
      browser.assert.ok(true, stringFormat("'%s' - %s", description, techDescription));
    });

    return this;

  };

  browser._elementPresent = function(selector, selectorType = "CSS", description, timeout, onFail = noop, onSuccess = noop) {

    var attempts = parseInt((timeout || TIMEOUT) / POLLING_RATE);
    var currentAttempt = 0;

    function checkforEl(selector) {
      browser.execute(
        prepStringFuncForExecute(`function(selector, selectorType) {
          ${snptGetElement}
          return !!snptGetElement(selector, selectorType);
        }`), [selector, selectorType],
        function(result) {

          if (!result.value && currentAttempt < attempts) {
            currentAttempt++;
            browser.pause(POLLING_RATE);
            checkforEl(selector);
          } else if (!result.value) {
            onFail();
          } else {
            onSuccess();
          }

        });
    }

    checkforEl(selector);

    return this;

  };

  browser.elementNotPresent = function(selector, selectorType = "CSS", description, timeout) {
    browser.perform(() => comment(description));
    browser.waitForElementNotPresent(selector, timeout || TIMEOUT);
    return this;
  };

  browser.focusOnEl = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(Focus '%s' at '%s' using '%s')", value, selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

      ${snptGetElement}

      (function(el) {
        var event = new FocusEvent('focus');
        el.dispatchEvent(event);
      })(snptGetElement(selector, selectorType));
    }`), [selector, selectorType], function(result) {
      if (result.state === "success") {
        this.assert.ok(description + "; " + techDescription);
      }
    });

    return this;
  };

  browser.formSubmit = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(Form Submit at '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

      ${snptGetElement}

      (function(el) {
        var event = new Event('submit');
        el.dispatchEvent(event);
      })(snptGetElement(selector, selectorType));

    }`), [selector, selectorType], function(result) {
      if (result.state === "success") {
        this.assert.ok(description + "; " + techDescription);
      }
    });

    return this;
  };

  browser.blurOffEl = function(selector, selectorType = "CSS", description, timeout) {

    var techDescription = stringFormat("(blur '%s' using '%s')", selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

      ${snptGetElement}

      (function(el) {
        var event = new FocusEvent('blur');
        el.dispatchEvent(event);
      })(snptGetElement(selector, selectorType));

    }`), [selector, selectorType], function(result) {
      if (result.state === "success") {
        this.assert.ok(description + "; " + techDescription);
      }
    });

    return this;
  };

  browser._getElText = function(selector, selectorType = "CSS", onSuccess = noop) {

    browser.execute(prepStringFuncForExecute(`function(selector, selectorType) {

    ${snptGetElement}

    return (function(element) {
      if (!element) return null;
      var text = "";
      for (var i = 0; i < element.childNodes.length; ++i)
        if (element.childNodes[i].nodeType === 3)
          if (element.childNodes[i].textContent)
            text += element.childNodes[i].textContent;
      text = text.replace(/(\\r\\n|\\n|\\r)/gm, "");
      return text.trim();
    })(snptGetElement(selector, selectorType));
  }`), [selector, selectorType], function(result) {
      onSuccess(result.value);
    });

    return this;

  };

  browser.elTextIs = function(selector, selectorType = "CSS", assertText, description, timeout) {

    var techDescription = stringFormat("(Assert text matches '%s' at '%s' using '%s')", assertText.toString(), selector, selectorType);

    browser._elementPresent(selector, selectorType, null, timeout, () => {
      browser.assert.ok(false, stringFormat("FAILED: '%s' - Couldn't find element. %s", description, techDescription));
    });

    var attempts = parseInt((timeout || TIMEOUT) / POLLING_RATE);
    var currentAttempt = 0;

    function checkforText(selector, selectorType, assertText) {
      browser._getElText(selector, selectorType, function(elsText) {
        if (assertText instanceof RegExp ? assertText.test(elsText) : assertText === elsText) {
          browser.assert.ok(true, description)
        } else if (currentAttempt === attempts) {
          browser.assert.ok(false, description)
        } else {
          currentAttempt++;
          browser.pause(POLLING_RATE);
          checkforText(selector, selectorType, assertText);
        }
      });
    }

    checkforText(selector, selectorType, assertText);

    return this;

  };

  function comment(description) {
    if (description) {
      console.log(description);
    }
  }

};

It shows the error when run in cmd using nightwatch command :

Starting selenium server... started - PID:  876

[Homepage] Test Suite
=========================

Running:  Unnamed test
Load page...
 × Failed [ok]: (FAILED: 'Change input' - Couldn't find element. (Change input '#lst-ib' using 'CSS'))  - expected "true" but got: "false"
    at browser._elementPresent (D:\NightwatchJS\tests\homepage.js:279:22)
    at Object.<anonymous> (D:\NightwatchJS\tests\homepage.js:426:13)


FAILED:  1 assertions failed (22.431s)

 _________________________________________________

 TEST FAILURE:  1 assertions failed, 0 passed. (22.547s)

 × homepage

   - Unnamed test (22.431s)
   Failed [ok]: (FAILED: 'Change input' - Couldn't find element. (Change input '#lst-ib' using 'CSS'))  - expected "true" but got: "false"
       at browser._elementPresent (D:\NightwatchJS\tests\homepage.js:279:22)
       at Object.<anonymous> (D:\NightwatchJS\tests\homepage.js:426:13)

Is this not the proper format that can be deployed in Nightwatch Test Framework?? Is it a syntax problem/error which i am missing .

I want the test code generated in Snaptest to work in NightwatchJS NPM test framework.

I use selenium standalone server 3.9.0 and chromewebdriver .

Suggestions. THANKS !

Using makeWith in combination with mocking

In my code I'm using makeWith to resolve dependencies. In my tests I'm creating a mock that should be resolved in the code by calling the makeWith. However it's not the case.

App::make('App\Item'); //ok: returns mock
App::makeWith('App\Item', ['name' => 'apple'];//not ok: doesn't return the mock but the class to be used outside the test environment

Is this a bug or am I missing something?

npm test failed while testing react js application

Here, I am doing unit testing on some component in my reactjs application through enzyme.But after firing npm test command it gives an error and I don't know what is that error and how can solve it. Please help me to solve this error. Here, I attach test.js file and console output.

NavigationItems.test.js:

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem/NavigationItem';
configure({adapter: new Adapter()});
describe('<NavigationItems />', () => {
let wrapper;
beforeEach(() => {
    wrapper = shallow(<NavigationItems />);
});
it('should render two <NavigationItem /> elements if not authenticated', () => {        
    expect(wrapper.find(NavigationItem)).toHaveLength(2);
});
it('should render three <NavigationItem /> elements if authenticated', () => {
    //const wrapper = shallow(<NavigationItems isAuthenticated />);
    wrapper.setProps({isAuthenticated: true});
    expect(wrapper.find(NavigationItem)).toHaveLength(3);
}); });

Console Output:

abc-17@abc17-B250M-D2V:~/bb1$ npm test

> burger-builder@0.1.0 test /home/abc-17/bb1
> node scripts/test.js --env=jsdom

fs.js:1384
    throw error;
    ^

Error: watch /home/abc-17/bb1/node_modules/lodash.uniq ENOSPC
    at _errnoException (util.js:1022:11)
    at FSWatcher.start (fs.js:1382:19)
    at Object.fs.watch (fs.js:1408:11)
    at NodeWatcher.watchdir (/home/abc-17/bb1/node_modules/sane/src/node_watcher.js:150:20)
    at Walker.<anonymous> (/home/abc-17/bb1/node_modules/sane/src/node_watcher.js:374:12)
    at emitTwo (events.js:126:13)
    at Walker.emit (events.js:214:7)
    at /home/abc-17/bb1/node_modules/walker/lib/walker.js:69:16
    at go$readdir$cb (/home/abc-17/bb1/node_modules/graceful-fs/graceful-fs.js:149:14)
    at FSReqWrap.oncomplete (fs.js:135:15)
npm ERR! Test failed.  See above for more details.

What is the screenshot tool?

As the picture showing below, blue color and with an cute arrow, very beautiful. Anyone please tell me what the screenshot tool it is that can make such pretty thing.

enter image description here

How to convert xml files into excel through protractor.Any idea?

I want the output of my protractor test reports in excel, right now its generating in HTML format. They are also generating in XML format. Any idea will be helpful and will be appreciated. Thank you.

Is it possible to do GivenStories parametrized by scenario meta parameters and by Examples same time in JBehave?

Auth.story
Scenario: Login into Application.
Meta:
@id1 Login
Given initialised for <BaseMarker>
When user with username <email> and password <password> logs in
Then user is logged in as <username>

Scenario: Logout from the Application.
Meta:
@id2 Logout
When user logs out
Then user is logged out


Test.story
GivenStories: authentication.story#{id1:Login}
When ....
Then ....

Examples:
|BaseMarker|email|password|username|
|xxxxxxxxxxx|yyyyy|zzzzzzzz|++++++++|



Here I've no idea how to pass the Examples to Scenario Login into Application (@id1 Login) from the Test.story.


Please help me to sort it out.
Thanks in advance!!!

Angular - Testing an @Input with a set attached to it

I have a component which takes an argument as a sort of directive to set the size of the <div> within its template, the only problem now is that I am unsure how to test it?

I call my component like this, where small can be replaced with other pre-defined sizes such as medium/large etc:

<spinner small></spinner>

I then take this as an @Input(<size>) and perform a set to change a size variable that is then passed into an [ngStyle] to change the CSS of the displayed component size.

component.ts

size: number;

@Input('small') set small(value) {
  this.size = !value ? 25 : this.size;
}

get getSize() {
  const myStyle = {
    width: this.size + 'px',
    height: this.size + 'px'
  };
  return myStyle;
}

component.html

<div [ngStyle]="getSize"></div>

I have successfully tested the get getSize() function, but I have become a bit stuck around the @Input(<val>) set functions :-/

Mocha test for svg

I am totally new to testing. Just want to write a test for my svg element using polymer 3. My code looks like blow

import {LitElement, html} from '@polymer/lit-element';

export class CDSCEMark extends LitElement {
  render() {
    return html`
      <style>
        :host {
          height: 2.5rem;
          display: flex;
          align-self: flex-end;
        }

        svg {
          width: auto;
          height: 100%;
          display: block;
        }
      </style>
      <svg viewbox="0 0 280 200" preserveaspectratio="xMinYMin meet" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;">
          <path d="M110,199.498744A100,100 0 0 1 100,200A100,100 0 0 1 100,0A100,100 0 0 1 110,0.501256L110,30.501256A70,70 0 0 0 100,30A70,70 0 0 0 100,170A70,70 0 0 0 110,169.498744Z" fill="black"/>
          <path d="M280,199.498744A100,100 0 0 1 270,200A100,100 0 0 1 270,0A100,100 0 0 1 280,0.501256L280,30.501256A70,70 0 0 0 270,30A70,70 0 0 0 201.620283,85L260,85L260,115L201.620283,115A70,70 0 0 0 270,170A70,70 0 0 0 280,169.498744Z" fill="black"/>
      </svg>
    `;
  }
}

customElements.define('cds-ce-mark', CDSCEMark);

jeudi 30 août 2018

Keep application-state in protractor E2E tests

I have a big application written with angular and I currently try to introduce e2e testing. Is it possible to keep the "state" of the application and not write a single it statement. So at the my tests look like this:

describe('Dashboard', () => {
  beforeEach(() => {
    // do login
  });

  it('should navigate to X', () => {
    // click on navigation
    // test if component X is open
  });

  it('should navigate to Y', () => {
    // click on navigation
    // test if component Y is open
  });

  it('should navigate to Z', () => {
    // click on navigation
    // test if component Z is open
  });
});

In the beforeEach the test logs into the app (so the dashboard is open). In every test, first there is a click on a navigation-element and I test if the according component opens.

What I want is that I don't have to do the login in each beforeEach in any of my tests. So the tests keep the state of the application and that the application running all the time as in "real usage" and not restart after every test. Is the only possibility for this to write a single it statement like this:

describe('Application', () => {
    // do login

    // should navigate to X
    // click on navigation
    // test if component X is open

    // should navigate to Y
    // click on navigation
    // test if component Y is open

    // should navigate to Z
    // click on navigation
    // test if component Z is open
  });
});

Maybe I understand the e2e test wrong and I should use another sort of tests for this. If thats the case, could you give me some advice for a testing-framework which can be used for angular?

Thanks in advance!

Pass let parameter to shared context

I have a shared context and want to pass some variable outside to this shared example. I currently make it like this:

shared_context "test" do |param1, param2|
    before :each do
      puts "context:"
      puts param1
      puts param2
    end
  end

  describe 'test' do
    let(:name1) { "name_1" }
    include_context "test", name_1, "name_2"
    ...
  end

But I got error:

An error occurred while loading ./spec/car_spec.rb.
Failure/Error: include_context "test", name_1, "name_2"

NameError:
  undefined local variable or method `name_1' for RSpec::ExampleGroups::Car::Test:Class
  Did you mean?  name
                 name

It can't recognize the variable defined in let, how should I pass a variable defined outside of a shared context into it? Thanks!

I have a few question about MC/DC and piarwise testing

Recently, I started working on software testing, and I had some questions.

Pairwise testing is the combination of all the values ​​that this parameter can have, and is it also applicable to Boolean Expression?

For example,

boolean expression is (A || B) && C (It is assumed that each parameter has only 0 and 1.)

Here, Is it applicable to Boolean Exp ??

Second question is about MC/DC.

I had learned how to make test case through MC/DC

But, I wondered how MC/DC could prove to cover almost 90% code code coverage ?

In (A || B) && C, there are 4 combination test case in my guess.

But, All combination is 8. how could MC/DC reduce cases ?

gradle : java tests ran twice

I am making a skeletton of a java project; the gradle build file has an annoying problem : tests are ran twice, one time by the task 'JUnitPlatformTest' and a second time by the task 'test'.

The first one seems to trigger the second, so I can't disable it, and I would like to keep the second one as there is a little difference between them : the first one is in the console (of intelliJ) and the second uses the integrated intelliJ window.

here is gradle.build

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
        classpath group: 'de.dynamicfiles.projects.gradle.plugins', name: 'javafx-gradle-plugin', version: '8.8.2'
        classpath 'eu.appsatori:gradle-fatjar-plugin:0.3'
    }
}

plugins {
    id 'java'
    id 'edu.sc.seis.launch4j' version '2.4.4'
}

apply plugin: 'org.junit.platform.gradle.plugin'
apply plugin: 'javafx-gradle-plugin'
apply plugin: 'eu.appsatori.fatjar'

junitPlatform {
    platformVersion '1.0.3'
    reportsDir file('build/test-results/junit-platform')
    enableStandardTestTask true
    //show results summary even on success.
    details details.SUMMARY
    filters {
        tags {
            // Framework tests need to be run only when required to verify that this framework is still working.
            exclude "Framework"
        }
        includeClassNamePatterns '.*Test', '.*Tests'
    }
}



group 'lorry'
version '1'

sourceCompatibility = 1.8
//mainClassName="imports.ColorfulCircles"

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    def final junitVersion = "5.2.0"
    compile group: 'com.google.inject', name: 'guice', version: '4.1.0'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2'
    compile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: junitVersion
    //compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.11.0'
    compile group: 'org.assertj', name: 'assertj-core', version: '3.9.0'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'

    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: junitVersion
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.7.22'

    testRuntime group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: junitVersion

    compile 'org.hamcrest:hamcrest-all:1.3'

    testCompile "org.testfx:testfx-core:4.0.13-alpha"
    testCompile 'org.testfx:testfx-junit5:4.0.13-alpha'
    testRuntime 'org.testfx:openjfx-monocle:8u60-b27'

}

test {
    useJUnitPlatform()
    jvmArgs = [
            "-Dtestfx.robot=glass",
            "-Dtestfx.headless=true",
            "-Dprism.order=sw",
            "-Dprism.text=t2k",
            "-Dheadless.geometry=1920x1200-32"
    ]
}

test.dependsOn 'clean'

jfx {
    // minimal requirement for jfxJar-task
    mainClass = 'imports.ColorfulCircles'

    // minimal requirement for jfxNative-task
    vendor = 'lolveley'
}

jar {
    baseName = 'executable3'
    version =  ''
    manifest {
        attributes(
                'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
                'Main-Class': 'imports.ColorfulCircles'
        )
    }
}
launch4j {
    outfile='bibliotek-v3.exe'
    mainClassName = 'imports.ColorfulCircles'
    icon = "${projectDir}\\icons\\hands2.ico"
    copyConfigurable = project.tasks.fatJar.outputs.files
    jar = "lib/${project.tasks.fatJar.archiveName}"
    //headerType = "console"
    //jar = "${buildDir}\\productFatJar\\fat.jar"
}

junitPlatformTest {
        jvmArgs = [
                "-Dtestfx.robot=glass",
                "-Dtestfx.headless=true",
                "-Dprism.order=sw",
                "-Dprism.text=t2k",
                "-Dheadless.geometry=1920x1200-32"
        ]
    }

and here is the result:

Testing started at 19:25 ...
19:25:01: Executing task 'test'...

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :clean
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :junitPlatformTest
constructeur appelé
Before all
Before each
my test 1
Before each
my test 2
This test method should be run
Test run finished after 3630 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         7 tests found           ]
[         0 tests skipped         ]
[         7 tests started         ]
[         0 tests aborted         ]
[         7 tests successful      ]
[         0 tests failed          ]
> Task :test
constructeur appelé
Before all
Before each
my test 1
Before each
my test 2
This test method should be run
BUILD SUCCESSFUL in 13s
5 actionable tasks: 5 executed
19:25:15: Task execution finished 'test'.

How to setup a sequence for an attribute while using create_batch in factory-boy?

When using factory_boy in Django, how can I achieve this?

models.py

class TestModel(models.Model):
    name = CharField()
    order = IntegerField()

recipes.py

class TestModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = TestModel

    name = factory.LazyAttribute(lambda o: faker.word().title())
    parent = 0

tests.py

recipes.TestModelFactory.create_batch(4, order=+10)

or

recipes.TestModelFactory.create_batch(4, order=seq(10))

or something along those lines, to achieve this result:

TestModel.objects.all().values_list('order', flat=True)

[10, 20, 30, 40]

Transferring variables between API tests in JS

I have following issue. I'm starting to create e2e api tests the aim of first test is to get unauthorized user token, second test use value from first test in method header and returning token for authorized user - and after all, second token will be used in further tests. How to save value of tokens in variable and pass it through tests?

I'm new in JS and now i received 'ReferenceError: auth_token is not defined'

const chai = require('chai');
const request = require('request-promise-native');
const mocha = require('mocha');
const config = require('../config');

const assert = chai.assert;
//const describe = mocha.describe;
//const it = mocha.it;
// request.debug = true;

describe('0_auth', () => {
  it('should return token for unauthorized user', async () => {
  const result = await request({
  headers: config.headers,
  url: `${config.url}/rest/v1/auth/get-token`,
  method: "POST",
  json: {
      "deviceUuidSource": "DEVICE",
      "source" : "KIOSK",
      "deviceUuid" : "uniquedeviceuuid"
  }
});
   assert.isNotNull(result);
   assert.property(result, 'token');
   var auth_token=result.token;
   console.log(auth_token)
   }).timeout(15000);


 it('should return token for authorized user', async () => {
 const result = await request({
  headers: Object.assign(config.headers, { 'Authorization': 'Bearer '+auth_token }),
  url: `${config.url}/rest/v1/auth/with-password`,
  method: "POST",
  json: {
    "email" : "dulexun3hvw0@10minut.xyz",
    "password" : "Test123"
     }
   });
   assert.isNotNull(result);
   assert.property(result, 'token');
   assert.property(result, 'user');
   console.log('token:', result.token);
 }).timeout(15000);
 });

in further test i want to pass Bearer token to Authorization field in diffrent class config.js

config.headers = {

 'User-Agent': 'WOR API Tester', // android
  Source: 'MOBILE',
 'Accept-Language': 'EN',
 Authorization:'Bearer '+auth_token;


};
module.exports = config;

Testing - set declined card to a customer

I want to update a customer with a declined card for testing purposes.

But if I do:

Stripe.customers.update(stripeCustomer.id, {
    source: 'tok_chargeDeclined', // Token provided by stripe of a declined card
});

Exception while invoking method 'stripe.test' { Error: Your card was declined.

What I am missing?

Tests are running sequentially in protractor even when shard files is true

I am running the tests using protractor .I have 3 specs file but still it runs sequentially What am i missing here ? Code : capabilities: { 'browserName': 'chrome', chromeOptions: { args: ['--headless', "--disable-gpu", "--window-size=1920,1080"]

    },
    // Ability to run the tests in parallel.
    shardTestFiles: true,
    maxInstances: 2
},

Spring - How to test publishing of an event?

I have a Controller which is publishing an event

@RestController
public class Controller
{
    @Autowired
    private ApplicationEventPublisher publisher;

    @GetMapping("/event")
    public void get()
    {
        publisher.publishEvent(new Event());
    }
}

Now I want to test that the event is published. First I tried to @MockBean the ApplicationEventPublisher and verify the method call. But this does not work according to https://jira.spring.io/browse/SPR-14335

So I am doing it like this:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = Controller.class)
public class ControllerTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void getTest() throws Exception
    {
        this.mockMvc.perform(get("/").contentType(MediaType.APPLICATION_JSON)
                    .andExpect(status().isOk());
        assertNotNull(Listener.event);
    }

    @TestConfiguration
    static class Listener
    {
        public static Event event;

        @EventListener
        void listen ( Event incoming )
        {
            event = incoming;
        }
    }
}

Is there an easier way for this common use case?

Spring Boot @WebMvcTest returns 404 if success login

I'm learning how to Test my SpringBoot Apps.

Right now I'm trying to learn by creating test for an existing working project.

I started with my AdminHomeController that manages the Home when admins login:

@Controller
@RequestMapping("/admin/home")
public class AdminHomeController {

private UsuarioService usuarioService;

@Autowired
public AdminHomeController(UsuarioService usuarioService) {
    this.usuarioService = usuarioService;
}

@RequestMapping(value={"", "/"}, method = RequestMethod.GET)
public ModelAndView admin_home(){
    ModelAndView modelAndView = new ModelAndView();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Usuario loggedUser = usuarioService.findUsuarioByUsername(auth.getName());
    modelAndView.addObject("userFullName", loggedUser.getNombre() + " " + loggedUser.getApellido());
    modelAndView.addObject("userGravatar", Utils.getGravatarImageLink(loggedUser.getEmail()));

    modelAndView.addObject("totalUsuarios", usuarioService.getUsuariosCount());


    modelAndView.setViewName("admin/home");
    return modelAndView;
}
}

And this is my test:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyOwnProperties.class)
@WebMvcTest(AdminHomeController.class)
@Import(SecurityConfigurationGlobal.class)
public class AdminHomeControllerUnitTest {

@Autowired
private MockMvc mockMvc;

@MockBean
UsuarioService usuarioService;

@Autowired
MyOwnProperties myOwnProperties;

@MockBean
FacebookProfileService facebookProfileService;

@MockBean
MobileDeviceService mobileDeviceService;

@MockBean
PasswordEncoder passwordEncoder;

@MockBean
CustomAuthenticationProvider customAuthenticationProvider;


@Test
@WithMockUser(username = "user1", password = "pwd", authorities = "ADMIN")
public void shouldAllowAdminAccess() throws Exception{
    when(usuarioService.findUsuarioByUsername("user1")).thenReturn(new Usuario());


    mockMvc.perform(get("/admin/home"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(view().name("admin/home"));
}

}

And I think that the relevan part of my SecurityConfig would be:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.
            authorizeRequests()
            .antMatchers("/", "/login", "/error/**", "/home").permitAll()
            .antMatchers(
                    myOwnProperties.getSecurity().getJwtLoginURL(),
                    myOwnProperties.getSecurity().getFacebookLoginURL()).permitAll()
            .antMatchers("/registration", "/registrationConfirm/**").permitAll()
            .antMatchers("/resetPass", "/resetPassConfirm/**", "/updatePass").permitAll()
            .antMatchers("/admin/**").hasAuthority(AUTHORITY_ADMIN)
            .antMatchers("/user/**").hasAuthority(AUTHORITY_USER)
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error=true")
            .successHandler(new CustomUrlAuthenticationSuccessHandler())
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/")
            .and()
            .exceptionHandling().accessDeniedPage("/403");
}

And AUTHORITY_ADMIN is a static final definition of "ADMIN".

What I can not understand due to my lack of experience are my test results.

  • If I remove the @WithMockUser I get a 401 as expected
  • If I use the @WithMockUser with ANY other authority than "ADMIN" I get a 403 that would also be the expected response
  • And finally if I use the @WithMockUser with "ADMIN" authority then I get a 404

As said, my app is working and I can only access /admin/home if logged in as ADMIN.

UPDATE

Running this other similiar test works fine, but this one requieres the FULL SpringBoot app to load. I think it would be an integration test and I only want to test the controller "alone". Only a slice using @WebMvcTest

@SpringBootTest
@AutoConfigureMockMvc
public class AdminHomeControllerTest {

@Autowired
private MockMvc mockMvc;


@MockBean
private UsuarioService usuarioService;

@Test
@WithMockUser(username = "user1", password = "pwd", authorities = "ADMIN")
public void shouldAllowAdminAccess() throws Exception{
    when(usuarioService.findUsuarioByUsername(anyString())).thenReturn(new Usuario());


    mockMvc.perform(get("/admin/home"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(view().name("admin/home"));
}

}

VSTest with xml/json reports obtained from Katalon

We are looking for your help to use the module VSTest – TestAssemblies.

Let me summarise our workflow before asking the question. We are trying to automate our tests. In order to do it, we decided to record the interaction with the browser through a 3rd party software. We managed to successfully integrated TFS and the 3rd party software: this means that when someone runs a test in TFS, underneath the hood TFS launches the 3rd party software and makes it repeat the recorded instructions, finally the 3rd party software saves the reports as .xml or .json files. For completeness, the 3rd party software that we use is Katalon.

We’d like to publish the reports using the module VSTest – TestAssemblies. It is my understanding that this module takes as input the results of a test run, then converts it to a .trx file and finally publishes statistics and analytics. The 3rd party sw that we use saves the results in an xml or json file, therefore the .trx file that TestAssemblies generates is empty and invalid. Is there any way to make TestAssemblies support .xml/.json files? What are the formats that TestAssemblies supports?

Thanks a lot in advance for your help Luigia

Angular - Test component with custom injection - StaticInjectionError

I have an Angular library which gets configuration for an API with forRoot:

static forRoot(api: Api): ModuleWithProviders {
  return {
    ngModule: XyzModule,
    providers: [XyzComponent, { provide: 'API', useValue: api }]
  };

}

The module injects the object into the a component:

constructor(
  ...
  @Inject('API') private api: Api
) { }

This works very well when building the app or running it with ng serve.

However, when I try to test the component with ng test, I get the following error:

Error: StaticInjectorError(DynamicTestModule)[api]: 
  StaticInjectorError(Platform: core)[api]: 
    NullInjectorError: No provider for api!

The test file provides an Api object:

describe('XyzComponent', () => {
  beforeEach(async(() => {
    const api: Api = { url: 'http://localhost:8080' };
    TestBed.configureTestingModule({
      declarations: [ XyzComponent ],
      imports: [ ... ],
      providers: [
        { provide: 'API', useValue: api }
      ]
    })
    .compileComponents();
  }));
})

I already tried:

  • Replacing the string token with an InjectionToken
  • Using the inject() function for each test separately

.. but nothing works. Any ideas?

Stubbing express middleware functions with sinon is

I'm trying to use sinon stubbing via callsFake function, just as it's advised from their most updated docs.

Even though I'm requiring the module and replacing the function from the property at the export. I keep seeing the original function behavior acting.

I know that I should try to get the function stubbed before the middlewares get setup, and that's when express app is first imported.

This is the function I'm trying to stub, defined as a function and exported as a object too. It's defined in a script file with a path like api/middlewares/stripe/signature.

const stripeHelper = require('../../../lib/stripe')
const logger = require('../../../lib/logger')
const verifySignature = (req, res, next) => {
  let event
  let eventName = req.url.replace('/', '')
  try {
      // Try adding the Event as `request.event`
    event = stripeHelper.signatureCheck(
        eventName,
        req.body,
        req.headers['stripe-signature']
      )
  } catch (e) {
      // If `constructEvent` throws an error, respond with the message and return.
    logger.error('Error while verifying webhook request signature', e.message, e)
    return res.status(400).send('Webhook Error:' + e.message)
  }
  req.event = event
  next()
}
module.exports.verifySignature = verifySignature

Then I've tried to stub such middleware this way:

before(function (done) {
  verifySignatureStub = sinon.stub(signatureMiddleware, 'verifySignature')
  rawStub = sinon.stub(bodyParser, 'raw')
  rawStub.callsFake(function (req, res, next) {
    return next()
  })
  verifySignatureStub.callsFake(function (req, res, next) {
    const {customerId} = req.params.customerId
    const subscriptionId = req.params.subscriptionId
    const planId = req.params.planId
    req.event = generateEventFromMock('invoice.payment_failed', {subscriptionId, customerId, planId})
    return next()
  })
  done()
})

after(function (done) {
  verifySignatureStub.restore()
  rawStub.restore()
  done()
})

In my test I'm trying to make sure app, my express instance is just required AFTER the stubs are set.

Tried in different ways but always seeing the original middleware function acting instead of the replace stub I'm trying to get used.

Particularly, tried to:

  • Defined the stub within a before hook at my test file BEFORE requiring app
  • Getting a bootstrap.test.js file and require it at a mocha.opts file
  • Manually require a file with such hooks ay my test file

None of these worked so far, always seeing the original function executed.

Any suggestions or ideas?

How to set a value with calculations with no setter?

I'm in need of help! So I have made methods that already run great and have been tested with unit tests! However I realized that it was needed of me to not have a setter for a get. This pretty much gave me errors and now I'm stuck.

This photo shows a unit test I made to test out if the debit was valid.

enter image description here This was my getter and setter. And since taking out the setter I have gotten errors. I know that I have to do something with the return value but am unsure what I should do. Two methods are connected to the balance.enter image description here

I am unsure on how i'd be able to make the calculations without having a setter. Please help!

Like TESTNG testing framework in JAVA,,, what is the Testing framework for Python Selenium?

Like TESTNG testing framework in JAVA,,, what is the Testing framework for Python Selenium ???

JMeter and data test visualization

I'm novell in JMeter's world and I'm trying to get graphs with only the data used in the test, no JMeter's metrics needed.

My test case consists in many sensors sending information to a central point, wich has to process this info and send a response to a consumer.

The group of sensor are a group of threads where every single sensor has it's own csv data file. The consumer is an AMQP Consumer.

I would like to save in cvs files the next:

  • One file for the information sent by the every sensor with the timestamp(one file->one sensor).
  • One file containing all consumer's responses.

By now, I have mess with Agreggated Report and sample_variables declarated in user.properties file. In this way, Jmeter includes the variables declarated in user.properties in every report.

Does JMeter fits for my needs?

Best regards.

Angular - Unit testing keypress

I have a function that detects a keypress and if the key pressed = escape, a function is fired.

I am having trouble with faking the KeyboardEvent itself to be passed in.

I saw this post, but implementing this solution yields the following output (I console.logged the event itself):

LOG: KeyboardEvent{isTrusted: false} Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent should call onDeny when ESCAPE button pressed FAILED Expected spy onDeny to have been called.

component.ts

@HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    console.log(event);
    // Press escape - close dialog with simulated 'cancel' click
    if (event.code === 'Escape') {
      this.onDeny();
    }
  }

  onDeny() {
     // something is done here
  }

test.ts

it('should autofocus on cancel button on init', () => {
    spyOn(component, 'onDeny');
    component.keyEvent(ESCAPE);
    expect(component.onDeny).toHaveBeenCalled();
  });

Conflict with dependency 'com.android.support:support-media-compat' in project ':app'

When I try to start a test I get this error:

Conflict with dependency 'com.android.support:support-media-compat' in project ':app'. Resolved versions for app (27.0.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

and here's my build.gradle dependencies:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'

    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:1.1.1"
    annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
    // ButterKnife Library
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    // Gson Library
    implementation 'com.google.code.gson:gson:2.8.5'
    // Glide Library
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    // ExoPlayer Library
    implementation 'com.google.android.exoplayer:exoplayer-core:2.8.3'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.8.3'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation "com.android.support.test:rules:1.0.2"
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support:support-annotations:27.1.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'
}

I don't see using the version 27.0.0 anywhere in my code, and I think that ExoPlayer might be using that version internally! What can I possibly do to solve the conflict?!

Cognizant selenium automation

Can any one help me knowing that what questions they may ask in the interview.

I have an interview on Saturday for automation selenium and i am new to selenium.

Please help

Angular - Unit testing focusing on button

I am attempting to unit test whether my button has been focused on, but I cannot seem to get the spy to work correctly?

I saw this post, but it hasn't helped fully.

Am I missing something obvious?

component.ts

ngOnInit() {
    // autofocus on the cancel button to guard against mistakes
    document.getElementById('cancel').focus();
  }

component.spec.ts

beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ ConfirmationComponent ],
      providers: [ MessageService]
    });

    fixture = TestBed.createComponent(ConfirmationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    component.ngOnInit();
  });

  it('should autofocus on cancel button on init', () => {
    const cancelButton = document.getElementById('cancel');
    spyOn(cancelButton, 'focus');
    expect(cancelButton.focus).toHaveBeenCalled();
  });

Web Performance Test(MVC5)

i'm trying to create a web performance test for my MVC project but i'm getting this error:

could not load type 'Microsoft.VisualStudio.TestTools.WebTesting.SharepointInformation' from assembly 'Microsoft.VisualStudio.QualityTools.WebTestFramework, version = 10.0.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a

am i missing an assembly? thank you for your help

Angular - Unit testing Subject()?

I have a Angular service that simply uses a Subject, but I am unsure of how to write unit tests for it.

I saw this thread, but I didn't find it terribly helpful.

I have attempted to mock next() but I am more than a little lost.

message.service.ts

serviceMsg: Subject<IMessage>;

  constructor() {
    this.serviceMsg = new Subject();
  }

  confirm(action: MessageActions) {
    this.serviceMsg.next({result: true, action: action});
  }

IMessage.ts

export interface IMessage {
  result: boolean;
  action: MessageActions;
}

MessageActions.ts

export enum MessageActions {
  STATUS_UPDATE
}

spec.ts

describe('MessageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MessageService]
    });
    fixture = TestBed.createComponent(MessageService);
    service = fixture.componentInstance;
    httpMock = TestBed.get(HttpTestingController);
  });

  it('should be created', inject([MessageService], (service: MessageService) => {
    expect(service).toBeTruthy();
  }));

  it('should catch what is emitted', () => {
    const nextSpy = spyOn(service, 'next');
    service.confirm(ACTION);
    expect(nextSpy).toHaveBeenCalled();
  });
});

mercredi 29 août 2018

How to setup MongoDB from Mocha for some Node.js tests?

I'm manually testing some Node.js endpoints that access a MongoDB. And I'm using run-rs to setup replica sets in development mode (https://www.npmjs.com/package/run-rs)

My process is the following:

  1. $ run-rs -v 4.0.0 -s
  2. rs:PRIMARY> use my_db
  3. rs:PRIMARY> load("create-db.js")

Then in a separate terminal window, npm start to run my Node.js app and connect to my_db. In create-db.js I have the setup of many collections. Something like:

db.categorie.insert({"categories":["all","cat","dog","cow","mus"]});

var users = [{
    "_id" : ObjectId("5b7b99477943f109fba8b128"),
    "admin" : false,
    "log" : false,
    "city" : "",
    "state" : "",
    "country" : "",
    "active" : true,
    "forgot" : false,
    "email" : "some+user@gmail.com",
    "hash" : "88409d4e8754af084ccb8554934e979bcd7c6a7f2532915b225a47b97de9b80a70c2c025e5610d9cdc15afebdd4efe26f9df586ee3b57763d196c96fb5dff96a1e3cfa80acf0bd232acb5b8eb7a2e9cf06a48dfd9b8cfd16ebd6fc33a1d7c5a6f66fb1c1efa45c570acb16e08c1867c8a58de40d4471433aa025de46cc21d07f52b68e0494f24f41efc2234c97070a943fb149640ae9e434de0df0154e0893718d3177c9bde61169cac2ee3bf265ffa99ca8338602d5be8c3e18aa7df99ba3cb38ca00bc17e85d680f92c6e3f84bb0cd63c062931b5e90793e9774c1f7c58a4312562e24752c366d5459ff9214b57309ac8e16357fee109cc1d397d48d1f1a6438d19226ffb0c42a175a0043a8a6405f85290657b1ce75504585123b0af9c1de01e3edc2d0538ab2246900e3a811c12ece1b2495e2d532a4a01f5e5ebc1ebe25853147071cfc394f9161d643b518327c5be777d5dabb701485a919533d972a046c4b86af6c3edf427ea73ac8d7a5cf19cf236ec9849984f4c1029a12c7ee0bc655125b9558eba223e6768a36c4bbbefdcda6f218561446bbc86efb41c4ca5755e89d3a4a9f3e7f480dea158e15687d6b1838356cc9ce37b86827283bb4a596681a4f691c5ab812769b753e7ece29d4dd81c90e98e3b8cf0261d88ecfc37c8d32db7efea99a84d2689d577cd20130b4c7f93493bd7c88d2a388c1de4d0d4c41d1",
    "salt" : "9b3a7884e00077a125e7cbdc9dddc09236804cee65gb31467910755aeb2759d0",
    "__v" : 0
},
{
...
},
{
...
}];
db.users.insertMany(users);

...and so on, with many other collections.

The database setup is huge and I want to keep things organised. The thing is that I'm running run-rs manually, and I'm also loading the script from mongo shell. I don't know how to to this from mocha - or even if it's best practice or not.

Clojure - How To Properly Mount State In Unit Tests

I'm attempting to test some database operations in a luminus app with the Monger database library.

Ideally, I'd like the following to work. I've stripped out some of the irrelevant code.

Test File:

(ns app.test.handler
  (:require [clojure.test :refer :all]
            [app.db.core :as db]))

(testing "create user"
    (db/create-user "test" "test" "test")
    (is (true? true))))

DB File

(defstate db*
  :start (-> env :database-url mg/connect-via-uri)
  :stop (-> db* :conn mg/disconnect))

(defstate db
  :start (:db db*))


(defn create-user
  "Creates a new user with a token"
  [username email password]
  (let [user {:username username
              :email email
              :password (hashers/derive password)
              }]
  (mc/insert db "user" user)))

This doesn't work, and gives me the following error:

java.lang.ClassCastException: mount.core.DerefableState cannot be cast to com.mongodb.DB

From what I can tell, this isn't mounting the DB correctly, so it can't call the database operations. I tried to move this mounting code to the test, but still received the same error.

I did get this to work:

Test file

(def db (mg/connect-via-uri "mongodb://127.0.0.1:27017/worldbuilder"))

(testing "create user"
     (let [user {:username "test"
                 :email "test"
                 :password "test"
                 :token "test"
                 }]
    (mc/insert (:db db) "user" user)
    (is (true? true))))

But this requires me to re-write the operation in my test defeating the purpose. If I leave the connection above, but call the db/create-user I get the same state error.

I'd like to be able to pass that connection defined in my test file into my other database file. Is there I way I can do this and get it to override how it's being set there?

Espresso testing on Android API 28 emulator click issue

This is only on Android devices with api level 28. trying to match a text after clicking the spinner fails.

Two approaches, one looking for a window that is not the activity, the second is looking for popup menu:

...
    // Look for text "Green" in the menu
    onView(withId(getFieldId(COLOR_ID))).perform(click());
    onView(withText("Green"))
            .inRoot(withDecorView(not(is(rule.getActivity().getWindow().getDecorView())))) // Look for popup menu
            .perform(click());

    // Second spinner, Look for the text "Medium"
    onView(withId(getFieldId(SIZE_ID))).perform(click());
    onView(withText("Medium")).inRoot(RootMatchers.isPlatformPopup()).perform(click());
...

Both are working fine with devices API <=27

Any idea why this is not working on 28? Thank you.

Test coverage 0% even with tests being executed (Opencover / xUnit)

I am using OpenCover to get the coverage of the tests in my application .Net Core

When I run the OpenCover command, my tests are executed, but no classes are visited. Furthermore, my coverage is always 0.

Total de testes: 2. Aprovados: 2. Com falha: 0. Ignorados: 0.
Execução de Teste Bem-sucedida.
Tempo de execução de teste: 7,6713 Segundos
Committing...
Visited Classes 0 of 18 (0)
Visited Methods 0 of 68 (0)
Visited Points 0 of 133 (0)
Visited Branches 0 of 74 (0)

==== Alternative Results (includes all methods including those without corresponding source) ====
Alternative Visited Classes 0 of 19 (0)
Alternative Visited Methods 0 of 92 (0)

My OpenCover command is this one:

"%LOCALAPPDATA%\Apps\OpenCover\OpenCover.Console.exe" -oldstyle -output:"%CD%\opencover.xml" -register:user -target:"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" -targetargs:"InterpretadorFaleConoscoWexTests\bin\Debug\net461\InterpretadorFaleConoscoWexTests.dll"

I already put the tag <DebugType>Full<DebugType> , tried with and without TestAdapterPath and oldStyle and other tags, and no one worked. My coverage is always 0.

Can anyone give me any help?

I´ve seen some people with the same problem. However, there was no answer that solved my problem.

Thank you in advance.

2123211234 used as test or default number

My telephone number is, and has been for almost 40 years, 212-321-1234. Yes, I know, it is a great number. Unfortunately it has been picked up and used as a test number in countless coding scenarios. I do not believe there has been any malicious intent, it just seems to be that folks think it is a fake number. It isn't. I am inundated with calls and texts. When it is used as a default place holder in an online form and someone doesn't enter a number, some bad code allows the test number to be displayed and sent out to marketing companies. Can you please spread the word to stop using this number in test account/defaults and to repair the code error that is allowing it to go through? Many thanks.

Java. Execute tests form one jar

I need to build one executable *.jar file, that will contains src and test classes (and their resources). I have:

  • custom testing framework (aka src classes);
  • public libs for http transport, etc (aka dependency for src classes);
  • bunch of tests (aka test classes);
  • TestNG (as dependency for test classes).

I also have my test runner, that run tests as:

testNG.run();

That read *.xml from resources (in test resources).

I tryed maven jar manual, but i need just ONE jar.

All answers on stack didn't work. One time i cant add manifest file, one time i can't add resources files, one time this is two differet jars and i need use one as dependency.

Anyone know working solution or this?

P.S. this in not a production code. I know, that have test in production jar is bad idea. this is test for QA team.

Spark Testing: does it worth? (Best Practices)

Using Apache Spark, I was wondering if it is really valuable producing test and in case at which level.

Reading Spark: The Definitive Guide they suggest:

The business logic in your pipelines will likely change as well as the input data. Even more importantly, you want to be sure that what you’re deducing from the raw data is what you actually think that you’re deducing. This means that you’ll need to do robust logical testing with realistic data to ensure that you’re actually getting what you want out of it.

Which suggests to introduce some sort of testing.

But what impress me is:

One thing to be wary of here is trying to write a bunch of “Spark Unit Tests” that just test Spark’s functionality. You don’t want to be doing that; instead, you want to be testing your business logic and ensuring that the complex business pipeline that you set up is actually doing what you think it should be doing.

Which outlines that Unit Testing is discouraged by the authors of this book (correct me if I misinterpreted).

What probably it is worth to test instead is the logic of the Data Transformation applied through Spark.

Again from the book:

First, you might maintain a scratch space, such as an interactive notebook or some equivalent thereof, and then as you build key components and algorithms, you move them to a more permanent location like a library or package. The notebook experience is one that we often recommend (and are using to write this book) because of its simplicity in experimentation

Which suggests to test your Data Transformation logic in an interactive environment such as Notebooks (e.g. Jupyter Notebooks for Pyspark). Basically you directly see what the transformations produce.

So I am asking to people with more experience than me, do you agree with the cited points from the book? (or am I misinterpreting) Can they be used as a sort of Best Practices in this domain? (for example avoiding Unit Tests, promoting instead higher level testing like Logic / Integration Tests)

Unit tests with new Android X

I've tried to use new android x and create some unit test. But i can't find new test runner for it. I've tried:

androidx.test:runner:1.1.0-alpha1.AndroidJUnitRunner 

and get

java.lang.ClassNotFoundException: androidx.test.runner.AndroidJUnit4

What i should do?

AutoWiring steps with Spring Cucumber Serenity

I'm failing miserably to auto wire some steps. To illustrate the point, I made a small sample project on github

https://github.com/lpicquet/serenity-cucumber-spring

I am trying to autowire steps so that I can share data between them but the test is currently failing. Anyone can help?

Call Request From Collection Within Pre-Request Script

I am fully aware that there is a way to make an ajax call from within a request's Pre-request script, a la,

const getBooks = {
    url: "http://" + pm.environment.get("host") + "/books",
    method: "GET",
    header: "G-TOKEN:ROM831ESV"
};

pm.sendRequest(getBooks, function(err, books) {
   const ids = _.map(books.json(), function(book) {
       return book.id;
   });

   pm.globals.set("bookIds", ids);
});

pane but is there a way to call a saved request from a collection by name like you can do with postman.setNextRequest('') something akin to...

pm.sendRequest('Get Books', function(err, books) {
   const ids = _.map(books.json(), function(book) {
       return book.id;
   });
});

javafx & testfx : HeadlessException at java.awt.MouseInfo.getPointerInfo

I created a skeletton of a java gradle project using javaFx and testFx. When running the test gradle task, I get the following error, on the line which clicks on the button :

java.awt.HeadlessException at java.awt.MouseInfo.getPointerInfo(MouseInfo.java:74) at org.testfx.service.adapter.impl.AwtRobotAdapter.getMouseLocation(AwtRobotAdapter.java:78) at org.testfx.robot.impl.BaseRobotImpl.retrieveMouse(BaseRobotImpl.java:77) at org.testfx.robot.impl.MoveRobotImpl.moveTo(MoveRobotImpl.java:55) at org.testfx.robot.impl.ClickRobotImpl.clickOn(ClickRobotImpl.java:57) at org.testfx.api.FxRobot.clickOn(FxRobot.java:595) at ...

all the tests pass excepted "should_click_on_button(FxRobot)".

here are the test class and my build.gradle. In the test class, an arrow shows the faulty line.

thank you!

test class:

package imports;

import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.ApplicationTest;

import java.awt.*;
import java.util.concurrent.TimeoutException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.testfx.api.FxAssert.verifyThat;
import static org.testfx.api.FxToolkit.registerPrimaryStage;
import static org.testfx.matcher.control.LabeledMatchers.hasText;

@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@ExtendWith(ApplicationExtension.class)
class ClickableButtonTest extends ApplicationTest {

    @BeforeAll
    static void setUp() throws TimeoutException {
        System.setProperty("testfx.robot", "glass");
        System.setProperty("testfx.headless", "true");
        System.setProperty("prism.order", "sw");
        System.setProperty("prism.text", "t2k");
        System.setProperty("java.awt.headless", "true");
        registerPrimaryStage();

    }



    public void start(Stage stage) {
        Button button = new Button("click me!");
        button.setId("marqueur");
        button.setOnAction(actionEvent -> button.setText("clicked!"));
        stage.setScene(new Scene(new StackPane(button), 100, 100));
        stage.show();
    }

    public Parent getRootNode() {
        ClickableButtonTest app = new ClickableButtonTest();
        return app.getRootNode(); // the root StackPane with button
    }


    @Test
    void should_contain_button() {
        // expect:
        //verifyThat(".button", hasText("click me!"));
        verifyThat("#marqueur", hasText("click me!"));
    }

    @Test
    void should_click_on_button(FxRobot robot) {
        // when:
        robot.clickOn(".button");

        // then:
        verifyThat(".button", hasText("clicked!"));
    }

    @Test
    public void given2Strings_whenEqual_thenCorrect() {
        String a = "foo";
        String b = "FOO";
        assertThat(a, equalToIgnoringCase(b));
    }




}

build.gradle:

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
        classpath group: 'de.dynamicfiles.projects.gradle.plugins', name: 'javafx-gradle-plugin', version: '8.8.2'
        classpath 'eu.appsatori:gradle-fatjar-plugin:0.3'
    }
}

plugins {
    id 'java'
    id 'edu.sc.seis.launch4j' version '2.4.4'
}

apply plugin: 'org.junit.platform.gradle.plugin'
apply plugin: 'javafx-gradle-plugin'
apply plugin: 'eu.appsatori.fatjar'

junitPlatform {
    platformVersion '1.0.3'
    reportsDir file('build/test-results/junit-platform')
    enableStandardTestTask true
    //show results summary even on success.
    details details.SUMMARY
    filters {
        tags {
            // Framework tests need to be run only when required to verify that this framework is still working.
            exclude "Framework"
        }
        includeClassNamePatterns '.*Test', '.*Tests'
    }
}



group 'lorry'
version '1'

sourceCompatibility = 1.8
//mainClassName="imports.ColorfulCircles"

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    def final junitVersion = "5.2.0"
    compile group: 'com.google.inject', name: 'guice', version: '4.1.0'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2'
    compile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: junitVersion
    //compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.11.0'
    compile group: 'org.assertj', name: 'assertj-core', version: '3.9.0'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'

    testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: junitVersion
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.7.22'

    testRuntime group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: junitVersion

    compile 'org.hamcrest:hamcrest-all:1.3'

    testCompile "org.testfx:testfx-core:4.0.13-alpha"
    testCompile 'org.testfx:testfx-junit5:4.0.13-alpha'
    testRuntime 'org.testfx:openjfx-monocle:8u60-b27'

}

test {
    useJUnitPlatform()
}

test.dependsOn 'clean'

jfx {
    // minimal requirement for jfxJar-task
    //1mainClass = 'imports.ColorfulCircles'
    mainClass = 'imports.ClickableButtonTest'
    // minimal requirement for jfxNative-task
    vendor = 'lolveley'
}

jar {
    baseName = 'executable3'
    version =  ''
    manifest {
        attributes(
                'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
                //1'Main-Class': 'imports.ColorfulCircles'
                'Main-Class': 'imports.ColorfulCircles'
        )
    }
}
launch4j {
    outfile='bibliotek-v3.exe'
    mainClassName = 'imports.ColorfulCircles'
    icon = "${projectDir}\\icons\\hands2.ico"
    copyConfigurable = project.tasks.fatJar.outputs.files
    jar = "lib/${project.tasks.fatJar.archiveName}"
    //headerType = "console"
    //jar = "${buildDir}\\productFatJar\\fat.jar"
}

junitPlatformTest {
        jvmArgs = [
                "-Djava.awt.headless=true",
                "-Dtestfx.robot=glass",
                "-Dtestfx.headless=true",
                "-Dprism.order=sw",
                "-Dprism.text=t2k",
                "-Dheadless.geometry=1920x1200-32"
        ]
    }

Gradle: Can I build up multiple excludes by calling excludeCategories more than once

I know I can use the following to exclude 1 or more categories from my test run.

One Category

excludeCategories = 'my.test.Category1'

Multiple Categories

excludeCategories = 'my.test.Category1', 'my.test.Category2'

What happens if i specify the excludesCategories multiple times in my build file? Does the latter overwrite the previous?

For example is excludeCategories = 'my.test.Category1' excludeCategories = 'my.test.Category2'

The same as

excludeCategories = 'my.test.Category1', 'my.test.Category2'

Or is the result of the 2 commands that only Category2 is excluded?

Do I have to do += to add the 2nd category to the excluded list? i.e.

excludeCategories = 'my.test.Category1'
excludeCategories += 'my.test.Category2'

Jest - Test if an array is empty or contains a certain object with

I'm quite new to Jest put couldn't find anything online in regards to the following scenario:

I want to test if an array is empty or contains objects of a certain structure. So in pseudo code it could be something like this:

expect([]).toHaveLength(0).or.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })) => true

expect([{foo: 'bar'}]).toHaveLength(0).or.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })) => true

expect([1]).toHaveLength(0).or.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })) => false

Maybe I'm getting it wrong on the how things work in Jest, but to me my problem looks like an or-question.

Thanks for your help

Is a new token generated for the same user on different node on a load balancer with stickiness enabled?

My project (on angularJs) implementation is done in a way that a single webpage application is deployed on a load balancer with 2 nodes, I am not able to figure out a solution for the below problem.

Implementation:

  • Each time a user logs in, a new token is created
  • When the user switches to a different node (by any means), the user will need to login again on that particular node

Here is the scenario: (Note: The same User is logging-in from client1, client2 & client3)

Client1 -> lands and logs-in on node1 -> token1 is created
Client2 -> lands and logs-in on node2 -> token2 is created
    Now suppose node1 goes down (due to some reasons), 
Client3 -> lands on node2 by default -> Now,

Note: Since there is a token already generated on node2 for the user and the session here is active too, so

Questions


  1. Should the user be asked for login again on node2? OR
  2. The user should be able to use the current/active session without login?
  3. Why in either case?

Python like function mock in JavaScript

With Python it's so easy to mock a function that is used in the function under test.

# my_module.py
def function_a():
    return 'a'


def function_b():
    return function_a() + 'b'



# tests/test_my_module.py
from unittest import TestCase
from unittest.mock import patch

from my_module import function_b


class MyModuleTestCase(TestCase):
    @patch('my_module.function_a')
    def test_function_b(self, mock_function_a):
    mock_function_a.return_value = 'c'

    assertEqueal(function_b(), 'cb')

Is something like this possible in JavaScript using, for example, jest?

# myModule.js
function myFunctionA() {
  return 'a';
}

export function myFunctionB() {
  return myFunctionA() + 'b';
}


# __test__/test.myModule.js
import { myFunctionB } from './myModule';

describe('myModule tests', () => {
  test('myFunctionB works', () => {
    // Mock `myFunctionA` return value here somehow. 
    expect(myFunctionB()).toBe('cb')
  });
});

I've read https://github.com/facebook/jest/issues/936 and still have no idea how to do it as there are so many (hacky) suggestions (some of them ~2 years old).

Testing Chart.js Plugin with React and Jest/Enzyme

For my project, I am using React and Jest/Enzyme. I built out a reusable Doughnut Chart component and used a plugin to render text in the middle of the Doughnut Chart. Here is my code.

export default class DoughnutChart extends React.Component {
    renderDoughnutChart = () => {
        const { labels, datasetsLabel, datasetsData, datasetsBackgroundColor, displayTitle, titleText, displayLabels, doughnutCenterText, doughnutCenterColor, height, width, onClick } = this.props;

        const plugin = {
            beforeDraw: (chart) => {
                if (chart.config.options.elements.center) {
                    //Get ctx from string
                    let ctx = chart.chart.ctx;

                    //Get options from the center object in options
                    let centerConfig = chart.config.options.elements.center;
                    let fontStyle = centerConfig.fontStyle || "Arial";
                    let txt = centerConfig.text;
                    let color = centerConfig.color || "#000";
                    let sidePadding = centerConfig.sidePadding || 20;
                    let sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2);
                    //Start with a base font of 30px
                    ctx.font = "30px " + fontStyle;

                    //Get the width of the string and also the width of the element minus 10 to give it 5px side padding
                    let stringWidth = ctx.measureText(txt).width;
                    let elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

                    // Find out how much the font can grow in width.
                    let widthRatio = elementWidth / stringWidth;
                    let newFontSize = Math.floor(30 * widthRatio);
                    let elementHeight = (chart.innerRadius * 2);

                    // Pick a new font size so it will not be larger than the height of label.
                    let fontSizeToUse = Math.min(newFontSize, elementHeight);

                    //Set font settings to draw it correctly.
                    ctx.textAlign = "center";
                    ctx.textBaseline = "middle";
                    let centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
                    let centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
                    ctx.font = fontSizeToUse + "px " + fontStyle;
                    ctx.fillStyle = color;

                    //Draw text in center
                    ctx.fillText(txt, centerX, centerY);
                }
            }
        };

        const data = {
            labels: labels,
            datasets: [{
                label: datasetsLabel,
                data: datasetsData,
                backgroundColor: datasetsBackgroundColor,
            }],
            config: {
                animation: {
                    animateRotate: true,
                }
            }
        };

        const options = {
            maintainAspectRatio: false,
            responsive: true,
            title: {
                display: displayTitle,
                text: titleText,
                fontSize: 24,
            },
            legend: {
                display: displayLabels,
            },
            elements: {
                center: {
                    text: doughnutCenterText,
                    color: doughnutCenterColor,
                    fontStyle: "Arial",
                    sidePadding: 40,
                }
            },
            animation: {
                animateRotate: true,
            },
            onClick: onClick,
        };

        if (!labels || !datasetsLabel || !datasetsData || !titleText) {
            return null;
        }

        Chart.pluginService.register(plugin);

        return (
            <Doughnut
                data={data}
                options={options}
                height={height}
                width={width}
            />
        );
    }

    render() {
        return (
            this.renderDoughnutChart()
        );
    }
}

This code displays the chart and the text in the middle perfectly for me. My problem is when I try to write tests for this component, it says the lines for the plugin isn't covered. I have a basic test here that tests the component renders itself and its props.

it("should render based on passed in props", () => {
    let testOnClick = jest.fn();
    let labels = ["Red", "Yellow", "Blue"];
    let datasetsLabel = "test data sets label";
    let datasetsData = [10, 20, 30];
    let datasetsBackgroundColor = ["red", "yellow", "blue"];
    let titleText = "Title";
    let height = 300;
    let width = 300;
    let doughnutCenterText = "Hello";
    let doughnutCenterColor = "white";

    let wrapper = shallow(
        <DoughnutChart
            labels={labels}
            datasetsLabel={datasetsLabel}
            datasetsData={datasetsData}
            datasetsBackgroundColor={datasetsBackgroundColor}
            titleText={titleText}
            height={height}
            width={width}
            onClick={testOnClick}
            doughnutCenterText={doughnutCenterText}
            doughnutCenterColor={doughnutCenterColor}
        />
    );

    expect(wrapper.find("Doughnut").props().data.labels).toEqual(labels);
    expect(wrapper.find("Doughnut").props().data.datasets[0].label).toEqual(datasetsLabel);
    expect(wrapper.find("Doughnut").props().data.datasets[0].data).toEqual(datasetsData);
    expect(wrapper.find("Doughnut").props().data.datasets[0].backgroundColor).toEqual(datasetsBackgroundColor);
    expect(wrapper.find("Doughnut").props().options.title.text).toEqual(titleText);
    expect(wrapper.find("Doughnut").props().height).toEqual(height);
    expect(wrapper.find("Doughnut").props().width).toEqual(width);
    expect(wrapper.find("Doughnut").props().options.elements.center.text).toEqual(doughnutCenterText);
    expect(wrapper.find("Doughnut").props().options.elements.center.color).toEqual(doughnutCenterColor);
});

I'm guessing the plugin applies all the configuration changes when the chart is drawn, so I don't understand why the tests do not hit the plugin lines.

If anyone can show me how to test the plugin or guide me in the right direction, I would greatly appreciate it! Thank you!

Can you create a distinct Hibernate in-memory database for each thread (for testing)?

I've been implementing Hibernate and JPA interfaces for testing backed by a map of maps. This data structure makes a really simple "database":

// All my database classes implement this (Kotlin) interface.
// "Idd" means "having an ID" as in "ID'd"
interface Idd {
    val id: Long
}

// This simple data structure works as an in-memory database.
//
// The Class is the name of the mapped entity class (which extends Idd)
//
// The inner map uses the ID as the key and the actual objects as
// the value.
//
// ID's are assigned by looking up the Class in the outer map
// and adding one to the size of the inner map (in a synchronized block).
map: SortedMap<Class<Idd>,
               MutableMap<Long, Idd>>

I wrap Hibernate's EntityManager so that a test can pass it a new map instead of connecting to a real database. I pass it a separate map for each test and have the test set up whatever data it needs so that tests running simultaneously in different threads are completely separate from each other.

This works great (it was kind of a breakthrough for my testing), but the relevant Hibernate/JPA classes have a lot of methods and change quite a bit between versions of Hibernate.

I've heard that Hibernate ships with an in-memory database. Can this be used with a separate database per thread for testing? An example would be great!

P.S. I use a Sorted/Tree-Map because I can print it out in a reliable order for debugging.

How to run filters on dotnet tests

I have a build in VSTS, as follows:

enter image description here

You can see from the screen shot there's a test step to "Test and generate code coverage". It uses this command:

/p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=$(Build.SourcesDirectory)\TestResults\Coverage\coverage

Which allows the code coverage report to be generated. I have added "Categories" to my xUnit tests with my defined Trait (such as integration or unit), to allow me to filter tests during build/release. Example would be:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Xunit.Abstractions;
    using Xunit.Sdk;

    /// <summary>
    /// Decorates a test as a Unit Test, so that it runs in Continuous Integration builds.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class IsUnitAttribute : AICategoryAttribute
    {
        /// <summary>
        /// Initializes a new instance of <see cref="IsUnitAttribute"/>
        /// </summary>
        public IsUnitAttribute() : base("Unit") { }
    }

    /// <summary>
    /// Decorates a test as an Integration Test, so that it runs in Continuous Integration builds.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class IsIntegrationAttribute : AICategoryAttribute
    {
        /// <summary>
        /// Initializes a new instance of <see cref="IsIntegrationAttribute"/>
        /// </summary>
        public IsIntegrationAttribute() : base("Integration") { }
    }

I only know how to apply a filter in VS-Test step, as follows:

But not when I'm testing using dotnet:

enter image description here

I only know how to build code coverage using dotnet (and not VS-Test)… I want to do both! How do I:

a) Add the commands to the VS-Test to generate the code coverage, the same as I do for dotnet using the command above.

OR

b) Apply the filter to the dotnet Test step?

Any pointers much appreciated!