lundi 31 décembre 2018

Rails factories having multiple associations to same object

I have a model which have associations like this:-

 class Order < ApplicationRecord
  belongs_to :customer, inverse_of: :orders
  belongs_to :user, inverse_of: :orders
  belongs_to :shipping_address, class_name: "Customer::Address", inverse_of: :shipped_orders
  belongs_to :billing_address, class_name: "Customer::Address", inverse_of: :billed_orders
end

Also, customer_address have a field customer_id. My factory is like this:-

FactoryGirl.define do
  factory :order do 
    customer
    user
    association :shipping_address, factory: :customer_address, customer_id: customer.id 
    association :billing_address, factory: :customer_address, customer_id: customer.id
  end
end

But I am not able to access customer.id. I am getting this error:-

undefined method `id' for #<FactoryGirl::Declaration::Implicit:0x007fa3e6979d70>

How can I pass customer.id to shipping_address and billing_address association?

What is on the New Jersey STEM exam for high school? What kind of things should I be studying to prepare?

!!!Even if you don’t live in NJ I could still use your help if you have taken this test!!! I am going to be taking this exam in a few months but I have no idea what's going to be on it so I don't know what to study. Has anybody that lives in New Jersey know what is on it? It’s the STEM exam for 8th graders to take before high school.

Is it possible to test meteor packages with npm peer dependencies?

I have an Atmosphere package that depends on meteor-accounts-t9n, an npm package. The guide recommends that peer dependencies be used, if possible, and to do a runtime check for the dependency using tmeasday:check-npm-versions.

That works great for my main application, but when I try to run the tests on my package the dependency is not found:

Uncaught Error: Cannot find module 'meteor-accounts-t9n'
at makeMissingError (modules-runtime.js?hash=b819d45cbf32aff410d740fac0364cb4088cd3f2:232)
at Module.require (modules-runtime.js?hash=b819d45cbf32aff410d740fac0364cb4088cd3f2:251)
at Module.moduleLink [as link] (modules.js?hash=655bc49ceeeeb29fd8970000aeef404082790b9b:302)
at at_error.js (at_error.js:1)
....

Is there a way to specify an npm peer dependency in package.js, its onTest() function, or somewhere else in the package?

Mockito - a test makes another one fail

If I run each test individually, they will pass. If I run them together, only the first one passes (onGetAmountSuccess). The other ones show the error Message: Wanted but not invoked: view.showErrorMessage();

I have already tried to use Mockito.reset but it did not work.

 class Test {

private  var myRepository: MyRepository = mock()
private  var view : MyContract.View = mock()
private  var presenter : Presenter =  MyPresenter(myRepository)

@Before
fun setup() {
    RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
    presenter.attach(view)
}


@Test
fun onGetAmountSuccess(){
    doAnswer { Single.just(Currency("EUR", "12/31/2018", arrayListOf()))}.whenever(myRepository).getRates()
    presenter.getRates()
    verify(view, times(1)).updateAmount(arrayListOf)
}

@Test
fun onGetAmountFailure(){
    doAnswer { Single.error<Currency>(Exception("Error"))}.whenever(myRepository).getRates()
    presenter.getRates()
    verify(view, times(1)).showErrorMessage()
}

@Test
fun onUpdateAmountFailure(){
    doAnswer { Single.error<Currency>(Exception("Error"))}.whenever(myRepository).updateAmount("USD", 100.toBigDecimal())
    presenter.updateAmount("USD", 100.toBigDecimal())
    verify(view, times(1)).showErrorMessage()

}

}

Presenter:

 override fun updateAmount(base : String, amount: BigDecimal) {
    myRepository.
        updateAmount(base,  amount)
        .compose(applySingleSchedulers())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe (
            {currency ->
                view?.updateAmount(amount)

            },
            {
                view?.showErrorMessage()
            }
        ).apply {
            disposables.add(this)
        }
}


   override fun getRates() {
    myRepository.getRates()
        .compose(applySingleSchedulers())
        .observeOn(AndroidSchedulers.mainThread())
         .repeatWhen{ done -> done.delay(1, TimeUnit.SECONDS) }
        .subscribe (
            {currency ->
                view?.updateAmount(amount)

            },
    {
        view?.showErrorMessage()
    }
    ).apply {
            disposables.add(this)
        }
}

I have also tried to use mockito reset, but it did not work:

@After
fun reset(){
    Mockito.reset(view)
    Mockito.reset(myRepository)
    presenter = MyPresenter(myRepository)
    presenter.attach(view)

}

I am using the following lib:

com.nhaarman.mockitokotlin2:mockito-kotlin:2.0.0

Does any one know what I am doing wrong and how to fix it? Thanks!!

Are there any tools to simulate the logs for load testing an API endpoint?

I have a product up with almost 20 API endpoints and have real-time logs for them. I would like to replay these logs with commands customized to different formats available in the logs. I am not looking into much statistics at this point. My priorities are towards as little time delay as possible and freedom in structuring the commands using regex or other such tools.

How to run/terminate shell command when starting/finishing iOS tests?

I am trying to write an integration test for my iOS app & our API server. Both are in the same repo, so this test would prevent merging any changes that would break their ability to communicate.

The server team has created a bash script that I need to call to start a local copy of the API server. That script will run until it is terminated. How can I run that script when I run my iOS integration test? I can't put it as part of the build phase as the build will wait for it to terminate before it lets the build finish. I can't use Process directly in my tests to launch the script because that's only available on the Mac, not to iOS targets. Refactoring all my networking & model code to it's own framework that supports iOS & Mac targets would work, but that's a sizable refactor to do. Are there any other ways to run commands along with tests? I'm just using XCTest for all my tests.

Develop a test automation framework from scratch using python

How to start developing sanity test automation framework from scratch using python and how to integrate the framework with test execution engine for regression environment(where we can create a test set and job profiles through UI)?

Before starting development what and all things should be taken care? [What and all python modules may be needed and optimized way to develop]

My idea here is, through Execution engine UI ppl should be able to create a testset and job profiles for regression runs and after gave run the control should go to framework for running the tests and produce the output logs in some dirs and i want to achieve parallelism while executing the test cases.

How to extract an ID from JSON response and use it as path variable in another HTTP requests in JMeter

I have a requirement where I will run a search API which will return me a list of object, each with unique 'facilityID'. I need to create a list of them and use them in another HTTP Delete Request. I have to pass the values as path variable and there are multiple simultaneous threads.

Example: Search API return following IDs: [18c2, 77v3, 45f1]

Now in my Delete HTTP Request, different threads should fetch an Id from the list and bind it to the path variable of the URL.

I read about JSON extractor and am using following expression in Search API,

$.result[*].facilityId

This should return me the list, but how do I make sure that each thread should pick one value from it and hit the API?

best way to do React testing

I have a react project using typescript and i looking for the best way to test my components and the flow (on click button, right rendering etc..). i already tried mocha, enzyme and chai and i had a lots of problems with it.

if someone have another recommend i would like to hear about it.

thanks!

How to perform component level automation testing android and ios app?

I am using Appium to write the automation script. I am able perform the test using automation appium but i have no idea how component level automated test is performed for android/iOS app. Is it possible to use appium to test at component level. Any advice and suggestions will be greatly appreciated

Send keys for 2 fields using tab option in one command line

I'm trying to automate a web page that requires to enter credentials to navigate to the page, so when enter the URL, a windows security window appear to enter user name and password then click on ok. I've tried the following code to enter the credentials, but is fills the value "username\tPassword" in the user name only without tab to the next field to enter the password (I'm using \t to switch to the password field) how can I solve this problem?

public static void main(String[] args) {

System.setProperty("webdriver.ie.driver", "C:\Users\demah\Desktop\Selenium\IEDriver\IEDriverServer.exe");

    WebDriver driver= new InternetExplorerDriver();
    driver.get("URL");
    driver.findElement(By.id("overridelink")).click();

    Alert obj = driver.switchTo().alert(); 
    obj.sendKeys("username\tPassword");
    obj.accept(); 

dimanche 30 décembre 2018

Simplest way to build a Java project with JUnit tests in it? (after being sent only src folder)

I have a Java project with src directory containing main and test (JUnit testing). I used Gradle within Intellij IDEA in development to build it, but now I have to send someone else only the src file and clear instructions how to build it and run the tests from their side.

I moved the src into a new project and I can get Gradle to work from the command line, but when I open it in Intellij it's a mess and it can't resolve anything in the test folder.

What is the simplest build tool to use on the src folder that will allow them to run it both from the command line and to open and build in in the IDE of their choosing?

Thank you!

Component test for ContentChildren with directive not working

I have a modal component also using the bootstrap. Among the features, I have a @ContentChildren for the CloseModalDirective directive that makes any element be responsible for closing modal when clicked. The problem is that I can not test this functionality.

The component works perfectly in the application, my problem is only with the test

This is my component:

import {
    AfterContentInit,
    Component,
    ContentChildren,
    Directive,
    ElementRef, EventEmitter,
    Input,
    OnDestroy,
    Output,
    QueryList,
    ViewChild
} from '@angular/core';

import $ from 'jquery';
import ModalSizes from './modal-size.enum';

@Directive({ selector: '[appCloseModal]' })
export class CloseModalDirective {}

@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements AfterContentInit, OnDestroy {

    @Input() header: string;

    @Input() size = ModalSizes.Medium;

    @Input() closeable = true;

    @Output() openFinished = new EventEmitter();

    @Output() closeFinished = new EventEmitter();

    @ViewChild('modal') modal: ElementRef;

    // FINDING MY ELEMENTS        
    @ContentChildren(CloseModalDirective, { descendants: true, read: ElementRef })
    closeButtons: QueryList<ElementRef> = new QueryList();

    show() {
        $(this.modal.nativeElement).modal({
          backdrop: this.closeable ? true : 'static',
          keyboard: this.closeable,
          show: true
        });
    }

    hide() {
        $(this.modal.nativeElement).modal('hide');
    }

    ngAfterContentInit() {
        $(this.modal.nativeElement).on('shown.bs.modal', () => {
          this.openFinished.emit();
        });

        $(this.modal.nativeElement).on('hide.bs.modal', () => {
          this.closeFinished.emit();
        });

        // ADDING HIDE EVENT
        this.closeButtons.forEach(button => {
          button.nativeElement.addEventListener('click', this.hide.bind(this), false);
        });
    }

    ngOnDestroy() {
        $(this.modal.nativeElement).off('shown.bs.modal');
        $(this.modal.nativeElement).off('hide.bs.modal');

        this.closeButtons.forEach(button => {
          button.nativeElement.removeEventListener('click', this.hide.bind(this));
        });

        $(this.modal.nativeElement).modal('dispose');
    }

}

This is my tests:

import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';

import {CloseModalDirective, ModalComponent} from './modal.component';

import {Component} from '@angular/core';
import ModalSize from './modal-size.enum';
import 'bootstrap';

@Component({
    selector: 'app-test',
    template: `
        <app-modal header="Title">
          <div class="content">Content</div>
          <button appCloseModal footer>Close</button>
        </app-modal>
    `
})
class TestComponent {}

describe('ModalComponent', () => {
    let component: ModalComponent;
    let fixture: ComponentFixture<ModalComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
        declarations: [ CloseModalDirective, ModalComponent, TestComponent ],
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ModalComponent);
        component = fixture.componentInstance;
        component.header = 'Titulo';
        component.size = ModalSize.Small;
        component.closeable = true;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should display title and size', () => {
        const title = fixture.nativeElement.querySelector('.modal-title');
        expect(title.textContent).toBe(component.header);

        const classes = fixture.nativeElement.querySelector('.modal-dialog').classList;
        expect(classes).toContain(component.size);
    });

    it('should show the modal on call show method', fakeAsync(() => {
        component.show();

        tick(1000);

        const modal = fixture.nativeElement.querySelector('.modal');
        expect(modal.classList).toContain('show');

        component.hide();
        tick(1000);
    }));

    // NOT WORKING!
    it('should hide modal on click elements with appCloseModal directive', () => {
        spyOn(component, 'hide');

        const testFixture: ComponentFixture<TestComponent> = TestBed.createComponent(TestComponent);
        const element = testFixture.nativeElement.querySelector('[appCloseModal]');
        element.click();

        expect(component.hide).toHaveBeenCalled();
    });
});

What did I do wrong?

samedi 29 décembre 2018

How to debug regression test binary pg_regress in postgreSQL?

I tried to debug pg_regress in postgreSQL using lldb on mac. However, when I run pg_regress using lldb, the test failed and reported: "failed to wait for subprocesses: Interrupted system call"

I customized a test schedule file which only has one test SQL. When I execute make check, the regression test passed.

Below is the output when debugging with lldb through Clion:

============== removing existing temp instance        ==============
============== creating temporary instance            ==============
============== initializing database system           ==============
============== starting postmaster                    ==============
running on port 60848 with PID 16262
============== creating database "regression"         ==============
CREATE DATABASE
ALTER DATABASE
============== running regression test queries        ==============
test some_test               ... failed to wait for subprocesses: Interrupted system call

Process finished with exit code 2

Expected result should be

============== removing existing temp instance        ==============
============== creating temporary instance            ==============
============== initializing database system           ==============
============== starting postmaster                    ==============
running on port 60848 with PID 16262
============== creating database "regression"         ==============
CREATE DATABASE
ALTER DATABASE
============== running regression test queries        ==============
test some_test               ... ok

Chrome Dev tools device with keyboard is not showing

When in chrome dev tools, I can't seem to have an option to select the device with keyboard. When clicking on "rotate" button in chrome tools, it just rotates the device-mode (landscape, vertical). However, it seems that it has to give an option to select whether the device will have virtual keyboard or not.

How to write a JUnit test in Java, that checks one particular print that depends on a userinput in a loop

I try to write JUnit tests in IntelliJ for an application, that modifies a String. Now how can I test one particular print on the console?

Let's assume the start-string is stored in args[0] as "Hello World" and we have a method that can change a single letter in the string. The string will be printed out after the execution of the method.

public class modifyString {
    public static void main(String[] args) {

          Scanner scanner = new Scanner(System.in);

          while(true) {
              // Print the string
              System.out.println(args[0]);

              // Wait for a userinput that only contains two chars,
              // e.g. '0h' <- 'Change the index 0 to 'h''
              // (the order of the chars is unimportant)
              String input = scanner.nextLine();

              if(preconditionFullfilled(input)) {
                  executeOperation(input, args);
              }
         }
    }
}

For example: The expected output for the input '0h' with a 'Hello World' string in args[0] should be 'hello World'.

How do I write a JUnit test to test this particular result?

Test Runner tab in IntelliJ 2018.3 CE not showing

I'm using IntelliJ 2018.3 CE. I have a java maven project (developed using springboot) in which the JUnit tests have already been written. However, when I try to run the tests, the output is always shown in the default run window, and NOT in the Test Runner Tab. In fact, I cannot make this window pop-up after a running a test.

I have Junit 4.12 in the external libraries of my project (as Maven: junit:junit:4.12). The test folders have been appropriately flagged as test resources.

I presume it has to deal with settings in IntelliJ but even with all the effort in the world, I wasn't able to find what is causing this.

Is someone experiencing the same issue? Or does someone know how to resolve this?

Any help would be very much appreciated.

How test IP from JavaScript?

how are you all here in the community?

I have a problem and I need your help or guidance.

In the windows command console when you put: ping "example" -t

We know that a constant reading of what is being tested is executed.

I basically want to know if there is a way to do the same but from javascript.

My idea is to make a software that tells me when an ip is left without connection, or when the ips are in connection I indicate a status of "Online" or "Active"

This I want this application to run on NodeJS

I'm looking for information. but I have not been lucky.

regards

goapp test not working,getting error "GOPATH must be absolute" while it is absolute

I'm tying to write tests for my google cloud app. I read the documents and it seems the only way to run the test locally is the running the command goapp test in the test package directory. But when I run the command I get the error go: GOPATH entry is relative; must be absolute path: "".

I'm pretty sure my GOPATH is set absolutely. Here are the results when I run the command go env | grep GOPATH:

GOPATH=":/home/mohammad/go:/home/mohammad/go/src/gitlab.com/gc-auth"

Also getting the same output when I run echo $GOPATH.

Any help is appreciated.

PS: I have ubuntu 18.04 and my go version is 1.10.4

results of gcloud version:

Google Cloud SDK 228.0.0 app-engine-go app-engine-python 1.9.80 bq 2.0.39 cloud-datastore-emulator 2.0.2 core 2018.12.07 gsutil 4.34

vendredi 28 décembre 2018

Check thousands of website working status

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

Mocha says test suceeded but it threw an exception

I am running some unit tests with mocha. One of my methods called in the unit tests throws an exception. As such, I would like that the test is reported to have failed. However, mocha logs the exception and says the test has succeeded.

import * as mocha from 'mocha';

mocha.describe('Tests Disassembler', () => {

it('simple test', () => {
    throw new Error("failed");

});

});

Is there any way of telling mocha the test should be reported as failed if there is an uncaught exception?

Mock navigation service in jest

I'm using react-navigation and calling that service in my code. Although I'm not sure how to mock the navigate function. Here is my code:

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

Here is what I got so far:

export const loginEpic = (action$, state$, { ajax, navigate }) =>
  action$.pipe(
    ofType(LOGIN_REQUEST),
    map(() => state$.value),
    switchMap((options) =>
      ajax(options).pipe(
        pluck("response"),
        map((res) => loginSuccess(res)),
        tap((r) => navigate(ROUTES.DASHBOARD_SCREEN))
      )
    )
  );

navigate is navigationService.navigate and I'm passing it from the dependencies of redux-observables.

The test looks like this:

const dependencies = {
      ajax: ({ }) => of(mockedResponseFromAjax),
      navigate: () => // ??? 
    };
    const result$ = loginEpic(action$, state$, dependencies).pipe(toArray());

C# Performance benchmark

To keep track of performance in our software we measure the duration of calls we are interested in.

for example:

using(var performanceTrack = new PerformanceTracker("pt-1"))
{
    // do some stuff

    CallAnotherMethod();

    using(var anotherPerformanceTrack = new PerformanceTracker("pt-1a"))
    {
       // do stuff

       // .. do something
    }

    using(var anotherPerformanceTrackb = new PerformanceTracker("pt-1b"))
    {
       // do stuff

       // .. do something
    }
    // do more stuff
}

This will result in something like:

pt-1  [----------------------------] 28ms

      [--]                            2ms from another method

pt-1a   [-----------]                11ms

pt-1b                [-------------] 13ms

In the constructor of PerformanceTracker I start a stopwatch. (As far as I know it's the most reliable way to measure a duration.) In the dispose method I stop the stopwatch and save the results to application insights.

I have noticed a lot of fluctation between the results. To solve this I've already done the following:

  • Run in release built, outside of visual studio.
  • Warm up call first, not included in to the statistics.
  • Before every call (total 75 calls) I call the garbage collector.

After this the fluctation is less, but still not very accurate. For example I have run my test set twice. Both times

See here the results in milliseconds.

Avg: 782.946666666667 981.68
Min: 489 vs 513
Max: 2600 vs 4875
stdev: 305.854933523003 vs 652.343471128764
sampleSize: 75 vs 75

Why is the performance measurement with the stopwatch still giving a lot of variation in the results? I found on SO (https://stackoverflow.com/a/16157458/1408786) that I should maybe add the following to my code:

//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;

//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;

But the problem is, we have a lot of async code. How can I get a reliable performance track in the code? My aim is to discover performance degradation when for example after a check in a method is 10ms slower than before...

When testing time-dependent code in Python, how can I "speed up time" without skipping seconds?

Background

I'm currently working on a project for a company where they're trying to create software for managing those TV-screen-sized dynamic video ads that you see in malls.

As part of testing the software, I've learned how to use the freezegun package to run a test where the time is frozen at a particular value. I also see that it has an option to tick the time forward in chunks of seconds:

tick argument

FreezeGun has an additional tick argument which will restart time at the given value, but then time will keep ticking. This is alternative to the default parameters which will keep time stopped.

auto_tick_seconds argument

FreezeGun has an additional auto_tick_seconds argument which will autoincrement the value every time by the given amount from the start value. This is alternative to the default parameters which will keep time stopped. Note that given auto_tick_seconds the tick parameter will be ignored.


Problem

The problem with the above solution is that in order to test a full day of the billboard-management software I'm working on, I need both to dramatically speed up the rate of time and also keep the granularity of minutes and seconds, as there are some functions that need to execute seconds or minutes before other functions run.

How can I speed up time without just skipping time?

How to test a function which returns something and has side effect?

I have a function which returns something but has a side effect at the same time. Should I test only value which this function returns or I need to test result of a side effect too?

@slack_interactions.on('admin_add')
def handle_admin_add(payload):
    team_id = payload['team']['id']
    user_id = payload['user']['id']
    action_value = payload['actions'][0]['selected_options'][0]['value']

    user = SlackUser.objects.find_by_ids(team_id, action_value)

    if user and not user.is_bot:
        user.make_admin()

    return build_admins_message(team_id, user_id)

How to extract token from response and pass it to next api-requests in SOAPUI

I try testing web-service with SOAPUI. I face with problem that i don`t know how to pass access token from the first response to second request. I have 8 requests and want to run them together.But but after my first request(Remote Login) I get the access token for user and i need using it in next requests. I have to do it manually. Could you help me, how i can get token from the first request and pass it to next requests automatically.In this case, all the case must be started by pressing 1 button.

"dotnet test": how to run xunit tests projects in parallel?

I am runnning all tests projects from solution level with a single command: dotnet test how can I make all tests projects(assemblies) run in parallel?

In Visual Studio there is a simple button "Run tests in parallel" which works perfectly but I need to use dotnet core test command for CI.

jeudi 27 décembre 2018

Scroll and Width in JSDOM not implemented due to no layout in jsdom?

I am trying to write a test case for a component which checks if a function bound to a component is called if scroll is triggered on window object.This is not using react framework although I am using JEST as my testing framework which uses JSDOM since it is very good and fast.

The first problem is the scroll is not getting triggered at all. Read about it in a lot of github issues but had no luck.

The second problem is that I have set a width to one of the elements to 1000 px which is a sandbox element in jsdom using jest. But when I add another element below it which is the result of the rendered component the DOMElement function of getClientBoundingRect still returns all zeros.

tried a couple of things which did not work:

  1. global.document.dispatch(new Event('scroll')) [this was done after adjusting the scroll position]

  2. After rendering my component which has around 19 li elements in it [each li element has a 10px x 10px image and a title], I am trying to check the height of my component to scroll to that position, but unluckily everything is coming to 0.

Is there any other way to test or cover a function which is called on window.scroll using jsdom/jest, I dont want to use phantomjs.

Snapshot testing with react-spring/react-motion

I am trying to snapshot test my React components with Jest and Enzyme. Some components have the animation component (imported from react-spring/react-motion) in them, which renders a function as its child. This makes testing incredibly hard. I did quite a bit of research and came up with 3 ideas:

  • Use Enzyme's mount to render everything, and snapshot test it. I found it impossible/ineffective for expensive components, and the snapshots produced are often really heavy (1MB - 2MB).
  • Use Enzyme's shallow and snapshot test the component. Then find the animation component, render the children inside it using Enzyme's renderProp() and snapshot test them. This worked great until I found that renderProp() doesn't work nicely with <StaggeredMotion /> for react-motion and react-spring. A workaround for this issue is explicitly call the function as .prop('children')(), then shallow the whole thing, but the code will then look messy and tough to read.
  • Just use Enzyme's shallow and snapshot test the component. The rest are on the library's side.

The question is: Which one should I use? If none of these are good enough, what are the alternatives? Thanks in advance.

(If you need a code sample, I am more than happy to provide)

Cloud machines available for free docker test

Can you please advise some cloud machines available for free docker tests in learning purposes?

Can't download docx files using selenium headless chrome

I am doing an automation E2E and trying to download files for a Drop-down working perfectly using chromedriver not headless mode , but when giving chrome options as headless the file is not downloaded .

The Drop-down when you click on the file it opens an external link and then downloads the file and go back again to the main screen , i have to open the file and check the data inside it , but unfortunately it's not download

and this is the code of my Webdriver manager

                String downloadFolder = System.getProperty("user.dir") +      "/exportedFiles";
                HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
                chromePrefs.put("plugins.always_open_pdf_externally", true);
                chromePrefs.put("download.default_directory", downloadFolder);
                chromePrefs.put("browser.setDownloadBehavior", "allow");
                chromePrefs.put("download.prompt_for_download", "false");
                ChromeOptions options = new ChromeOptions();
                options.addArguments("headless");
                options.addArguments("--test-type");
                options.addArguments("--disable-extensions");
                options.setExperimentalOption("prefs", chromePrefs);
                driver = new ChromeDriver(options);

How to do UI test with airbnb epoxy?

Currently I'm working in a project that's using epoxy and I'm having a hard time thinking on how could I create UI/integration tests with it. At Epoxy github's repository I've only got a hint about testing the RecyclerView but I don't think this is the best way.

Could you give me any tips?

Thanks :)

Remote software deployment solution ( no gpo)

I was wondering if you could help me. I'm writing my bachelor project on topic remote deployment of software. It has this condition that is has to be non GPO ( active directory) solution. I will be testing it on few computers in school so free , limited software should do its work. Some recommendations? So far i tested EMCO remote installer but had some issues and can not connect to the remote pc. But more important thing is if someone know some publications or books or trusted articles about this topic because I signed in to our national library which gave me access to other libraries but cant find solid source. i will be much thankful if someone could give me some answers or directions where to look, I'm so desperate.. Thank you in advance

How to add Karma Init to project file

Hi I'm absolutely new to testing and I have no idea how to add karma to your projects using command line. I actually have no idea how to access my projects using command line and then add Karma test runner to it to test the code. Can someone please help me out ? Thanks

groovy and junti tests in one project

I have spring boot project with groovy tests and I need to add java junit tests. I am using maven gmaven plugin to run groovy tests. After adding java junit tests still only groovy tests are running during build. How can I run all tests (groovy and java junit ) ? I tried to add maven surefire plugin and it's still the same.

Protractor / Selenium XHR stays in status "pending"

I'm using protractor with selenium to test my Angular page. At some random points, it justs stops the execution because an XHR-Request is still "pending" (in Chrome Dev Tools). When I copy the request URL (it is a simple GET request) and open it in a new tab, it immediately returns the data (JSON, ~200 chars long).

The request stays "pending" when executing the E2E tests, and out of 10 times the said GET-URL gets called it fails maybe 1 time.

Selenium prints the following error: "Timed out receiving message from renderer: 298.388".

Any idas?

Unecpected token { in Jest testing

I'm starting to learn Jest testing framework, and trying to do simple test by using npm test, but I have this error:

enter image description here

I am trying ot change import to require, but it's not help :( any suggestions about how can I handle this error?

Also here is my package.json file part, that related to devDependencies and jest: { "devDependencies": { "babel-core": "^6.26.3", "babel-preset-env": "^1.6.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "jest": "^22.4.3", "parcel-bundler": "^1.11.0" }, "jest": { "verbose": true, "testURL": "http://localhost:1234/" } }

Pact for PHP - 404 response code from mock server

I've tried to configure Pact for PHP using example configuration. My problem is I can run a mockServer, but every request I make returns 404 response. Of course I set everything up like in a GitHub readme. Still, I know server is visible (localhost config) but routes could not be registered.

Code example:

class PactTest extends \Tests\BaseTestCases\V2TestCase {

/** @var MockServerConfig */
private $config;

public function setUp()
{
    // Create your basic configuration. The host and port will need to match
    // whatever your Http Service will be using to access the providers data.
    $this->config = new MockServerConfig();
    $this->config->setHost('localhost');
    $this->config->setPort(7200);
    $this->config->setConsumer('someConsumer');
    $this->config->setProvider('someProvider');
    $this->config->setHealthCheckTimeout(60);
    $this->config->setCors(true);

    // Instantiate the mock server object with the config. This can be any
    // instance of MockServerConfigInterface.
    $server = new MockServer($this->config);

    // Create the process.
    $server->start();

    // Stop the process.
    $server->stop();
}

public function testSimple()
{
    $matcher = new Matcher();

    // Create your expected request from the consumer.
    $request = new ConsumerRequest();
    $request
        ->setMethod('GET')
        ->setPath('/test/abc')
        ->addHeader('Content-Type', 'application/json');

    // Create your expected response from the provider.
    $response = new ProviderResponse();
    $response
        ->setStatus(200)
        ->addHeader('Content-Type', 'application/json;charset=utf-8')
        ->setBody([
            'message' => $matcher->term('Hello, Bob', '(Hello, )[A-Za-z]')
        ]);

    // Create a configuration that reflects the server that was started. You can
    // create a custom MockServerConfigInterface if needed. This configuration
    // is the same that is used via the PactTestListener and uses environment variables.
    $builder = new InteractionBuilder($this->config);
    $builder
        ->given('a thing exists')
        ->uponReceiving('a get request to /test/abc')
        ->with($request)
        ->willRespondWith($response); // This has to be last. This is what makes an API request to the Mock Server to set the interaction.

    $service = new HttpClientService($this->config->getBaseUri()); // Pass in the URL to the Mock Server.
    $result  = $service->getTestAbc(); // Make the real API request against the Mock Server.

    $builder->verify();

    self::assertEquals('Hello, Bob', $result); // Make your assertions.
}

Where getTestAbc() is:

public function getTestAbc(): string
{
    $uri = $this->baseUri;
    $response = $this->httpClient->get("{$uri->getHost()}/test/abc", [
        'headers' => ['Content-Type' => 'application/json']
    ]);
    $body   = $response->getBody();
    $object = \json_decode($body);

    return $object->message;
}

What do I do wrong?

Why Spring @Service methods appear with 0% code coverage in JaCoCo?

These libraries are loaded:

  • JUnit 5.3.2
  • JaCoCo 0.8.2
  • Mockito 2.10.0

Only element "static {...}" appears with 100% coverage. All the rest is at 0%:

JaCoCo report

The unit test class has annotations @ExtendWith(SpringExtension.class) and @AutoConfigureMockMvc. The service is injected with @Mock.

doReturn(actual).when(service).get(param);
when(service.get(param)).thenReturn(actual);

expected = service.get(param);
verify(service, times(1)).get(param);

assertEquals(expected, actual);
assertEquals(actual, expected);

My ServiceImpl class is red when I click any method. It extends an abstract class. Jackson's ObjectMapper is red, and also the entire lines within the methods. For example:

public CustomReturnObject get(final CustomParamObject paramObject) {
    try {
        return retryTemplate.execute(status -> {
            String json = repository.get(paramObject);
            CustomReturnObject returnObject = json2CustomObject(json, paramObject);

            if (returnObject == null) {
                returnObject = new CustomReturnObject();
                returnObject.setId(paramObject.getId());
            }

            return returnObject;
        });
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        return null;
    }
}

mercredi 26 décembre 2018

jest fail with id generated of element in library

I am using jest to test my component with snapshot testing. When I check a component with a smaller component ( that componet in a library ), so, it found that two id generated different of each and test fail, I want to know how to fix it. example: My component to test: <Loading><Loading> In Loading component: render(){ } Spinner is a component in "react-spinner-material", so i don't know how its id generated. When i run test, it shows fails:

<div className="spinner" id="spinner_1545879774934" id="spinner_1545884872602"

How to test the phase angle in pandas dataframe, using numpy.testing in Python3?

I have a dataframe

import numpy as np
import pandas as pd

dat1 = {
        'f': [0],
        'abs_1': [1],
        'angle_1': [-np.pi]
       }


dat2 = {
        'f': [0],
        'abs_1': [1],
        'angle_1': [np.pi]
       }

df1 = pd.DataFrame(dat1).set_index('f')
df2 = pd.DataFrame(dat2).set_index('f')

# test using np.testing
np.testing.assert_array_almost_equal(df1, df2)

According to maths, the phase angle has the period of 2*np.pi. This means:

-np.pi = -np.pi + 2*np.pi = np.pi

So df1 and df2 are the same.

Do you know how to make the test pass?

By the way, in my real application, the df1 and df2 can have many more columns, half of them are abs values and the other half are angle values.

How to test aiohttp server?

This is the code I've found in aiohttp docs:

async def test_hello(aiohttp_client):
    app = web.Application()
    app.router.add_get('/', hello)
    client = await aiohttp_client(app)

This uses aiohttp_client pytest fixture. The problem is that it creates a new web.Application(), while my code already have a web.Application(). so Should I import it from the testing modules? Does it mean I need to expose it as a global variable (which I prefer not to)?

My server.py code looks like:

async def init():
    app = web.Application()
    app.add_routes(.. )

loop = asyncio.get_event_loop()
loop.create_task(init())
loop.run_forever()

So my app is not a global variable here.

Second, does it possible, and is it correct, to actually run the server somehow before starting pytest? Because as I see these tests just interact with web.Application() itself, without listening to port and spawning a server process.

Why is a helper object passed around when testing in golang?

I need to test a function

func Sum(a, b int) {
    return a + b
}

func TestSum(t *testing.T) {
    assert.Equal(t, 5, Sum(2,3))
}

Why do I have to provide t as a helper object to assert.Equal()? Couldn't it be implicitly inferred like other languages? (Example Ruby's rspec)

I couldn't find a reference doc/blog/video explaining this, hence asking it here. If someone would be kind to point me to it.

Thanks.

Tests passing locally, but not on TravisCI - Cause is unknown

Cause is unknown, at least to me...

I have a bunch of tests which are working great on my local machine, but wont pass on TravisCI. This is happening on an open source package stored on Github which you can easily check out.

The failed builds can be seen here: https://travis-ci.org/dugajean/pouch/builds/472391121
And the tests can be found here: https://github.com/dugajean/pouch/tree/master/tests

The errors/exceptions thrown on TravisCI simply don't happen locally. What I get locally is:

OK (15 tests, 22 assertions)

I simply can't see what I could be doing wrong. Help would be highly appreciated.

Test IF in Subscribe Karma and Jasmine

How to be inside a subscribe in Karma angular 6 ?

  this.watcher = this.media.subscribe((change: MediaChange) => {
            this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : '';
            this.changeMqAlias = change.mqAlias;
            if (this.changeMqAlias == 'xs' || this.changeMqAlias == 'sm' || this.changeMqAlias == 'xl') {

                
                if (this.id) {
                   this.get(this.id);
                }
            }
        });

How to use Promises in Postman tests?

I need to use some async code in my Postman test.

As it's a complex scenario I've reproduced the scenario in a very simple test with the following code:

let promiseNumber = 0;

function resolvedPromise() {
    return new Promise((resolve, reject) => {
        pm.sendRequest('https://postman-echo.com/get', function (err, res) {
            if (err) {
                console.log(err);
                reject();
            } else {
                console.log(`Resolved promise ${++promiseNumber}`);
                resolve();
            }
        });
    });
}

resolvedPromise()
    .then(resolvedPromise)
    .then(resolvedPromise)
    .catch(err => console.log(err));

The expected result on the console would be:

Resolved promise 1
Resolved promise 2
Resolved promise 3

But instead I receive:

Resolved promise 1

Is there a way to make Promises or async code available at Postman?

How driver.navigate().to() work on selenium in Selenium class? Means what is navigate() and to()?

I am confused with this. Basically when we create an object of a class, then we can access property or method. Up to I am fine. But what when we are creating an object of WebDriver class in Selenium and setting url through driver.navigate().to() . So Why are here two things navigate() and to() after the Selenium object driver.

Cannot run automation test because of project double cloning

everyone. I faced with the following problem and it is very difficult to describe it correctly: 1. My DevOps created a git repository in GitLab 2. I have pushed my testing project to the GitLab repository 3. Then I cloned again the project from the repository (yes, I know that was a fail) After these actions, I cannot run any tests. But other testers can pull and run the tests. I even created a separate folder in another place and pulled a project but it did not resolve the problem. Maybe someone already had a similar issue and can give me advice on what I should do to resolve it. Thanks in advance!

How do i implement testNG features such as @beforesuite, @aftersuite and @dataprovider in automation testing with python-selenium?

We checked several test framework for python, such as NOSE, PYTEST, unittest frameworks. but we didn't find anything which can help us with testNG features, specifically- @beforesuite, @aftersuite and dataprovider

We have also checked Proboscis for python, which is claimed as testNG alternate. But this also doesn't have anything for beforesuite, aftersuite and dataprovider.

Cannot build the Selendroid server APK for application '...'

Hi everyone I'm trying to Run a tester with selendroid to test an app on my device. the selendroid server is running on PORT 4444 and the test script is correct but when I'm trying to run the test script by TestNG these errors shown in Console :

[RemoteTestNG] detected TestNG version 6.14.2 FAILED CONFIGURATION: @BeforeSuite setUp org.openqa.selenium.SessionNotCreatedException: Cannot build the Selendroid server APK for application 'io.selendroid.standalone.android.impl.DefaultAndroidApp@37f09ad0': Error executing shell command: C:\dev\sdk\android-sdk-essential\build-tools\24.0.1\aapt.exe package -M C:\Users\NP\AppData\Local\Temp\io.selendroid.testapp1545829318250\AndroidManifest.xml -I C:\dev\sdk\android-sdk-essential\platforms\android-24\android.jar -F C:\Users\NP\AppData\Local\Temp\io.selendroid.testapp1545829318250\manifest.apk -f Command duration or timeout: 33.59 seconds Build info: version: 'unknown', revision: 'unknown', time: 'unknown' System info: host: 'Shakib', ip: '192.168.73.45', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_144' Driver info: io.selendroid.client.SelendroidDriver at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:247) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) Caused by: io.selendroid.server.common.exceptions.SessionNotCreatedException: Cannot build the Selendroid server APK for application 'io.selendroid.standalone.android.impl.DefaultAndroidApp@37f09ad0': Error executing shell command: C:\dev\sdk\android-sdk-essential\build-tools\24.0.1\aapt.exe package -M C:\Users\NP\AppData\Local\Temp\io.selendroid.testapp1545829318250\AndroidManifest.xml -I C:\dev\sdk\android-sdk-essential\platforms\android-24\android.jar -F C:\Users\NP\AppData\Local\Temp\io.selendroid.testapp1545829318250\manifest.apk -f

I really don't know why the APK is not being installed does anyone know how can I fix this? any help will be much appreciated.

How do I test a ranking system?

Let us assume we have 3 students in a class with the below marks

   <table border='1'>
    <tr><td></td><td>Mathematics</td><td>English</td><td>Science</td></tr>
    <tr><td>John</td><td>60</td><td>40</td><td>70</td></tr>
    <tr><td>Mark</td><td>30</td><td>90</td><td>40</td></tr>
    <tr><td>Alice</td><td>60</td><td>60</td><td>70</td></tr>
    </table>

Normally the rank is decided by adding all three marks and sorting the total in descending order.

Looking at the above table, the rank would be Alice, John, Mark. If there exists a system that takes student marks as input and gives out the rank sequence as response, then how do I certify that the system returns student ranks in sequence for all sorts of possible data?

What should be the approach to test such a system? Generating all possible combinations of data would be exhaustive when the number of students and subjects increase.

How to get what activity is running android studio

I`m trying to check the flow of my program and to do so i need a way to get the type of a class that is currently running.

I tried searching the web for some info about the subject but as i see most of the examples add a static variable for the active data.

Beside testing the logic of my program I want to test the GUI as well so i will be able to check that after I press a button the correct activity is running.

There isn't much info about testing on Android studio so any help will be highly appreciated (Such as "You are in a completely wrong path, you can test your GUI by...")

Thanks

How to verify observed ViewModel LiveData inside my test?

I am currently trying to write a test for my ViewModel class. I already managed to write some tests for its LiveData updates, and verified behaviors.

However when I tried to test a method with chained methods, and see if my linked LiveData updated correctly, there is nothing happening. Test gives error stating that there is no invoke happened during test.

Below is how I tried to test the LiveData object

class WorkViewModelTest : AndroidTest() {
@Mock
private lateinit var sqlQueryUseCase: SqlQueryUseCase
private lateinit var workViewModel: WorkViewModel
val prefs = PreferencesHelper.defaultPrefs(context())
val resourceProvider = ResourceProvider(context())

@Before
fun setup() {
    workViewModel = WorkViewModel(sqlQueryUseCase, prefs, resourceProvider)
    workViewModel.toggleProductListState.observeForever {}
}

@Test
fun `When invalid barcode text given to function, it returns error message`() {
    //given
    val invalidString: String? = null
    val observer = mock<Observer<String>>()
    workViewModel.warningMessage.observeForever(observer)

    //when
    workViewModel.checkProductCode(invalidString)

    //then
    verify(observer).onChanged(resourceProvider.getStringFromResources(R.string.work_screen_empty_product_code_warning))
}

---> This is the test that fails

@Test
fun `When user read a barcode and it is not found on remote with ERP System, we should move our state to error`() {
    //given
    val barcode = "123456789"
    val observer = mock<Observer<String>>()
    workViewModel.warningMessage.observeForever(observer)

    given {
        runBlocking { sqlQueryUseCase.run(any()) }
    }.willReturn(Either.Right(emptyList())

    //when
    runBlocking { workViewModel.checkProductCode(barcode) }
    //then
    verify(observer).onChanged(resourceProvider.getStringFromResources(R.string.work_screen_data_not_found_for_given_barcode_warning))
}

Here is my ViewModel class, which invokes some use cases and fetch data from remote connection:

class WorkViewModel
@Inject constructor(
private val sqlQueryUseCase: SqlQueryUseCase,
private val prefs: SharedPreferences,
private val resourceProvider: ResourceProvider
) : BaseViewModel() {

val productListState: MutableLiveData<Boolean> = MutableLiveData()
val itemList: MutableLiveData<List<ItemDetailModel>> = MutableLiveData()
val warningMessage: MutableLiveData<String> = MutableLiveData()
val productInformation: MutableLiveData<String> = MutableLiveData()

val toggleProductListState = Transformations.map(itemList) {
    if (it.isEmpty()) {
        productListState.postValue(false)
    } else {
        productListState.postValue(true)
    }
}

fun initializeItemList(itemList: List<ItemDetailModel>) {
    this.itemList.postValue(itemList)
}

fun checkProductCode(productCode: String?) {
    if (productCode.isNullOrEmpty()) {
        warningMessage.postValue(resourceProvider.getStringFromResources(R.string.work_screen_empty_product_code_warning))
    } else {
        executeSqlQuery(productCode)
    }
}

private fun executeSqlQuery(productCode: String) {
    sqlQueryUseCase(
        SqlQueryUseCase.Params(
            String.createAuthToken(PreferencesHelper.getAuthorizationToken(prefs)),
            RequestBody.create(
                MediaType.parse("application/json"),
                QueryCreatorFactory.createQueryCreatorFromErpType(
                    prefs,
                    resourceProvider
                ).getProductInformationFromBarcodeQuery(productCode)!!.toByteArray(Charsets.UTF_8)
            )
        )
    ) {
        it.either(::handleErrorState, ::handleQueryResult)
    }
}

private fun handleQueryResult(resultData: List<Any>) {
    if (resultData.isNotEmpty()) {
        productInformation.postValue(resultData[0] as String)
    } else {
        warningMessage.postValue(resourceProvider.getStringFromResources(R.string.work_screen_data_not_found_for_given_barcode_warning))
    }
}

private fun handleErrorState(failure: Failure) {
    if (failure is Failure.ServerError)
        warningMessage.postValue(failure.errorMessage)
    else
        warningMessage.postValue("Some other failure")
}
}

What I am trying to achieve is, whenever user tries to get information about a product with a barcode, which actually does not stored in system, we will get an empty list as a response, and at that case, ViewModel should post a warning message via warningMessage LiveData.

However with the test I wrote, I cannot see in debug mod that "handleQueryResult" function is called at all. I am struggling with that problem, and since I am a bit new with Mockito, I cannot understand what is wrong with my test. Any help is welcomed. Thanks a lot.

mardi 25 décembre 2018

how to make right cycle

for(int i=0;i<=ts.listOfTasks().allTasks().size()-1;i++){
        if(ts.listOfTasks().allNamesForTask().get(i).getAttribute("title").equals(param)){
            ts.listOfTasks().allTasks().get(i).click();
        }
        else {
            TestData.SIZE_OF_TASKS=ts.listOfTasks().allTasks().size();
            js.executeScript("document.getElementsByTagName('td')["+TestData.SIZE_OF_TASKS+"].scrollIntoView()");

        }
}

I want to 1)compare all located elements with String param 2) if there are no same , scroll by js and to campare again

*But it compare only first alement and then scroll , but I want it to compare the first few located elements , and then do js *

I have tryed continue and brake with marks, but maybe do something wrong...

how to get text from alert box in appium?

I wrote the following code but it is showing org.openqa.selenium.WebDriverException: Method has not yet been implemented (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds

AndroidDriver driver = new AndroidDriver(u,dc);

     driver.manage().timeouts().implicitlyWait(100,TimeUnit.SECONDS);

     WebDriverWait wait = new WebDriverWait(driver,30);

     wait.until(ExpectedConditions.alertIsPresent());
     Alert alert = driver.switchTo().alert();
     alert.accept();
     String t = alert.getText();
     System.out.println(t);

using type classes to provide alternative implementations for when using Acid-State

I wrote a web application using scotty and acid state, now i would like to use type classes to be able to provide alternative implementations for the capabilities of my application for testing. I get the general idea of it and am able to apply it so simple examples but since im am using acid state there are a lot of type classes and template haskell involved which i am not entirely comfortable with yet.

so i have these straight-forward classes for the different capabilities

class Logging m where
  log :: T.Text -> m ()

class Server m where
  body :: m B.ByteString
  respond :: T.Text -> m ()
  setHeader :: T.Text -> T.Text -> m ()

class Db m where
  dbQuery :: (MethodState event ~ Database,QueryEvent event) => event -> m (EventResult event)
  dbUpdate :: (MethodState event ~ Database,UpdateEvent event) => event -> m (EventResult event)

and i also provided instances for them for my "production" monad.

But when it comes to the database capability i cant get to work what i want.

the class looks like this

class Db m where
  dbQuery :: (MethodState event ~ Database,QueryEvent event) => event -> m (EventResult event)
  dbUpdate :: (MethodState event ~ Database,UpdateEvent event) => event -> m (EventResult event)

and the instance for the production monad works fine since it only passes the event to the update and query functions of acid state, but for a test monad i would like to have something like this: instance Db Test where dbQuery (GetVersion) = use (testDb . clientVersion) dbQuery (GetUser name) = preuse (testDb . users . ix name) dbUpdate (PutUser name user) = users %= M.insert name user ... so that I can match on GetVersion,GetUser etc. (which are generated by the template haskell function makeAcidic ... ) and specify how they should be handled in the test environment.

But I get the error:

Could not deduce: event ~ GetVersion
from the context: (MethodState event ~ Database, QueryEvent event)
  bound by the type signature for:
              dbQuery :: (MethodState event ~ Database, QueryEvent event) =>
                        event -> Test (EventResult event)
  at Main.hs:88:3-9
‘event’ is a rigid type variable bound by
  the type signature for:
    dbQuery :: forall event.
                (MethodState event ~ Database, QueryEvent event) =>
                event -> Test (EventResult event)
  at Main.hs:88:3
• In the pattern: GetVersion
In an equation for ‘dbQuery’:
    dbQuery (GetVersion) = use (testDb . clientVersion)
In the instance declaration for ‘Db Test’
• Relevant bindings include
  dbQuery :: event -> Test (EventResult event)
    (bound at Main.hs:88:3)

i guess thats because GetVersion, GetUser etc. all have a their different own types. So is there a way to do this?

Test Unit Jasmine e Karma Angular

I'm doing unit testing on angle 6, I'm having trouble testing this branch, I use it to observe how big the screen is to decide how many columns I'll display

@Component({
  selector: 'app-rdesp-waiting-approval',
  templateUrl: './rdesp-waiting-approval.component.html',
  styleUrls: ['./rdesp-waiting-approval.component.scss'],
  animations: fuseAnimations

})
export class RdespWaitingForApproval implements OnInit  {
   this.watcher = media.subscribe((change: MediaChange) => {
      this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : '';
          if ( change.mqAlias == 'xs') {      
           this.displayedColumns = ['job' ,'name', 'totalValue'];
          }else{
            this.displayedColumns = ['internalId','DateOfPublication', 'alias', 'job', 'name','totalValue'];
      }
    });

  
  }
 

C++ googlemock won't compile in silly example

I'm very new to C++, and I'm trying to use googlemock and googletest. I can't seem to get them to work even in simple examples so I'm sure there must be something simple I'm missing. I would really appreciate some help on this. I have a class Foo which has another class Bar as a dependency so I'm trying to mock this dependency out in tests. I'm sorry in advance, this seems like the simplest Dependency Injection example to me but it still spreads across 9 files! This is Bar:

// lib/bar.h
#ifndef BAR_H
#define BAR_H

class Bar {
  public:
    Bar(int baz);
    virtual ~Bar() {};
    int _baz;
};

#endif

With implementation:

// lib/bar.cpp
#include "bar.h"

Bar::Bar(int baz) : _baz(baz) {}

Here is the MockBar header:

// tests/mock_bar.h
#ifndef MOCK_BAR_H
#define MOCK_BAR_H
#include <gmock/gmock.h>
#include "../lib/bar.h"

class MockBar : public Bar {
  public:
    MockBar();
    virtual ~MockBar() {};
};

#endif

And the implementation:

// tests/mock_bar.cpp
#include "mock_bar.h"

MockBar::MockBar() : Bar(0) {
}

So MockBar is just Bar with baz set to 0. Here is Foo:

// lib/foo.h
#ifndef FOO_H
#define FOO_H
#include "bar.h"

class Foo {
  public:
    Foo(Bar bar);
    virtual ~Foo() {};
    Bar _bar;
    int getBaz();
};

#endif

// lib/foo.cpp
#include "foo.h"

Foo::Foo(Bar bar) : _bar(bar) {
}

int Foo::getBaz() {
  return _bar._baz;
}

And here is my test:

// tests/test_foo.h

#ifndef TEST_FOO_H
#define TEST_FOO_H
#include <gtest/gtest.h>
#include "../lib/foo.h"
#include "mock_bar.h"

class FooTest : public ::testing::Test {
  public:
    FooTest();
    Foo subject;
    MockBar mock_bar;
    virtual ~FooTest() {};
};

#endif

// tests/test_foo.cpp

#include "test_foo.h"

FooTest::FooTest() : mock_bar(), subject(mock_bar) {
}

TEST_F(FooTest, BazTest)
{
  ASSERT_TRUE(subject.getBaz() == 0);
}

Finally, the main test function is:

// tests/main.cpp

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "test_foo.h"

int main(int argc, char **argv) {
  testing::InitGoogleMock(&argc, argv);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

When I compile this all together with:

g++ tests/main.cpp tests/test_*.cpp tests/mock_*.cpp lib/*.cpp -o test 
-lgtest -lpthread -std=c++11

I get the error:

Undefined symbols for architecture x86_64:
  "testing::InitGoogleMock(int*, char**)", referenced from:
      _main in main-0b53fe.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1

I would really appreciate some help, please let me know if I can be more clear!

How to make a method with @BeforeClass to run more than once?

I wish to run a method with @BeforeClass annotation twice (or more). Is there a way to do so with TestNG?

Like: @Test(invocationCount = 2)?

How to send json from apache benchmark without external file?

I have JSON from postman collection and i am iterating the requests list and calling ab from my script. get is working fine. I have json of request body, how i can send json with ab without using external file.

How to test void method which returns single instance of a class?

I'm setting up new java project , i have a void method in database class which returns single instance of the object (singleton class). I want to test it using junit and mockito.

I have tried the fallowing testcase code using assertSame which return's the test fails.

public class DatabaseConnectionTestCase {

        DatabaseConnection connectoin;
        
        @Before
        public void setup()
        {
                connectoin = DatabaseConnection.getInstance();
        }
        @Test
        public void test() throws SQLException 
        {
                Assert.assertSame(connectoin.GetDBConnection(),connectoin.GetDBConnection());
                
        }

}

Database class which is used for testing

   public Connection con = null;
public static DatabaseConnection Database_single_instance = null;

// create single object for all the class
public static DatabaseConnection getInstance() 
   {
    if (Database_single_instance == null)
        Database_single_instance = new DatabaseConnection();

    return Database_single_instance;
}

private DatabaseConnection()
{

}
// establish a database connection used across the project
public Connection GetDBConnection() throws SQLException {

    String url = "jdbc:mysql://localhost:3306/iteration";
    String username = "root";
    String password = "";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, username, password);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return con;
}

// return connection as single instance
public Connection getConnection() {
    return con;
}

lundi 24 décembre 2018

Is there any way to control html pc and html mobile in a single component?

I have the following code

import { Component, OnInit } from '@angular/core';
import { mobile } from '../../../../environments/environment';

@Component({
  selector: 'ctk-details-advisory',
  templateUrl: (mobile) ? 'details-advisory.component.mobile.html' : 
'details-advisory.component.html',
 styleUrls: ['./details-advisory.component.scss'],
})
export class DetailsAdvisoryComponent implements OnInit {
// ...

this helps me control different html, pc and mobile view. the problem is that when I want to perform unit tests I get the following error

Module not found: Error: Can't resolve ' (mobile) ? 'details-advisory.component.mobile.html' : 'details-advisory.component.html'' in '/home/anonymous/criptoanalisis-0.2/frontend/src/app/pages/advisory/details-advisory' @ ./src/app/pages/advisory/details-advisory/details-advisory.component.ts 23:22-121

would be of much help some solution to this problem or another way to control different html the truth is that I'm going a good time trying to solve the problem I would greatly appreciate any suggestion

how do i test mongoDB database correctly

im getting into testing and i need to know what is the best way to test my database. I have put in a class. do i do both unit test and integration test on just integration tests for this. please provide advice and an example of how you would test.

im not even sure if this is a good way to setup your database. most people attach database calls to the route handler but i figured this way makes it easier to test the database so please give your input on that too.

thanks

import { MongoClient } from 'mongodb';



function Database(URI) {
    this.URI = URI;
    this.MONGO = MongoClient;

    // used defineProperty instead of normal method to prevent having to call collection
    Object.defineProperty(this, 'userCollection', {
        get: () => this.MONGO.db().collection(process.env.MONGO_USER_COLLECTION)
    })
}

Database.prototype.start = function () {
    this.MONGO = new this.MONGO(this.URI, { useNewUrlParser: true });
    return this;
};

Database.prototype.stop = function () {
    this.MONGO.shutdownServer();
};

Database.prototype.connect = async function (callback) {
    await this.MONGO.connect((error) => {
        if (error) return error;
        // linter expected a return value :S
        return callback();
    });
};

Database.prototype.createUser = function (data) {
    return this.userCollection.insertOne(data)
        .then(response => this.userCollection.find({ _id: response.insertedId })
            .limit(1)
            .next()
        );
};

// Database.prototype.deleteUser = function (userId) {
//     return this.userCollection.deleteOne({ _id: userId })
//         .then( deleteResult => {
                // (it might have changed to deleteResult.deletedCount)
//             if (deleteResult.result.n === 1) return { status: 'OK' };
//             return Error({status: 'Warning: object not found'});
//         });
// };

// Database.prototype.getUser = function (userId) {
//     return this.userCollection.find({ _id: userId })
//         .limit(1)
//         .next()
//         .then( user => {
//             if (!user) return { message: `No such issue: ${userId}` };
//             return user
//         })
// };

Firebase Test Lab can't record page scroll event in script recording

I'am trying to record a script. Every things is ok but when I try to scroll page, recorder is not responding and record nothing. I tried that in page with RecyclerView and ScrollView.

When I looked at test result in firebase console and watched the video, when the script is over and start the random test, pages can scrolling. So I thing there is a way but I can't find what it is. Please help.

Testing for a sudoku

I'm currently / was programming a proframm which tests if the given sudoku is a real sudoku. It works. My only problem is that i dont know if it meets all the required criteria. I am testing that every number is 9x in the sudoku and that it is only 1x in every 3x3 field. Adding to that im testing that every vertical and horizontal line (when added together) have the same result(45) wich includes that the overall result has to be 405. My question is if I need to test for every number to only once in every horizontal and vertical line once or is it not needed anymore?

how to reduce disc space if we have 10,000 input test data files

We have 10,000 test cases each test case has a test input file XML. So there are 10,000 XML files which are taking a lot of disc space about 2GB.

we have converted all the XML files to JSON files. which reduce a significant amount of space.

My Question is?

Is there any tool or another way we can reduce the size without affecting the performance.

Configuring If-else Statement in Katalon Studio

I'm trying to configure if-else statement, but my code stucks on if statement and doesnt go on else statement.

I've tried to make break; in if statement but it doenst works too

WebUI.openBrowser('')

WebUI.navigateToUrl('123/account/login?ReturnUrl=%2F')

WebUI.maximizeWindow()

WebUI.setText(findTestObject('123/Page_Log in/input_ _Username'), 'admin')

WebUI.setEncryptedText(findTestObject('123/Page_Log in/input_ _Password'), 'admin')

not_run: WebUI.verifyElementPresent(findTestObject('123/Page_Log in/span_Log in'), 1)

WebUI.click(findTestObject('123/Page_Log in/span_Log in'))

not_run: WebUI.verifyElementPresent(findTestObject('123/Page_Operator/button_To activate session sta'), 1)

WebUI.click(findTestObject('123/Page_Operator/button_To activate session sta'))

if (WebUI.verifyTextPresent("Operator already has active session", true)) {
    WebUI.click(findTestObject('if-else/Page_Operator/button_Clear'))

    WebUI.click(findTestObject('if-else/Page_Operator/button_To activate session sta'))

    WebUI.waitForPageLoad(5)

    WebUI.click(findTestObject('123/Page_Operator/click_phone'))

    WebDriver driver = DriverFactory.getWebDriver()

    WebElement Table = driver.findElement(By.xpath('//div[@id=\'missedCallsContainer\']'))

    List<WebElement> rows_table = Table.findElements(By.xpath('//tr[@class=\'dl-menu\']'))

    int rows_count = rows_table.size()

    println('No. of rows: ' + rows_count)
} 

else {
    WebUI.click(findTestObject('123/Page_Operator/click_phone'))
}

it works if the code goes in If statement but if that text what i have provided in if statement doesnt present, it stops working and doesnt go to else.

How to correctly set tests to run with H2 and alongside with MySql for the application in SpringBoot

I have implemented the spring boot application to work with MySql database and that is working perfectly fine. After that I started to implement some tests and I would like to use H2 db for the test purposes but I'm having issues with sql scripts when running tests.

In order to do that I added dependency

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
<scope>test</scope>
</dependency>

after that in the src/test/resources i have create application.yml with settings

spring:
  datasource:
    driver-class-name: org.h2.Driver
    platform: test
    url: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
    username: username
    password: password

  jpa:
    properties:
      hibernate:
        format_sql: true
        show_sql: true
        dialect: org.hibernate.dialect.H2Dialect
eureka:
  client:
    enabled: false

alongside with schema and data scripts for testing purposes.

Currently I have only main test

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {

  @Test
  public void contextLoads(){
  }

}

My problem is that when I run the tests I get an error "Syntax error in SQL statement" because it tried to execute scripts from src/main/resources. The errors are:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.autoconfigure.RefreshAutoConfiguration$JpaInvokerConfiguration': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker': Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement

Caused by: org.springframework.beans.factory.BeanCreationException: ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@14028087]to prepare test instance java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker': Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #8 of URL [file:/.../my-service/target/classes/schema.sql]
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE ... " expected "USING, ,, )"; SQL statement:

The errors are reasonable, spring boot is trying to execute sql scripts that are not in correct syntax to be executed on H2 DB, is there any way to state that when running tests schemas from src/main/resources to be executed or there is something that is not correctly configured?

Further request(s) expected leaving 1 unsatisfied expectation(s). 0 request(s) executed

I have following test class for my spring-integration application.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/test-dao-rest.xml"})
public class TestEmployeeRestDao {

  @Autowired
  private EmployeeDao employeeRestDao;

  @Autowired
  private RestTemplate mockRestTemplate;

  private MockRestServiceServer mockServer;

  /**
   * Sets up.
   */
  @Before
  public void setUp() {
    mockServer = MockRestServiceServer.bindTo(mockRestTemplate).build();
  }

  @Test
  public void testGetEmployeeById() {
    when(mockRestTemplate.getForObject(url + 1, Employee.class)).thenReturn(emp2);
    mockServer.expect(times(1), requestTo(url + 1))
        .andExpect(method(HttpMethod.GET))
    Employee employee = employeeRestDao.getEmployeeById(1L);
    assertNotNull(employee);
    mockServer.verify();
  }

`}

My xml config

  <bean class="com.nikolay.client.handler.CustomResponseErrorHandler"
    id="customResponseErrorHandler"/>

  <bean class="org.mockito.Mockito" factory-method="mock" id="mockRestTemplate">
    <constructor-arg value="org.springframework.web.client.RestTemplate"/>
    <property name="messageConverters">
      <list>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
      </list>
    </property>
    <property name="errorHandler" ref="customResponseErrorHandler"/>
  </bean>

  <bean class="com.nikolay.client.EmployeeRestDaoImpl" id="employeeRestDao">
    <property name="restTemplate" ref="mockRestTemplate"/>
  </bean>

</beans>

When I run a test, an error is thrown. Who can say what is wrong? I could not understand why this error occurs.

java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expectation(s).
0 request(s) executed.

Can you please help me to find out how this issue can be resolved.

Can't resolve all parameters for ApplicationModule: (?)

I just migrated an application module to be an importable library.

I'm trying to make the tests work correctly, just as they worked before, but I get this error:

Error: Can't resolve all parameters for ApplicationModule: (?).
at syntaxError (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:1275:17)
at CompileMetadataResolver._getDependenciesMetadata (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:11176:35)
at CompileMetadataResolver._getTypeMetadata (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:11069:26)
at CompileMetadataResolver.getNgModuleMetadata (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10937:24)
at CompileMetadataResolver.getNgModuleSummary (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10747:35)
at eval (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10861:51)
at Array.forEach (<anonymous>)
at CompileMetadataResolver.getNgModuleMetadata (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10849:49)
at CompileMetadataResolver.getNgModuleSummary (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10747:35)
at eval (webpack:///C:/Repositories/MyProject/my-library/node_modules/@angular/compiler/fesm5/compiler.js?:10861:51)

I've seen these possible solutions: Error: Can't resolve all parameters for ApplicationModule: (?) and Cannot resolve parameters for ApplicationModule: (?) but they cannot fix my problem.

projects/my-library/src/test.ts

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

Let me know if you need more information to figure out where is the problem.

Monkeypatching clean() method in a django Form Class

I use Django 2.1 on python 3.6 with pytest-django 3.4

I like to test the clean() method of a form defined like this :

from django.forms import HiddenInput, ModelForm, ValidationError 
from log.models import Entry 

class EntryForm(ModelForm): 
    class Meta: 
        model = Entry 
        fields = ['user', 'contact', 'title', 'desc'] 
        widgets = { 
            'user': HiddenInput(), 
            'contact': HiddenInput(), 
        } 

    def __init__(self, *args, **kwargs): 
        """ Get back user & contact obj for `self.clean()` """ 
        user = kwargs.pop('user') 
        contact = kwargs.pop('contact') 
        super(EntryForm, self).__init__(*args, **kwargs) 

        self.fields['user'].initial = user 
        self.fields['contact'].initial = contact 

    def clean(self): 
        """ 
        Checks if a entry is added on a contact owned by the connected user 
        """ 
        cleaned_data = super(EntryForm, self).clean()

        if 'user' in self.changed_data or 'contact' in self.changed_data: 
            raise ValidationError("Hidden input changed") 

        if cleaned_data['contact'].user != cleaned_data['user']: 
            raise ValidationError("Not allowed")

Outside tests, in a browser, this work as charm even if I change the values of hidden inputs : the ValidationError is raised.

I think about using monkeypatch but I did not understand how to inject my test conditions in a django class…

I use my feelings to build this test, but I cannot raise the expected ValidationError :

def fake_entry_form__init__():
    self.fields['user'].initial = 'initial user'
    self.fields['contact'].initial = 'initial contact'

def fake_entry_form_unvalid_changed_data():
    return  {
        'user': 'foo user',
        'contact': 'foo contact'
    }

def test_entry_form_clean_unvalid(monkeypatch):
    monkeypatch.setattr('log.forms.EntryForm.__init__', fake_entry_form__init__)

    form = EntryForm
    monkeypatch.setattr('log.forms.EntryForm.changed_data', fake_entry_form_unvalid_changed_data)

    try:
        form.clean
        assert False
    except KeyError:
        assert True

Am I on a good track or completely wrong?

I am new in django, CBV & testing, this is maybe a very obvious case, but I did not find explanation about it.

Count items,rows,users, etc in Katalon Studio

i'm having some problem in Katalon Studio. Can i somehow count items on page by class or something ? i can do it with javascript but i dont know how to do it with groovy language in katalon studio.

document.getElementsByClassName("").length <-- I'm trying to convert this javascript code into groovy but nothing happens.

dimanche 23 décembre 2018

Jest Enzyme tesing, passing props as obj function and expect return for test

I have login component, and

MobileNumber as subComponent,

I am passing props details to the MobileComponent from LoginComponent

login.js

setHeaderInfo = () => {
    this.setState({
      showHeader: true,
      headerContent: {
        headerContent: {
         showBckBtn: true,
         headerTitle: 'Next'
        },
        headerTitle
      }
    })
  }
return(
<MobileComponent setHeaderInfo={this.setHeaderInfo}>
) 

Now for testing js :

  let wrapper = shallow(<Login  />)

  const MobileNumberComponent = wrapper.find('MobileNumberComponent')

  it('header Title text checking', () => {
    MobileNumberComponent.props().setHeaderInfo( () => ({setHeaderInfo: {
      showHeader: true,
      headerContent: {
        showBckBtn: true,
        headerTitle: 'Next'
        }
    }}))
  })

Here console.log for

    console.log(MobileNumberComponent.debug())
<MobileNumberComponent setHeaderInfo={[Function]} />

I have passed the function here... But how could I expect that output... whether my test header is set or not as 'Next'..?

How to assert page doesnt reload with Cypress

I am running a test that assures a page does not reload when a button is clicked. So far, I have not found the best way to assert on this. I initially thought to create a route and wait for the xhr request that I don't want to happen, and if it happens, to fail the test. However, there does not appear to be a way to catch an error from a cy.wait() which makes it impossible for me to pass the test once the timeout occurs. My current solution is to ensure that the href for the given element starts with "#", but that seems to have the shortcoming of someone potentially attaching an event to it that would in-fact reload the page and it would not be caught by my test.

Any recommended ways to execute Jest tests sequentially, in a predefined order?

I've tried a suggestion from a related post (see link below) and it works: create separate files (that don't end in .test) for each test (or group of tests), import them into the main App.test.js, and call the files in the desired order. https://github.com/facebook/jest/issues/6194#issuecomment-419837314

However, I wonder if there are better ways of doing this by using Jest scripts for integration tests. This is not for unit tests.

App.test.js

import { apptestgroup1 } from './apptests.set1'
import { apptestgroup2 } from './apptests.set2'
import { apptestgroup3 } from './apptests.set3'

describe('App tests Group 1', apptestgroup1)
describe('App tests Group 2', apptestgroup2)
describe('App tests Group 3', apptestgroup3)

apptests.set1.js

export const apptestgroup1 = () => {
  it('sets loggedInUser = false when logOut is called', () => {});
  it('renders <Home /> when logOut is called', () => {});
}

apptests.set2.js

(more tests, similar to above)

apptests.set3.js

(more tests, similar to above)

Running the same Gradle task multiple times

So i have a gradle test task which runs all my tests. How can I set up gradle to run this task 100 times? It works and runs all my tests, I just need an option to choose how many times to run this.

The task in build.gradle:

test {
    // enable JUnit Platform (a.k.a. JUnit 5) support
    useJUnitPlatform()

    // set a system property for the test JVM(s)
    systemProperty 'some.prop', 'value'

    // explicitly include or exclude tests
    include 'com/company/calculator/**'

    // show standard out and standard error of the test JVM(s) on the console
    testLogging.showStandardStreams = true

    // set heap size for the test JVM(s)
    minHeapSize = "128m"
    maxHeapSize = "512m"

    // set JVM arguments for the test JVM(s)
    jvmArgs '-XX:MaxPermSize=256m'

    // listen to events in the test execution lifecycle
    beforeTest { descriptor ->
        logger.lifecycle("Running test: " + descriptor)
    }

    // Fail the 'test' task on the first test failure
    failFast = true

    // listen to standard out and standard error of the test JVM(s)
    onOutput { descriptor, event ->
        logger.lifecycle("Test: " + descriptor + " produced standard out/err: " + event.message )
    }

samedi 22 décembre 2018

How to make sure all cases are covered in an event-based concurrent setup?

In SICP 3.4.2 there is the problem of the order of events in the different processes.

Suppose we have two processes, one with three ordered events (a,b,c) and one with three ordered events (x,y,z). If the two processes run concurrently, with no constraints on how their execution is interleaved, then there are 20 different possible orderings for the events that are consistent with the individual orderings for the two processes.

20 orderings

As programmers designing this system, we would have to consider the effects of each of these 20 orderings and check that each behavior is acceptable. Such an approach rapidly becomes unwieldy as the numbers of processes and events increase.

Is there any tool / best practice which helps the programmer making sure every logically different cases are covered?

It would be nice if the programmer could define a set of events & constraints between them and the tool would return all the valid order of events (recognizing and grouping similar eg. looping patterns).

Given the list of possible event streams the programmer would be able to add/remove/modify the constraints.

The problem is important to me, because the most bug I have is related to some race condition or some not handled cases.

I don't really want to use a specific language with some advanced type system, I'd rather have a technology/language independent solution which acts as some kind of assistant - to design and document a system: with its events, constraints (and states).

It would be the holy grail to me.

I was searching for the solution across these topics: formal methods, formal verification, prolog (because of exhaustive search and logic), concurrency, dependent types, event-based programming, many types of testing, design by contract, cyclomatic complexity; but none of them gave me the answer. Furthermore, going deep into type theory seems to be an overkill.

My controller is working in runtime, but the mockkmvc test is failing for a dependency that is not even in the class

When I run the test, I get a dependency error of UserService is not able to be found to be injected. This is weird because no where in ConstantsController.java did I use UserService. Also, UserService is label properly with @Service annotation.

I have tried using the @MockBean annotation in the controller test class. It gave me unidentifiable errors. I even tried autowiring the bean in the configuration because the log said define bean of type of UserService in configuration. Still no luck.

UserService

package com.GMorgan.RateMyFriendv5.Service;

import com.GMorgan.RateMyFriendv5.Entitiy.Role;
import com.GMorgan.RateMyFriendv5.Entitiy.User;
import com.GMorgan.RateMyFriendv5.Repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserService {
    private UserRepository repository;

    public boolean login(String username, String password) {
        List<User> userList = repository.findByUsername(username);
        boolean isSuccessful = userList.get(0).isPassword(password);
        log.info("Username: {} isSucessful: {}", username, isSuccessful);
        return isSuccessful;
    }

     public boolean signUp(String email, String username, String password) {
        if (userEmailExists(email) || userUsernameExists(username)) return false;
        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(Role.USER);
        repository.save(user);
        log.info("User email: {} username: {}", email, username);
        return true;
     }

    public boolean userEmailExists(String email) {
         return !repository.findByEmail(email).isEmpty();
    }

    public boolean userUsernameExists(String username) {
        return !repository.findByUsername(username).isEmpty();
    }
}

ConstantsController.java

package com.GMorgan.RateMyFriendv5.Controller;

import com.GMorgan.RateMyFriendv5.Utils.Mappings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConstantsController {

    @Value("${controller.constant.ping.message}")
    public String pingMessage;

    @RequestMapping(Mappings.PING)
    public String ping() {
        return pingMessage;
    } 
}

ConstantsControllerTest

@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class ConstantsControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Value("${controller.constant.ping.message}")
    public String pingMessage;

    @Test
    public void pingTest() throws Exception {
this.mockMvc.perform(get(Mappings.PING)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString(pingMessage)));
    }
}

I want the test to pass. In runtime, when I go to the link, I see the ping message. I want the test to do so as well.

Why do I get a different result when I use an auxiliary variable before inserting a return value into an array?

I'm trying to brush up my Java so I'm implementing a double-array trie data structure. Now I'm trying to understand some strange behavior in my code.

I have a class with the following method that searches an array check, which is a non-static member of the same class, until it finds an element that satisfies certain conditions. The code does not modify anything apart from what you see in the method, where only local variables are updated.

private int findBase( final int[] characters )
{
    final int setLength = characters.length;
    final int max = characters[setLength - 1];
    final int firstCharacter = characters[0];

    int nextLink = getLinkAfter( FIRST_LINK, INIT_LAST_LINK + firstCharacter );

    while ( nextLink > 0 )
    {
        int count = 1;
        int newBase = nextLink - firstCharacter;

        ensureCapacity( newBase + max );

        while ( ( count < setLength ) && ( check[newBase + characters[count]] < 0 ) )
            count++;

        // IF all characters fit with newBase
        if ( count == setLength )
            return newBase;

        nextLink = getNextLink( nextLink );
    }

    // Should never get here, so we raise an exception
    throw new RuntimeException( "Error traversing the G-list." );
}

In another method I call this function and insert the result into the array base, which is also a non-static member.

As you can see, I use an auxiliary variable newBase to save the return value before I insert it into the array. Afterwards I added an assertion that checks that the value is "OK".

I have a few JUnit test cases including one that reads a million strings from a file and tries to insert them into the data structure (with no randomization involved at any point), and when I run this code everything works just fine.

...
else
{
    // Find a base that can branch both characters
    int[] characters = 
        { CharMap.byteToInt( suffixA[0] ), 
          CharMap.byteToInt( suffixB[0] ) };
    Arrays.sort( characters );

    // TODO: Sort out this nonsense
    int newBase = findBase( characters );
    base[state] = newBase;

    assert ( base[state] > START_STATE );

    insertNewLeaf( state, suffixA, 0, data );
    insertNewLeaf( state, suffixB, 0, oldData );
}
...

However, if I insert the return value without the auxiliary variable like below, the above assertion fails at some point.

// TODO: Sort out this nonsense
base[state] = findBase( characters );

The data structure itself should be entirely deterministic and I don't see how any external randomness (like execution order of the test cases) could affect the outcome of the code above.

Any idea why this is happening?

I use OpenJDK 1.8.0_181 and Maven 3.3.9 in Linux.

How to test an RxJS observable that tracks the last emitted value (no complete signal)?

I did some searching, but was unable to find a simple answer to my use-case. I apologize in advance if there already exists a sufficiently similar question on SO.

I have an observable, myObservable, that continuously streams a value from a store (i.e. it represents the state of the store). I want to test, with Jest, that my observable is able to correctly update when changes happen to the store.

// i.e. every time the value changes, an event is emitted by myObservable
myObservable.subscribe(x => console.log(x))

So what I really want to do is something like the following:

await myStore.set(0)
// insert here: check that `myObservable` stream is a 0
await myStore.set(5)
// insert here: check that `myObservable` stream is a 5

Basically I need a way to "tap" in to myObservable at any point in time to see what value was last emitted. Sorry if this is a bit of a n00b question.

vendredi 21 décembre 2018

Laravel Dusk-Example Test Results in Risky Test, Skipped

I've just started using TDD and Dusk to my coding routine.

After a clean install of Laravel and Dusk, I run php artisan dusk and the Example test returns with the message

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Risky: 1.

Risky Skipped Message (screencap)

.

Can anyone explain why there are no test performed?

.

Set Up:

beyondcode/dusk-dashboard  1.0.3

laravel/dusk               v4.0.4

laravel/framework          v5.7.19

phpunit/phpunit            7.5.1

What I have done: Searched Google, StackOverflow for possible fixes

How to unit test a method involving time factor/

I have the following piece of code which has time factor in it. I have trouble thinking how to do unit test for this piece of code.

public void someMethod(MultipartFile file,String username){
long timeNow = System.currentTimeMillis();
        byte[] bytes = file.getBytes();
        String fileLocation = defaultLocation +username+"_picture_"+timeNow+"_"+file.getOriginalFilename();
        Path path = Paths.get(fileLocation);
        Files.write(path, bytes);
}

Since there is time involved i am unable to do unit testing. Can anyone please help in this? I use Mockito for unit testing btw