jeudi 31 janvier 2019

Laravel Dusk Draw on Canvas Element

I am trying to make a Laravel Dusk test to sign a canvas elememt (jSignature plugin)

But can seem to get it working. this is my current code:

    $this->browse(function (Browser $browser) {
        $browser->visit('/form')

            # Sign
            ->click('#input-13')
            ->pause(3000)
            ->mouseover('.jSignature')
            ->click('.jSignature')
            ->moveByOffset(100,100)
    });

Any ideas how?

Are there any tools to record and play test scripts in watir webdriver?

I need a tool that would record usr action on browser and generate watir webdriver scripts.Please help

Bivariate Mann-Whitnney using generated control database

I have the next experiment: I measured 190 cortical signals over 40 subjects and applied two nonlinear measures over each signal. In order to validate my method I create 50 surrogates for each signal (control database) and for each one of these I computed the nonlinear measures above refered. I want to test differences between the measures between the original and control databases using the function sr.loc.test from package SpatialNP in R but it's taking plenty of time and I must repeat this test 20 times.

Is there any quicker function that allows me to do the same or any guide you can give me to reduce computing time?

Running Puppeteer tests in order with Jest

I'm using Jest Puppeteer and I have a situation where I'd like to run my login test (which sets cookie/localStorage for the authentication) first and run the others after, however, I know that Jest doesn't work this way - as it searches the local filesystem and runs tests based on the patterns in the filename, and the order in which they run is different.

I'm not entirely sure I'm going about this the correct way as I'm relying on a test to set the the authentication session for the other tests.

Is it possible to do the above, or do I need to rethink my approach?

How to use Capybara sessions or remember a user login

I want to test a chat app with Minitest and Capybara. The app assigns a logged-in user a unique ID. This ID is embedded in the head of an html-document and calls a javascript script which is used to connect with a visitor to chat with him.

Now, the problem is that every time I log in with capybara the ID changes (as it is for every new user). But I need the ID to configure the test.html file so the chat is assigned to the right user.

How can I make Capybara remember my user that I created in my fixtures.yml? Is there even a way? I tried using sessions but I'm not sure how to do it exactly nor if that is the right approach....

Any help is highly appreciated!

Best,

Perform sanity check before running tests with pytest

I would like to perform some sanity check when I run tests using pytest. Typically, I want to check that some executables are accessible to the tests, and that the options provided by the user on the command-line are valid.

The closest thing I found was to use a fixture such as:

@pytest.fixture(scope="session", autouse=True)
def sanity_check(request):
  if not good:
     sys.exit(0)


But this still runs all the tests. I'd like for the script to fail before attempting to run the tests.

I cannot test asynchronous componentDidMount that changes state with jest and enzyme

All I am doing in my code is upon componentDidMount being run, I am making an axios get request to Github, and setting some data back onto state, however when I am running the test it still says the state is an empty array, here is my component below:

export default class HelloWorld extends Component {
constructor(props) {
    super(props)
    this.state = {
        goodbye: false,
        data: []
    }

}

async componentDidMount() {
    await this.func()
}

func = async () => {
    let data = await axios.get('https://api.github.com/gists')
    this.setState({data: data.data})
    console.log(this.state)
}

goodbye = () => {
    this.setState((state, currentProps) => ({...state, goodbye: !state.goodbye}))
}

render() {
    return (
        <Fragment>
            <h1>
                Hello World
            </h1>
            <button id="test-button" onClick={this.goodbye}>Say Goodbye</button>
            {
                !this.state.goodbye ? null :
                <h1 className="goodbye">GOODBYE WORLD</h1>
            }
        </Fragment>
    )
}

}

and here is my test:

it('there is data being returned', async () => { 
    const component =  await mount(<HelloWorld />)       

    component.update()

    expect(component.state('data')).toHaveLength(30)

})

I am very new to using jest and am not sure what I am doing wrong, this app was built soley for testing out jest with enzyme. please let me know if I am doing something wrong!

Generate a dump file in case xunit assert happens in test dealing with random data

I am writing xunit fact test with random data and validating properties of my system.

If some assert happens, i want to generate a crash dump to inspect the situation of how system reached this point.

I could not find a way to do this. I found that it is possible to generate a crash dump of itself from managed process.

However, how can i hook in custom code in all Assert.True or similar Assert.XXX functions ?

Is there any alternate strategy for this ?

Mock multiple level arrays in java for unit testing

Hypothetically I have

class Box{
   Item[] items;
}

class Item{
   Toy[] toys;
}

class Toy{
   Color[] colors;
}

The method is to test if the Box has green color toy;

public bool testHasColor(Box){
   //There will be code here that
   //Streams over each type till we get to color
   // Final point is
   if(color==Color.GREEN){
    return true;
   }
}

BoxText.class

public void testBoxHasColorGreenMethod(){
    // Need mocking here
}

What the best way to mock this Box class for the test case?

Thank you

Jasmine test property observable subscribe

I have this code:

export class ProgramComponent implements OnInit {
   @Input() events: Observable<any>;
   eventsSubscription: any;
   ...
   ngOnInit() {
      this.eventsSubscription = this.events.subscribe((event) => {
          ... <- Some code that I want to test!!!!
          console.log("The test doesn't get past here!!!!");
      });
   }
}

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

   beforeEach(async(() => {
       TestBed.configureTestingModule({
          imports: [
              ...
          ],
          declarations: [ProgramComponent],
          providers: [
              ...
          ]
       }).compileComponents();
    }));

    beforeEach(() => {
       fixture = TestBed.createComponent(ProgramComponent);
       component = fixture.componentInstance;

       // HERE I WANT TO SPY ON THAT EVENTS OBSERVABLE AND RETURN SOME VALUE
       // I tried this without success
       spyOn(component, 'events').and.returnValue({type: 'somevalue'}))

       fixture.detectChanges();
    });

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

The problem is that fixture.detectChanges(); does not trigger the subscribe of the events observable. Do I have to use spyOnProperty? But it's an Input of the component...

I already check this and this.

Thanks!

python patch object that is under __init__.py

I'm writing a test and I want to mock a list that is located in init.py, meaning not under a class. The object reference is: project/app/management/commands/__init__.py

and __init__.py looks something like:

my_list_of_dict = [
{
    'name': 'option1',
    'vesion': 0,

},
{
    'name': 'option1',
    'vesion': 0,

}
]

If it was under a class I would do something like -

@mock.patch.object(Class, 'my_list_of_dict')

but it isn't the case.

I tried something like

@mock.patch('project.app.management.commands.my_list_of_dict')
def test(self, mock_list):
    mock_list.return_value = [{.....}]

But it didn't work.

Installation of QARK in ubuntu 18.04

Installation of QARK in ubuntu 18.04

I've tried to install QARK in my ubuntu 18.04 Desktop machine. I was following some docs provided by linked in. but it is not worked for me

How to find classname (in selenium java) starting with a particular text and ending with a particular text?

Below is the element and I need to find the class names matching with the first "css-" and ending with "widget", How do i find it in selenium (java)?

tried with the below code, but it didnt work

List<WebElement> list1 = driver.findElements(By.xpath("//body[starts-with(@class, 'css-')]"));
List<WebElement> list2 = driver.findElements(By.xpath("//body[contains(@class, 'css-')]"));
List<WebElement> list3 = driver.findElements(By.xpath("//body[ends-with(@class, 'widget')]"));

Swift - using XCTest to test function containing closure

I am fairly new to Swift and am currently trying to write a unit test (using XCTest) to test the following function:

func login(email: String, password: String)  {

    Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
        if let _error = error {
            print(_error.localizedDescription)
        } else {
            self.performSegue(identifier: "loginSeg")
        }
    }
}

My research has identified that I need to use the XCTestExpectation functionality as XCTest executes synchronously by default meaning it won't wait for the closure to finish running (please correct me if I'm wrong).

Whats throwing me of is how I test the login function as it itself calls the asynchronous function Auth.auth().signIn().

Apologies if this has already been answered but I couldn't find an answer that directly addresses this issue.

Thanks

Separate Redis database for testing in Laravel

I'm using Redis to store user-defined config for my Laravel app. I want to know how can I separate the Redis database is being used while testing from the one that is going to be used in for production? That's because I need to flush Redis before each test case and I don't want this to touch my data in main (production) Redis database.

Common.py at Kiwi. How to mount to docker

Ok guys so I followed this step : https://kiwitcms.readthedocs.io/en/latest/index.html But what is really for me to is to understand how do you mount the common.py(main configuration file) to the working kiwi instance. I don't see the place of common.py in the kiwi, so I dunno where to mount it? Or do I have to recreate the images every time to get the new settings?

set proxy for webdriver manager

I have installed protractor by using npm install -g protractor then I am trying to update webdriver-manager update but it is giving an error for chrome driver googleapis and same for selenium. Please tell me how to set a proxy with full command, what username password should be given?

How to create a Class or Trait on package with autoload charging other path

Well, I'm create a package provider for extended fzaninotto/faker

For this I needs use this in the package's composer.json so that my package can become a provider of the Faker package

"autoload": {
    "psr-4": {
      "Faker\\Provider\\": "src"
    }
},

That's is no path for my package (real path package\abkrim\fake-ads\src)

When create a new faker class is easy (in path package\abkrim\fake-ads\src):

<?php

namespace Faker\Provider;

use Faker\Generator;

class MyFakerClass extends Base
{
    public function __construct(Generator $generator)
    {
        parent::__construct($generator);
    }
    ...
    // My own functions
}

And create a class file for data in same path

<?php

namespace Faker\Provider;

class MyFakerDataClass
{
    // My own code
}

Use code and work

$faker = (new \Faker\Factory())::create();
$faker->addProvider(new \Faker\Provider\Fakecar($faker));

echo $faker->someMethodOfMyFakerClass;

But I like create multiples classes (new providers in same package).

I don't know how to create a base class, because extend of Faker\Generator and name space is not my own dir.

So, I create a Helpers Class in my own dir

<?php

namespace Faker\Provider;

class Helpers
{
    /**
     * @param array $values
     * @return string
     * @throws \Exception
     */
    public static function getWeighted(array $values) :string
    {
        $currentTotal = 0;
        $firstRand = random_int(1, 100);

        $total = array_sum($values);

        $rand = ($firstRand / 100) * $total;

        foreach ($values as $key => $weight) {
            $currentTotal += $weight;

            if ($rand <= $currentTotal) {
                return $key;
            }
        }

        return '';
    }
}

For use in my provider use for example and works:

/**
 * @return string
 * @throws \Exception
 */
public static function flat() : string
{
    return Helpers::getWeighted(MyFakerDataClass::getStateTypeFlat());
}

I think taht is not best and correct method.

Plus, when I try to create a test, I can't.

<?php

namespace Faker\Tests\Provider;

use Faker\Factory;
use Faker\Generator;
use Faker\Provider\FakerRealState;
use Faker\Provider\RealStateData;
use Faker\Provider\Helpers;
use PHPUnit\Framework\TestCase;

class FakeAdsRealStateTest extends TestCase
{
    /**
     * @var Generator
     */
    private $faker;

    private $helpers;

    public function setUp()
    {
        $faker = Factory::create();
        $faker->addProvider(new FakerRealState($faker));
        $this->faker = $faker;
    }

    /**
     * @param $property
     * @param null $class
     * @return mixed
     * @throws \ReflectionException
     */
    public function getProtectedProperty($property, $class = null)
    {
        if( is_null($class))
        {
            $class = new FakerRealState($this->faker);
        }
        $reflection = new \ReflectionClass($class);
        $reflection_property = $reflection->getProperty($property);
        $reflection_property->setAccessible(true);
        return $reflection_property->getValue($class, $property);
    }

    public function testGetWeighted()
    {
        $data = [
            'key1' => 80,
            'key2' => 19,
            'key3' => 1,
        ];

        $result = array_fill_keys(array_keys($data), 0);

        for($i = 0; $i<1000; $i++)
        {
            $result[$this->faker->getWeighted($data)]++;
        }

        $this->assertGreaterThan($result['key2'], $result['key1']);
        $this->assertGreaterThan($result['key3'], $result['key2']);
        $this->assertGreaterThan($result['key3'], $result['key1']);

        $this->assertEquals('', $this->faker->getWeighted([]));
    }
}

Error

There was 1 error:

1) Faker\Tests\Provider\FakeAdsRealStateTest::testGetWeighted
InvalidArgumentException: Unknown formatter "getWeighted"

I think the difficulty lies in the fact that I do not know how to create a class to extend the rest of the suppliers under the prism of fzaninotto / Faker, or even create a Trait.

Test throws NullPointerException instead of RandomCustomException, but only in some environments

I am working on a project with more people and branches. There is a test, written by someone else, which weirdly passes in some of the environments and fails in some other ones.

We are working on separate branches but we made sure that we see the same version of the project with

git pull origin develop

The code looks like:

@Test(expected = RandomCustomException.class)
 public void saveReturnsWithCustomException() throws 
   RandomCustomException {
   xService.save(notValidX);   
}

In some environments it throws a NullPointerException, thus fails, in some other ones it throws a RandomCustomException.

We've checked it, and it's weird, but all the related codes seem to be exactly the same in all the environments.

My xService looks like:

  public X saveX(X x) throws RandomCustomException {
if (!validXName(X.getName())) {
  throw new RandomCustomException("The given name wasn't correct or the field is empty!");
}
return xRepository.save(x);

xRepository is mocked in the test.

xRepository:

public interface xRepository extends JpaRepository<X, Long> {
  X findByApplicationUser(ApplicationUser applicationUser);
}

Does anyone have a suggestion what can the problem be?

mercredi 30 janvier 2019

VUE CLI 3 - Testing Single-File Components with Mocha + webpack

I am trying to follow the documentation mentioned here Vue Test Utils!

Below is what i currently have set up

Project setup: Vue CLI 3.2.1 with Node v8.11.2

devDependencies

"@vue/cli-plugin-babel": "^3.2.0",
"@vue/cli-plugin-eslint": "^3.2.0",
"@vue/cli-service": "^3.2.0",
"@vue/test-utils": "^1.0.0-beta.28",
"babel-eslint": "^10.0.1",
"babel-plugin-istanbul": "^5.1.0",
"cross-env": "^5.2.0",
"eslint": "^5.8.0",
"eslint-config-standard": "^12.0.0",
"eslint-loader": "^2.1.1",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"eslint-plugin-vue": "^5.0.0-0",
"expect": "^24.0.0",
"istanbul-instrumenter-loader": "^3.0.1",
"jsdom": "^13.2.0",
"jsdom-global": "^3.0.2",
"mocha": "^5.2.0",
"mocha-webpack": "^1.1.0",
"node-sass": "^4.10.0",
"nyc": "^13.1.0",
"sass-loader": "^7.1.0",
"vue-template-compiler": "^2.5.17",
"webpack-cli": "^3.2.1",
"webpack-node-externals": "^1.7.2"

And nyc config inside package.json also

"nyc": {
    "include": [
      "src/**/*.(js|vue)"
    ],
    "instrument": false,
    "sourceMap": false
  },

vue.config.js

const nodeExternals = require('webpack-node-externals')
const path = require('path')
let isCoverage = process.env.NODE_ENV === 'coverage';

module.exports = {
    mode: 'development',
    externals: [nodeExternals()],
    devtool: 'inline-cheap-module-source-map',
    output: {
        // use absolute paths in sourcemaps (important for debugging via IDE)
        devtoolModuleFilenameTemplate: '[absolute-resource-path]',
        devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ].concat(
            isCoverage ? {
                test: /\.(js|ts)/,
                include: path.resolve('src'),
                loader: 'istanbul-instrumenter-loader',
                options: { esModules: true }
            }: [],
            {
                test: /.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
            },
            {
                test: /\.ts$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'ts-loader'
            }
        )
    },
    target: 'node',
    externals: [nodeExternals()],
    devtool: "inline-cheap-module-source-map"
}

My test folder structure looks like this:

enter image description here

My test code looks like this:

enter image description here

So far i tried running these commands:

"test-ci": "mocha-webpack --webpack-config vue.config.js --require test/setup.js test/**/*.js"
"cover": "cross-env NODE_ENV=coverage nyc --reporter=lcov --reporter=text npm run test-ci"

If i ran test-ci it will output this: WEBPACK Compiled successfully in 631ms But is just a blank page after then if i ran cover then the output come out as nothing being log by nyc:

enter image description here

What am i doing wrong here, been trying to figure this out for several hours now!

Selenium on Java: whats the differences between testing react and non-react web application

Can You expain me differences between testing in Selenium on Java React and non-react application or there's no difference? Now I only need unique id for element localization, does it look different in the React?

In my work we have automated tests written in Java with TestNG. Can I write test for React web application in Java or node.js is more recommended in this case? If yes - why? I'm looking for this on web but I have not found lot of information.

How to compute Intersection over Union for multiple overlapping boxes?

I have a set of predicted bounding boxes and a set of target bounding boxes. In each set, some of the boxes overlap. I understand that IoU is computed by counting the total area of overlap between pairs of corresponding boxes in predicted and target sets, and then dividing it by the total area of the pairs. I'm not entirely sure how that extends to boxes that overlap within a set.

For example, lets say red boxes are in predicted set, and blue boxes are in target set (i made them opaque, but there are just 4 boxes here - 3 squares and a rectangle):

enter image description here

Assume that the small red square corresponds to the small blue rectangle. And big red square corresponds to the big blue square.

Now, the IoU for the first pair is 1/5. For the second it's 4/9. So is the total IoU (1+4)/(5+9) = 5/14? Or is it 4/9 - all area covered with at least one blue divided by all the area covered total? And if it's the prior, how would you go about calculating it if you don't explicitly know which boxes in the prediction set correspond to which boxes in the target set (like if I didn't tell you that small red goes with small blue and big red goes with big blue)?

spring attempt to inject @Autowired dependencies in a Mocked instance

I have the following classes: com.foo.pkgx:

@Component public class A {}

@Component public class B {
    @Autowired A a;
}

com.foo.pkgy:

@Component public class C {
    @Autowired B b;
}

I.E. dependency-wise: C -> B -> A

When executing the following spock Specification:

@Configuration
@ComponentScan(basePackages = ["com.foo.pkgy"])
class Config {
    def mockFactory = new DetachedMockFactory()

    @Bean
    B b() {mockFactory.Mock(B)};
}

@ContextConfiguration(classes = Config)
class CSpec extends Specification {

    @Autowired
    C c;

    def "sanity"() {
        expect: c
    }
}

The test fails initialization:

Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'c': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: com.foo.pkgx.B com.foo.pkgy.C.b; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'b': 
Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: com.foo.pkgx.A com.foo.pkgx.B.a; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.foo.pkgx.A] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I read this as "tried to wire A into B, but failed". I wasn't expecting B to undergo autowiring, as it is mocked.

Could someone shed some light?

Thanks!

What is the best way to load test of website?

I would like to what is the best way to test load of website. Multiple users are going to login particular website. What is the best way to test the load of website?selenium c# program? java ? any free tool?

Failed: Expected one matching operation for criteria "Match DocumentNode", found none

I am trying to write a test for an angular service which I am using with grahpql & Apollo, I am trying to do the implementation as instructed here: Apollo Testing. The service is injected in a component which subscribes to the what's returned from the service.

I'm receiving these 2 errors:

  1. Failed: Expected one matching operation for criteria "Match DocumentNode", found none.
  2. NullInjectorError: No provider for HttpClient! - eventhough I added HttpClientTestingModule to the imports.

Component:

import { RulesService } from './rules.service'
import { Consequent, Condition } from './../../models/rules'
import { ModalComponent } from './components/modal/modal.component'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { Component, OnInit, OnDestroy } from '@angular/core'
import { RuleDisplayService } from './services/rule-display.service'
import { DataService } from '../data/data.service'

interface Rule {
    id: string,
    conditions: Condition[]
    consequent: Consequent
}
@Component({
  selector: 'lib-a-rate-rules',
  templateUrl: './rules.component.html',
  styleUrls: [
    './rules.component.scss',
  ]
})

export class RulesComponent implements OnInit {

  rules
  /**
   * Creates an instance of RulesComponent.
   */
  constructor (
    public rulesService: RulesService,
    public ruleDisplayService: RuleDisplayService,
    private modalService: NgbModal,
  ) {}

  ngOnInit(): void {
    this.rulesService.loadRules()
      .valueChanges.subscribe(
        ({data}) => {
          this.rules = data as Rule
        }
      )
  }

}

Service:

import { Injectable } from '@angular/core'
import gql from 'graphql-tag'
import { PlatformGraphQLService } from 'platform-graphql'
import { Apollo } from 'apollo-angular'

export const GET_RULE_QUERY = gql`
  query GetRule($id: ID!) {
    getRule(id: $id) {
      conditions {
        glItemType
        operation
        value
      }
      consequent {
        ... on FASelection {
          faPool {
            code
            name
            level
          }
          faSubpool {
            code
            name
          }
        }
        ... on MTDCSelection {
          mtdcCategory
        }
        ... on Exclusion {
          isExluded
        }
      }
    }
  }
`


@Injectable({
  providedIn: 'root',
})
export class RulesService {

  private apollo: Apollo
  constructor(
    private platformGraphQLService: PlatformGraphQLService,
  ) {
    this.apollo = this.platformGraphQLService
      .createClient('ws://localhost:5000/graphql')
  }

  loadRule(ruleID: string) {
    return this.apollo.watchQuery({
      query: GET_RULE_QUERY,
      variables: {
        id: ruleID
      }
    })
  }


}

Spec file:

import { PlatformGraphQLService } from 'platform-graphql'
import { TestBed, ComponentFixture } from '@angular/core/testing'
import { RulesService, GET_RULE_QUERY } from './rules.service'
import {
  ApolloTestingModule,
  ApolloTestingController
} from 'apollo-angular/testing'
import { async } from '@angular/core/testing'
import { HttpClientTestingModule } from '@angular/common/http/testing'
import { RulesComponent } from './rules.component'

describe('RulesService', () => {
  let controller: ApolloTestingController
  let fixure: ComponentFixture<RulesComponent>
  let component: RulesComponent
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        RulesComponent
      ],
      imports: [
        ApolloTestingModule,
        HttpClientTestingModule,
      ],
      providers: [
        PlatformGraphQLService,
      ],
    })
    controller = TestBed.get(ApolloTestingController)
  })

  xit('should be created', async(() => {
    const service: RulesService = TestBed.get(RulesService)
    expect(service).toBeTruthy()
  }))

  it('should return a rule from server', async(() => {
    fixure = TestBed.createComponent(RulesComponent)
    component = fixure.componentInstance
    component.ngOnInit()
    fixure.detectChanges()

    component.rulesService.loadRules()
      .valueChanges.subscribe(() => {
        expect(op.operation.variables.consequent.isExluded).toEqual(true)
      })

    const op = controller.expectOne(GET_RULE_QUERY)

    op.flush({
      data: {
        getRule: {
          'conditions': [
            {
              'glItemType': 'DEPARTMENT',
              'operation': 'LEQ',
              'value': 1300,
            },
            {
              'glItemType': 'SUBDEPARTMENT',
              'operation': 'GEQ',
              'value': 4805,
            }
          ],
          'consequent': {
            'isExluded': true,
          },
        }
      }
    })

    controller.verify()
  }))

  afterEach(() => {
    controller.verify()
  })


})

Why EntityGraph doesn't fetch related entity in JUnit test?

I have two enitities in my JPA/Hibernate application - Task and Timerecord.

Task

@NamedEntityGraph(
        name = "Task.timerecords",
        attributeNodes = {
                @NamedAttributeNode(value = "timerecords", subgraph = "timerecords"),
        }
)
@Entity(name = "tasks")
@Table(name = "tasks", schema = "myschema")
public class Task {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)", length = 16 )
    private UUID uuid;

    @NotNull
    @Column(name = "description", nullable = false)
    private String description;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Timerecord> timerecords = new ArrayList<>();
    //some more code
}

Timerecord

@Entity(name = "timerecords")
@Table(name = "timerecords", schema = "myschema")
public class Timerecord {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)", length = 16 )
    private UUID uuid;

    @NotNull
    @Column(name = "hours", nullable = false)
    private double hours;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tasks_uuid", nullable = false)
    private Task task;
    //some more code
}

TaskDao

@Repository("taskDao")
public class TaskDao {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Task> getAllWithTimerecords(){
         EntityGraph graph = entityManager.createEntityGraph("Task.timerecords");

        return entityManager.createQuery("from tasks", Task.class)
                .setHint("javax.persistence.fetchgraph", graph)
                .getResultList();
    }
}

But when I run my test

    Task task = new Task(...);
    Timerecord tr = new Timerecord(...);
    UUID taskUuid = taskDao.save(task);
    assertNotNull(taskUuid);
    UUID trUuid = timerecordDao.save(tr);
    assertNotNull(trUuid);

    tasks = taskDao.getAllWithTimerecords();
    assertEquals(1, tasks.size());
    assertEquals(1, tasks.get(0).getTimerecords().size()); //AssertionFailedError: Expected :1 Actual   :0

Debug shows that list of timerecords in task entity is empty!

The interesting moment: if I run Main class, get ApplicationContext and run the same code is in my test - everything is OK! Inside task entity list of timerecords contains one timerecord.

Strategies for DRY Jasmine tests

I'm writing extensive end-to-end tests for an Angular application using Protractor and Jasmine in Typescript. I have a specific problem, and a general problem, related to reusing my test code.

The specific problem: We want to test that our UI is behaving correctly when a user uploads a file. Since our system treats average-sized files differently from very large files, we'd like to run two identical test suites, where the only difference is the size of the file.

I've been using Page Objects to encapsulate details about our UI. That way my tests refer to actions that can be taken on a page, without needing to specify anything about what elements are on the page. But I don't know a good strategy for encapsulating details about the specs themselves --- describe and it blocks kind of seem like magic words to me, rather than methods.

The cut-and-paste strategy for the file upload tests would be, copy the 3 spec files and just change the path to the test file. But what is the clean code strategy for doing this?

Normalize test data (using IDF)

I would like to know how to train unseen (test) data to be passed through a model I have created that works well.

Testdata (unseen) has been trained following same steps as classification model, except for IDF.

I understand I have to normalize testdata, else I receive an error when trying to pass the testdata through the trained model.

The model created was normalized as follows (after data split):

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,3), norm='l2')
vectorizer.fit(train_text)
vectorizer.fit(test_text)

x_train = vectorizer.transform(train_text)
y_train = train.drop(labels = ['id','comment_text'], axis=1)

x_test = vectorizer.transform(test_text)
y_test = test.drop(labels = ['id','comment_text'], axis=1)

and here is the model

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.multiclass import OneVsRestClassifier


%%time 

# Using pipeline for applying logistic regression and one vs rest classifier 
LogReg_pipeline = Pipeline([ 
                           ('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=-1)), 
]) 

for category in categories: 
printmd('**Processing {} comments...**'.format(category))

# Training logistic regression model on train data 
LogReg_pipeline.fit(x_train, train[category])

# calculating test accuracy 
prediction = LogReg_pipeline.predict(x_test) 
print('Test accuracy is {}'.format(accuracy_score(test[category], prediction))) 
print("\n")

I would like to know how to prepare the testdata to be able to pass it through the model.

As when I pass the data though the model as it is:

prediction = LogReg_pipeline.predict(x_test) 

I get an error message.

Thank you

Josep Maria

Can Espresso work without launching activity with intent?

I want to write an Espresso test that will use currently launched activity on the tablet's screen. So I'll navigate to this activity with appropriate content manually prior launching the test, cause it's difficult and reluctant to write additional code to launch this activity with the same global "state" in app and pass all needed params in the launching intent and so one.

Is it possible and how to do this with Espresso, or I have to use UI Automator then?

Cant seed data in test_helper.rb

Seems loading seed data not work for me

my test_helper.rb file:

ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'

class ActiveSupport::TestCase
  fixtures :all
  Rails.application.load_seed
end

In rails console Rails.application.load_seed works fine

Angular unit testing form validation - control stays untouched

I've an Angular component which has form validation. I'm unit testing to make sure it displays an error message if the input is invalid.

But when I try to change the <input> box value, the control's state remains untouched and the error doesn't display.

Here's the code:

<form #zipForm="ngForm">
<label>
    <input type="text" id="postalCode" [(ngModel)]="postalCode" #postalCodeElem="ngModel" name="postalCode" [pattern]="validationPattern" required>
    <button type="button" (click)="click(postalCodeElem.value)">Enroll</button>
    <div *ngIf="postalCodeElem.invalid && postalCodeElem.touched">
    <span id="required-postal-code" *ngIf="postalCodeElem?.errors?.required">
        zip/postal code is required
    </span>
    <span id="invalidPostalCode" *ngIf="postalCodeElem?.errors?.pattern">
        zip postal code is invalid
    </span>
    </div>
</label>
</form>

Test file:

it('should show error in case of invalid postal code', () => {
    const elem: HTMLElement = fixture.nativeElement;
    const inputElem: HTMLInputElement = elem.querySelector('input');

    inputElem.value = 'L5L2';
    inputElem.dispatchEvent(new Event('input', { bubbles: true }));

    fixture.detectChanges();

    const invalidErrorElem: any = elem.querySelector('span');

    console.log('elem', elem);
    console.log('invalidErrorElem', invalidErrorElem);

    expect(invalidErrorElem).not.toBeNull();
});

I've created a stackblitz to demo the issue: https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts

Any idea what am I doing wrong?

Testing subscribe in service

Help please test the service. I found a lot of information about testing, but not one did not help.

admin.service.ts

  private bcUrl = 'http://30.30.0.101:8080';
  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.cookieService.get('token')
    })
  };

  constructor(
    private http: HttpClient,
    private cookieService: CookieService,
    private userService: UserService
  ) {
  }

  getUsers(page, lim): any {
    return this.http.get(`${this.bcUrl}/api/security/users?page=${page}&size=${lim}`, this.httpOptions)
      .subscribe(
        (data: DataInterface) => {
          this.users = data.content;
          this.st.totalElements = data.totalElements;
          this.st.totalPages = data.totalPages;
          this.dataSource = data.content;
        },
        error => {
          if (error.status === 404) {
            alert('Сторінка не знайдена');
          }
          if (error.status === 401) {
            alert('Немає прав доступу');
          }
        });
  }

This is part of the code. I would be very happy if you help test it. Or send to the desired resource.

Here is my test. I started writing it, but I don’t know where to go any further.

import {async, getTestBed, inject, TestBed} from '@angular/core/testing';
import {CookieService} from 'ngx-cookie-service';
import {AdminService} from './admin.service';
import {HttpClientTestingModule} from '@angular/common/http/testing';
import {UserService} from '@app/core/user/user.service';
import {RequestMethod, ResponseOptions} from '@angular/http';

describe('AdminService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [AdminService, CookieService, UserService]
    });
  });
  it('should be created', inject([AdminService], (service: AdminService) => {
    expect(service).toBeTruthy();
  }));


  it('should be getUsers', async(() => {
    const adminService: AdminService = getTestBed().get(AdminService);
mockBackend.connections.subscribe(connection => {
  expect(connection.request.method).toBe(RequestMethod.Delete);
  connection.mockRespond( new Response(new ResponseOptions()))
});

  }));


});

Globally disabling non-Animator animations for Espresso testing

I'm currently developing a UI test suite in Espresso for an app which has many procedural animations thorough. Many of those animations are actually infinitely-looped, which makes Espresso hang indefinitely while waiting for idleness.

Now, unfortunately, those animations were not developed using the Animator library classes, so the usual way of turning off animation scale (through Developer Settings) yields no effect here. At the same time, the dev team is wary about adding test-related code into the application's code (which prevents me from using flags/environment variables to manually stop animations, for instance).

Is there a solution to globally disable all animations regardless of their implementation without adding code into the application when running UI tests?

Protractor.explore() and .pause() and .enterRepl() run into a TypeError

When I run a protractor test with one of those:

await browser.enterRepl();
await browser.pause();
await browser.debugger();

It runs into the following error:

TypeError: doneDeferred.fulfill is not a function
TypeError: doneDeferred.fulfill is not a function
    at Socket.tester.once (C:\TSO-IP\tso-ip-ui\node_modules\protractor\built\debugger.js:212:34)
    at Object.onceWrapper (events.js:273:13)
    at Socket.emit (events.js:182:13)
    at Socket.EventEmitter.emit (domain.js:442:20)
    at TCP._handle.close (net.js:606:12)

I haven't really found anyone reporting an issue like this.

import 'jasmine';
import {browser} from 'protractor';
import {LoginPo} from '../login.po';
import {Process_adminPo} from "./process_admin.po";

describe ('Capacity register tests', () => {

let loginPage: LoginPo;
let process_adminPo: Process_adminPo;


beforeAll (async (done:DoneFn) => {
    loginPage = new LoginPo ();
    await loginPage.openApplication ();
    await loginPage.changeLanguage ();
    done();
});

beforeEach (async (done:DoneFn) => {
    process_adminPo = new Process_adminPo ();
    done();
});

it ('Add a new nomination group', async () => {
    await process_adminPo.open ();
    await browser.explore();
    //await browser.enterRepl();
    //await browser.pause();
    //await browser.debugger();
    await browser.sleep (5000);
    await process_adminPo.clickOnNewButton ();
}

I expect to enter into an interactive shell (REPL) mode to deal better with locating the elements

Angular testing observable in service

I would like to test function in service. But i can't test subscribe. How can i do this?

Function to test:

  getInvestigates(page, lim): any {
    return this.http.get(`${this.bcUrl}/api/investigates?page=${page}&size=${lim}`, this.httpOptions)
      .subscribe(
        (data: DataInterface) => {
          this.investigates = data.content;
          this.st.totalPages = data.totalPages;
          this.st.totalElements = data.totalElements;
        },
        error => {
          if (error.status === 404) {
            alert('Not found');
          }
        });
  }

JMeter non-GUI in Jenkins issue with Include Controller

I have two scripts in my test. A_script.jmx with the main test plan and the test fragment B_script.jmx with the module.

To include B-script into A_script.jmx I use the Include Controller with a path to the B_script.jmx

All works fine when I work in GUI locally but when I try to run it in Jenkins in non-GUI I receive an error:

Error in NonGUIDriver org.apache.jorphan.util.JMeterStopTestException: ModuleController:Notification has no selected Controller (did you rename some element in the path to target controller?), test was shutdown as a consequence

As I suppose the Include Controller in the A_script.jmx cannot find my B_script.jmx file here. Should I use some special path format in my Include Controller FileName? Both scripts are kept in one directory. I tried "B_script.jmx", "../B_script.jmx" etc

Any ideas where I'm wrong?

How do i integrate my swagger doc with my rest assured framework

My stakeholders want if any changes in API -request or response , my rest assured framework should be able to apt to the changes, so is there any way integration of swagger doc to rest assured framework possible?

Thanks in Advance

Unable to find visible elements

system characteristics:

**iPhone 6s iOS 10.2 Appium Desktop 1.10.0 Xcode 10.1 MacOS High Sierra 10.13.6

iPhone 7 iOS 12.2 Appium Desktop 1.10.0 Xcode 10.1 MacOS High Sierra 10.13.6**

In a specific section of the application under test, I tried to find all 'XCUIElementTypeStaticText' visible, but only one element was returned (in the pictures at the bottom).

When I tried to run the following query by iPhone 6s:

  • Predicate iOS: type == 'XCUIElementTypeStaticText' and visible == 1

screenshot at jan 30 11-53-31

screenshot at jan 30 11-55-58

  • Class Chain: **/XCUIElementTypeStaticText[visible == 1]

screenshot at jan 30 11-57-53

screenshot at jan 30 11-58-14

  • Xpath: //XCUIElementTypeStaticText[@visible = 'true']

screenshot at jan 30 11-59-03

screenshot at jan 30 12-00-45

As you can see for Xpath the elements retrieved are correct.

When I tried to run the following query by iPhone 7:

  • Predicate iOS: type == 'XCUIElementTypeStaticText' and visible == 1

screenshot at jan 30 12-23-25

screenshot at jan 30 12-23-45

  • Class Chain: **/XCUIElementTypeStaticText[visible == 1]

screenshot at jan 30 12-24-53

screenshot at jan 30 12-25-07

  • Xpath: //XCUIElementTypeStaticText[@visible = 'true']

screenshot at jan 30 12-36-19

screenshot at jan 30 12-29-12

Moreover, as you see in the picture at the bottom, the application's elements, although them are visible, have set up visible attribute to false on iPhone 7, instead with iPhone6 the attribute visible is true.

screenshot at jan 30 11-43-27

Finally, the find action is very slow also when is captured the screenshot and page source.

This is the link pointing to log file that include all action described: appium.log

Hamcrest matcher to compare two arrays

I have a method that do sort an array, and I want to test it, I want to compare its result with the expected one, of course that I can do it using a for loop, but i'm asking if there is a Hamcrest matcher to do the comparison

I have a class

class Person{
 String name;
 int age;
 double budget;
 Person(String name,int age,double budget){
  this.name = name;
  this.age = age;
  this.budget = budget;
 }
 @Override
 public boolean equals(Object obj) {
   if (obj == null || (obj instanceof Person)) return false;
   Person p = (Person) obj;
   if (((Person) obj).budget == budget && ((Person) obj).age == age && ((Person) obj).name.equals(name)) {
    return true;
   }
   return false;
 }
}

and my test method is like this

@Test
public void InsertionSortOfObjectUsingComparator() {
    Person p1 = new Person("A", 18, 800);
    Person p2 = new Person("K", 15, 1800);
    Person p3 = new Person("L", 18, 600);
    Person[] persons = {p1,p2,p3};
    Person[] expected = {p3, p1, p2};
    Person[] result = new Sort().sort(persons, Comparator.<Person>comparingDouble(o-> o.budget);
    //want to compare the content of the two arrays result and expected; using assertThat
}

Is it possible doing it using Hamcrest ? if yes, how ?

GTK Application for scrolling H

I am a Linux Kernel developer, we have a board running Yocto Image, got a requirement to display "A full black screen with scrolling H’s " for CISPR test. I am using GTK Library to this, Wrote a sample Code which blanks the whole screen and write "Hello World" on to the centre.

#include <gtk/gtk.h>
int main (int argc, char *argv[])
{
    GtkWidget *window;// GtkWidget is the storage type for widgets
    GtkWidget *label;
    gtk_init (&argc, &argv);// This is called in all GTK applications. Arguments are parsed
                        //from the command line and are returned to the application.
    window=gtk_window_new(GTK_WINDOW_TOPLEVEL); //creating a new window.
    label = gtk_label_new("Hello World");
    gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT);
    gtk_container_add(GTK_CONTAINER(window), label);
    gtk_window_set_decorated(GTK_WINDOW(window), FALSE);
    GdkCursor* Cursor = gdk_cursor_new(GDK_BLANK_CURSOR);
    GdkWindow* win = gtk_widget_get_window((window));
    gdk_window_set_cursor((win),Cursor);
    gtk_widget_show_all(window); //The final step is to display this newly created widget.
   gtk_main (); //All GTK applications must have a gtk_main(). Control ends here
                       //and waits for an event to occur (like a key press or mouse event).
   return 0;
}

As I am a newbie in GUI, can anyone guide me what all widgets should I use to get the scrolling H's.

https://www.youtube.com/watch?v=PWkuqyC3AWk

How to write an Integration test for API with Message Queue?

Consider that I have an API end-point http://localhost/add-page-view. When we send a post request with data {url: "google.com"} it will be sent to a message queue, then later will be inserted to the DB by the queue subscriber

I need to write a test case that will send a post request to this end-point, then check whether "google.com" has been inserted to DB. Since it's inserted via Message Queue, we aren't sure whether it's inserted or not.

One way is to post data to end-point after 2 seconds check whether it has been inserted

But, that doesn't sound like a good solution

Note: It's an integration test, not a unit test

mardi 29 janvier 2019

Error while trying to run shell script using OS process sampler in jmeter

one.jmx file takes command line arguments so i am putting the long command to run one.jmx in a shell script(RUN_GET_CALLS.sh). Now i am using Two.jmx which calls One.jmx via the shell script using OS process sampler. When i execute Two.jmx it is giving error

timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect
1548833794770,4,"Patient_""_id""",500,"Exception occurred whilst executing system call: java.io.IOException: Cannot run program ""bash /home/ubuntu/HSDP_Suit/TestSuite/JMX_files/RUN_GET_CALLS.sh"" (in directory ""/home/ubuntu/JMeter/apache-jmeter-5.0/bin""): error=2, No such file or directory",Patient 1-4,text,false,,0,0,6,6,null,0,0,0

enter image description here

I tried putting path in Working directory box also but it is not working

J2ee applications released under tomcat can still be intercepted by burpsuite after being modified to HTTPS protocol

I have a j2ee application that can be intercepted by burpsuite and get the parameters in the request, so I configured tomcat and changed the publishing mode from HTTPS, but it can still be intercepted by burpsuite.How do I harden the system to avoid being intercepted by burpsuite in the clear text parameters of the transport?

Changes to tomcat\conf\server.xml

<Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
    disableUploadTimeout="true" enableLookups="false" maxThreads="25"
    port="443" keystoreFile="D:/tools/apache-tomcat-6.0.53/.keystore" keystorePass="password"
    protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
    secure="true" sslProtocol="TLS" />

Changes to tomcat\conf\web.xml

<login-config>  
        <auth-method>CLIENT-CERT</auth-method>  
        <realm-name>Client Cert Users-only Area</realm-name>  
    </login-config> 
    <security-constraint>  
        <web-resource-collection >  
            <web-resource-name >SSL</web-resource-name>  
            <url-pattern>/*</url-pattern>  
        </web-resource-collection>  
        <user-data-constraint>  
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>  
        </user-data-constraint>  
    </security-constraint>

Code coverage for Robot framework where application written in C++

I have a scenario like this - Application written in hybrid languages (Python, C++ and Java majorly). There are around 100 test cases written in Robot framework to test the application. Now I want to see code coverage of my application. Is there any tool that can work in such scenario? Thanks in advance.

Facebook months, find if month dropdown contains any duplicates

I have a question. I want to find duplicate months on the Facebook dropdown by using automation selenium. I mean that how can I find duplicate months dropdown on the Facebook by using java selenium? I tried findelement, web element but I could not do that. Thank you...

Where do I need to place my Django tests so that they get executed?

I'm using Django and Python 3.7. I would like to create and run some unit tests. Per the Django documentation, I created this file ...

ls ./mainpage/tests/test_models.py

But when I run my tests using the command below, it says zero tests were executed ...

(venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test
Creating test database for alias 'default'...
/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField Article.main_page_first_appeared_date received a naive datetime (2019-01-29 22:43:53.575128) while time zone support is active.
  RuntimeWarning)
System check identified no issues (0 silenced).

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
Destroying test database for alias 'default'...

Below are the contents of my file. What am I missing? Where should I put my tests or how should they be named so that they get executed?

from django.test import TestCase
from mainpage.models import ArticleStat, Article


class TestModels(unittest.TestCase):

    # Test saving an article stat that hasn't previously
    # existed
    def test_add_articlestat(self):
        id = 1
        article = Article.objects.filter(id=id)
        self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id))
        articlestat = ArticleStat(article=article,elapsed_time_in_seconds=250,votes=25,comments=15)
        articlestat.save()
        article_stat = ArticleStat.objects.get(article=article)
        self.assertTrue(article_stat, "Failed to svae article stat properly.")

How do I reference my settings file from running my unit tests?

I'm using Django and Python 3.7. I have different database configurations per environment, so I wanted to create settings that only import the database config depending on the environment. I have this directory ...

mainpage_project/settings

and within it are these files. "base.py" contains settings that I wish to be included regardless of the environment taht is loaded ...

(venv) localhost:mainpage_project davea$ ls mainpage_project/settings
__pycache__  base.py  dev.py  prod.py  test.py

I have this in my mainpage_project/settings/test.py file ...

from mainpage.base import *

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'testdatabase'
    },
}

But when I go to run my test file, I get the error complaining that it cannot execute the first line of the import, "from mainpage.base import *" ...

(venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv
    super().run_from_argv(argv)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 308, in run_from_argv
    parser = self.create_parser(argv[0], argv[1])
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 282, in create_parser
    self.add_arguments(parser)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 47, in add_arguments
    test_runner_class = get_runner(settings, self.test_runner)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/test/utils.py", line 301, in get_runner
    test_runner_class = test_runner_class or settings.TEST_RUNNER
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
    self._setup(name)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup
    self._wrapped = Settings(settings_module)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/davea/Documents/workspace/mainpage_project/mainpage_project/settings/test.py", line 1, in <module>
    from mainpage.base import *
ModuleNotFoundError: No module named 'mainpage.base'

How do I properly reference my settings?

How can I access a cousin element, of an element with an identifier in Cypress

I am trying to click a check box in a list of Table rows snapshot of the HTML the only way I can think to access this level is by the span tag with its corresponding name.

cy.get('tr > td > span').contains('newCypressTestCore').siblings('td > input').click();

although this would only return the siblings of the span tag when i actually need to access the cousin of the span tag.

<tr>
   <td>
     <input type="checkbox" />
   </td>
   <td>
     <span> newCypressTestCore </span>
   </td>
</tr>






Is Skype bot automated by Botium?

In my project we need to automate Skype bot. Can this be done using Botium? If yes, then please guide me. If no, please suggest any another open source tool?

RunListener equivalent in TestNG

I am converting my Cucumber-JUnit project to Cucumber-TestNg. In Junit, I used RunListener to grab Gherkin steps under execution. I used this listener to return me for a scenario the step currently executing like: on step 'Given' condition or on step 'When' or on step 'Then' so on. But in TestNg I could not find a similar listener that returns me the Gherkin scenario steps under execution. I tried other TestNg listeners, but i could not solve this problem. I find TestNg listeners are at test status related and not like JuNit RunListener. Suggest even if there is an alternative solution to this.

Error: No component factory found for NgbModalBackdrop

I'am trying to test if my angular bootstrap modal gets built when the user clicks on a button but I am receiving this error: Error: No component factory found for NgbModalBackdrop. Did you add it to @NgModule.entryComponents, and all the test in the it expression fails.

I'm using NgbModal, NgbModalRef, NgbActiveModal from @ng-bootstrap/ng-bootstrap

My spec file is code is:

describe('RulesComponent', () => {
  let component: RulesComponent
  let fixture: ComponentFixture<RulesComponent>
  let modalComponent: ModalComponent
  let activeModal: NgbActiveModal
  beforeEach(async(() => {
     TestBed.configureTestingModule({
      declarations: [
        RulesComponent,
        ModalComponent
      ],
      imports: [
        ReactiveFormsModule,
        NgSelectModule,
        HttpClientTestingModule,
      ],
      providers: [
        PlatformGraphQLService,
        RuleDisplayService,
        Apollo,
        DataService,
        NgbModal
      ]
    })
    .overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [
          ModalComponent,
        ]
      }
    }).compileComponents().then(() => {
      const modalService: NgbModal = TestBed.get(NgbModal)
      const modalRef: NgbModalRef = modalService.open(ModalComponent)
      modalComponent = modalRef.componentInstance
      activeModal = modalComponent.activeModal
    })
    fixture = TestBed.createComponent(RulesComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  }))

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

  it('should invoke the openModal method when user clicks on edit button', async(() => {
    spyOn(component, 'openModal')
    /**
     * add an empty rule so one row is added at least
     * for the edit button to appear and test it
     */
    component.rules = {
      getAllRules: [
        {
          id: '',
          conditions: '',
          consequent: ''
        }
      ]
    }
    fixture.detectChanges()
    const button = fixture.debugElement.query(By.css('button.edit-rule'))
    fixture.detectChanges()
    button.triggerEventHandler('click', 'openModal')

    fixture.whenStable().then(() => {
      expect(component.openModal).toHaveBeenCalled()
    })
  }))

  it('should initiate the modal component', () => {
    spyOn(component, 'openModal')
    expect(activeModal).toBeDefined()
  })
})

SonarQube - Is there basic example/explanation of how coverage issues can be resolved?

I'm very new to using SonarQube/Cloud (so please be gentle!) and am trying to work out how to improve the '0% coverage on new code' that my code has.

Here's an example:

I added the code:

    validation_errors = []

    for field in required:
        if field not in request.POST:
            validation_errors.append("field '{0}' missing".format(field))

    if len(validation_errors) > 0:
        return JsonResponse({'errors': validation_errors}, status=400 )

and I have a (Django) test for this:

def test_required_params(self):
        # no username
        response = self.client.post(self.url, { 'password': 'secret', 'media_file': self.video_file })
        self.assertRaises(forms.ValidationError)
        self.assertEqual(response.status_code, 400)

But when I run the sonar-scanner, in the online report, I get the message that these lines are not covered (see: https://sonarcloud.io/component_measures?id=django_oppia&metric=new_coverage&selected=django_oppia%3Aapi%2Fmedia.py)

I'm sure I must have some very basic mis/non-understanding of what the coverage metric actually means.

I'd really appreciate if someone could explain to me what I need to add/update in my code (just the specific example above), so the SonarCloud analysis doesn't continue to flag this as not covered.

Thanks for your help - if you need any extra info on code/platform/versions etc, just let me know.

Testing based on roles and permissions based website

What would be the best approach or the best tool for testing a drupal based website that deals mainly with roles and permissions? Just an insight. I am currently thinking about behat being the best tool in order to do the testing on such a website. but any other suggestions? any other insights on the topic. its a website that builds another website or an intranet service. different types of roles are assigned different types of permissions in order to perform the build. behat still the best approach for automated testing or any other tool would help. behat is one of the best toold for drupal based websites, my question is more specific only because it involves a lot of users haveing various different roles and permissions. thank you world :)

Testing an e-commerce mobile application,

I have the following problem :You're testing an e-commerce mobile application, similar to Amazon, ZOOT, eMAG, etc. A 2 week long sprint has just started and the goal of the sprint is to differentiate product prices between user types. The application already has all the typical e-commerce functionalities up and running ( register => log in => find a product => add to cart => order a product => order history ). Requirements: - Prices should be calculated and displayed according to the user type on all pages: Product page, Shopping Cart, Order, Order History.

My question is : Knowing that the execution and validation of the regression test suite will take 3 days, and the feature will be implemented by the developers in 4 days, how would your test plan look for the 2 week sprint?

disable exception handling in laravel test

I've been trying to disable exception handling in my test so I can see the errors, but it's not working even if I intentionally break the code.

I'm just getting this generic response and it's not helping much.

Invalid JSON was returned from the route.

I've tried all solutions I can find online, but none of them is working.

I tried adding $this->disableExceptionHandling() at the top of the test method, it didn't work. I also tried the tutorial from Adam Wathan, (https://gist.github.com/adamwathan/125847c7e3f16b88fa33a9f8b42333da) that didn't work also.

I've even tried editing the Handler.php file

public function render($request, Exception $exception)
{
    throw $exception;
    // return parent::render($request, $exception);
}

It's still now working.

Please how can I fix this.

Any help would be appreciated.

Thanks.

C++ Testing with describe-it

When working with Node, I like to use libraries like Jasmine, frameworks like Mocha and Chai. But so far, the only way I tested my C++ code was to construct little programs in single files, build all of them separately and run them, and see what their exit status is. Though, I am very sure there is a much nicer, cleaner way to do this.

I looked at Google Test and a few random ones at Github, but I couldn't see where a test is ever really described, like you'd do in describe() or it().

Essentially, I'd like to do something like this in my C++ tests:

int add(int a, int b) {
  return a+b;
}

describe("the add(int,int) function", {
  it("should add two numbers", {
    int c = add(1,2);
    expect(c)->toEqual(3);
  })
})

This is obviously some concept code there, but essentially what I would like to do. Do frameworks for that exist - and is there one that does not require C++11 (which I'd like to avoid since MSVC is not very well on supporting that unfortunately)?

Associate Test case in VS 2017 shows error not connected to a project but I am

I am using Visual Studio 2017 with Selenium C# for automation testing. I do see when I right click a Test, 'Associate to Test Case' is enabled. When I click it though, I do see an error - 'You are not logged into Team Services or Team Foundation Server. Please login to an account and try again'. I validated in the Team Explorer - Home, my test repository is displayed. I did close and reopen Visual Studio and reconnected to my project but still seeing the error.

Any advice would be great. Thank you. :)

How to extend PHPUnit in Laravel?

I am trying to extend the PHPUnit in Laravel, but I’ve faced a problem - application instance is not loaded. I'll do my best to explain my problem.

I want to implement TestListener interface and TestListenerDefaultImplementation trait to use PHPUnit Listener feature. But also I need to use my models in this listener.

As you can guess I cannot do this because Laravel’s CreateApplication trait is used only in a pair with its BasicTest. Thus the listener does not know anything about the application instance. How can I manage to do this with listeners? My phpunit.xml file: https://gist.github.com/andrewgorpenko/1a7d472ab4747f081c7da247261e29d1

Golang: Retrying a test

As we all know, Golang comes with a builtin testing package. My team uses the testing package for unit tests as well as integration tests, which can fail due to downstream dependency errors.

For these flaky integration tests, we want to try using test retries. Is there an idiomatic way to retry a Golang test?

How to remove first line of element

Im having a small issue when writing my tests. Currently an element i am trying to use is returning me "Points:-" when i print it on the console. In the html its in the format "Points: " and on the next line "-". How can i remove the "Points: " from this element so it only returns "-" and also assign the value "0" to it if its "-"?

My previous code is

Integer point_player = Integer.parseInt(points_player); System.out.println(point_player);

And that used to only return a String from 0-9 which i could just convert to integer but now the - has been introduced.

How can I accept a windows x509 certificate automatically?

I am writing a test and windows seems to be prompting me for what certificate to use when using x509 client certificates. I would like to have it automatically select one without user interaction (user interaction is bad when writing tests). The problem is there seems to be no documentation on how this works in MSDN, could someone at least point me towards an answer?

Is there some way to rollback redis data after finish java test code?

Is there some way to rollback the data in redis after test code run. I worked on a java web project using spring boot 2.

I know redis does not provided rollback operation.

So using another redis (like some embedded redis) in test can ensure test code does not change the redis data. And make a mocked redis client to get data in test redis first and if no data then get from the origin Redis. Does it workable?

And is there a ready made package implements this function?

Or has any simpler way to rollback?

Which function to be used for URL assertion in Dusk?

public function testPagination()
{
    $this->browse(function($first)
    {
        $first->loginAs(\App\User::find(1))
              ->visit('http://mettledlp.in.linuxense.com/user');
    });
    $this->browse(function(Browser $browser)
    {
        $browser->visit('http://mettledlp.in.linuxense.com/mailLog?page=1')
                ->clickLink('2')
                ->assertUrlIs('http://mettledlp.in.linuxense.com/mailLog?page=2');
    });
}

Error 1) Tests\Browser\MessageTest::testPagination Actual URL [http://mettledlp.in.linuxense.com/mailLog?page=2] does not equal expected URL [http://mettledlp.in.linuxense.com/mailLog?page=2]. Failed asserting that 'http://mettledlp.in.linuxense.com/mailLog' matches PCRE pattern "/^http://mettledlp.in.linuxense.com/mailLog\?page\=2$/u".

Both URL seems to be the same for me. I am trying to click "2" resulting from pagination. The screenshot shows that click has been successfully done. When i run command php artisan dusk. Error i have given pops up and testing fails.

How to mock executorService.submit()

How can I mock executorService.submit() in the below scenerio. I have to mock

cacheController.someMethod(); but as submit method is called it creates a thread and cacheController.someMethod(); never gets called for test class.

@Autowired
CacheController cacheController;
protected static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(1);

EXECUTOR.submit(() -> {
        try {
            cacheController.someMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

Jest/Enzyme ShallowWrapper is empty when creating Snapshot

So I'm writing a test for my Item component and I tried to render the ItemCard component and then use that wrapper to create a snapshot but it returns an empty ShallowWrapper {}

Please see the code for more info:

Item.test.js

import { shallow } from 'enzyme';
import { ItemCard } from '../Item';

const fakeItem = {
  id: 'aksnfj23',
  title: 'Fake Coat',
  price: '40000',
  description: 'This is suuuper fake...',
  image: 'fakecoat.jpg',
  largeImage: 'largefakecoat.jpg',
};

describe('<ItemCard/>', () => {
  it('renders and matches the snapshot', () => {
    const wrapper = shallow(<ItemCard me item={fakeItem} showButtons />);

    // console.log(wrapper.debug());
    expect(wrapper).toMatchSnapshot();
  });
});

The snap it creates:

// Jest Snapshot v1

exports[`<ItemCard/> renders and matches the snapshot 1`] = `ShallowWrapper {}`;

As far as I know the ShallowWrapper should have some content in it instead of being empty..

Can someone tell me what am I doing wrong here?

Thanks

Figure out how many inputs satisfy a given branch condition

I am trying to do the following task. Suppose I have the following program:

int foo(char a){
  if (a > 3 && a < 7) {
     if (a >= 4 && a < 6) { <--- how many solutions can satisfy this point?
        printf("win!\n");
     }
  }
}

Given input a as a char variable, we want to figure out how many possible values of a can be used to reach the nested conditions.

Obviously since a is a char variable, then only if a is within {4, 5}, the nested condition can be satisfied. But in general, how I can figure this out? Is there any solution for that?

I am aware to use certain symbolic execution technique, together with model counting technique to formally infer the satisfiable solutions for such nested conditions. But that is, although quite general in principle, too slow...

How to add a unit test project to my existing asp.net core project?

I started an asp.net core project using VS code(which is a very powerful lightweight text editor). I want to add a unit test project to my already existing project. In visual studio, I did this by creating a new project under my solution. In vs code I can only create a new directory, how should I add the unit test project?

lundi 28 janvier 2019

indexedDB testing Jeste Enzyme -TypeError: Cannot read property 'open' of undefined

Aplication working fine but when i test then it crashed.

this is pice of code where is something wrong.. i think

componentDidMount = async() => {
    try{
      const request = await window.indexedDB.open("QuestionData",1)

      request.onsuccess = (event) => {
        const db = request.result;
        const transaction = db.transaction('Questions' , "readwrite");
        const store = transaction.objectStore('Questions');
  
        const get = store.get(1)
        get.onsuccess = () =>{ 
          this.setState({
            data: get.result.data
          })
        }
      }

    }catch(err){console.log(err)}
  }

and this is a pice of test

test('should render btn', () => {
  const wrapper = mount(<App />)
  const btn = wrapper.find('.btn')
  expect(btn.length).toBe(1)
})

now Error !

console.log src/App.js:36 TypeError: Cannot read property 'open' of undefined

Selenium test failed

I'm learning Selenium. Why this simple test is failing?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.action_chains import ActionChains
import unittest


class ToolTipTest (unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get("http://jqueryui.com/tooltip/")
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

    def test_tool_tip(self):
        driver = self.driver
        frame_elm = driver.find_element_by_class_name("demo-frame")
        driver.switch_to.frame(frame_elm)
        age_field = driver.find_element_by_id("age")
        ActionChains(self.driver).move_to_element(age_field).perform()
        tool_tip_elm = WebDriverWait(self.driver, 10).until(
            expected_conditions.visibility_of_element_located(
            (By.CLASS_NAME, "ui-tooltip-content")))

        # verify tooltip message
        self.assertEqual(
            "We ask for your age only for statistical purposes.",
            tool_tip_elm.text)

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

if __name__ == "__main__":
    unittest.main(verbosity=2)

Sometimes it gives

AssertionError: 'We ask for your age only for statistical purposes.' != "ThemeRoller: jQuery UI's theme builder app
lication"
- We ask for your age only for statistical purposes.
+ ThemeRoller: jQuery UI's theme builder application

Sometimes:

AssertionError: 'We ask for your age only for statistical purposes.' != "That's what this widget is"
- We ask for your age only for statistical purposes.
+ That's what this widget is

So the error isn't always the same. It looks that it select a random popup. Here's the page to test. I'm using python 3.6 selenium 3

Possible to get Jest coverage without running tests?

We have a large test suite and would like to run tests only on changed files in our CI pipeline to improve build times (using --onChanged). We also want to ensure that our overall test coverage meets a certain threshold and so are running jest with --coverage. The problem is that we want to get coverage for the entire test suite, not just the changed files. Is it possible to either get the coverage for all tests while only running tests on those that have changed or to run jest --coverage without actually running tests?

How do we test for an optional hash field using Test2::V0

I am trying to work out how to test for an optional hash field using Test2::V0. I currently have the following:

use 5.016;
use Test2::V0;

subtest 'optional fields in a hash' => sub {
    my $check = hash {
        field foo => qr/^[0-9]+$/;
        field bar => qr/^[a-zA-Z]+$/; # this field is optional
    };

    like(
        { foo => 1 },
        $check,
        'should pass when optional field is omitted',
    );

    like(
        { foo => 2, bar => 'a' },
        $check,
        'should pass when optional field is provided',
    );
};

done_testing;

Now if I drop the check for the optional field:

my $check = hash {
    field foo => qr/^[0-9]+$/;
    # field bar => qr/^[a-zA-Z]+$/; # this field is optional
};

the test will pass. But I want to test the value when it's there.

Any ideas?

Test failing in angular 6 due to APP_BASE_HREF not being set

I am starting to use tests in my angular 6 application. I have run into an error though that I am not sure how to solve.

As you can see below my test is complaining that the base href is not set, but in my index.html I do have <base href="/">

Error: No base href set. Please provide a value for the APP_BASE_HREF token or
       add a base element to the document.
at new PathLocationStrategy (./node_modules/@angular/common/fesm5/common.js?:498:19)
at provideLocationStrategy (./node_modules/@angular/router/fesm5/router.js?:5302:9)
at _callFactory (./node_modules/@angular/core/fesm5/core.js?:8735:20)
at _createProviderInstance (./node_modules/@angular/core/fesm5/core.js?:8687:26)
at initNgModule (./node_modules/@angular/core/fesm5/core.js?:8617:32)
at new NgModuleRef_ (./node_modules/@angular/core/fesm5/core.js?:9343:9)
at createNgModuleRef (./node_modules/@angular/core/fesm5/core.js?:9332:12)
at Object.debugCreateNgModuleRef [as createNgModuleRef]
       (./node_modules/@angular/core/fesm5/core.js?:11157:12)
at NgModuleFactory_.create (./node_modules/@angular/core/fesm5/core.js?:11874:25)
at TestBed._initIfNeeded (./node_modules/@angular/core/fesm5/testing.js?:1015:47)

This is my item-component.spec.ts test

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

import {ItemComponent} from './item.component';
import {HttpClientTestingModule} from '@angular/common/http/testing';
import {AppRoutingModule} from '../../app-routing.module';
import {HomeComponent} from '../home/home.component';
import {ContactComponent} from '../contact/contact.component';
import {InventoryComponent} from '../inventory/inventory.component';
import {SearchComponent} from '../search/search.component';
import {ApplicationFormComponent} from '../application/application-form.component';
import {SiteShellComponent} from '../site-shell/site-shell.component';
import {MainNavigationComponent} from '../partials/main-navigation/main-navigation.component';
import {FooterComponent} from '../partials/footer/footer.component';
import {ReactiveFormsModule} from '@angular/forms';

import {DebugComponent} from '../debug/debug.component';
import {NewformComponent} from '../debug/under-test/newform.component';
import {MultiSelectComponent} from '../debug/under-test/multi-select.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ItemComponent,
        HomeComponent,
        ContactComponent,
        InventoryComponent,
        SearchComponent,
        FinanceApplicationComponent,
        SiteShellComponent,
        MainNavigationComponent,
        FooterComponent,

        DebugComponent,
        NewformComponent,
        MultiSelectComponent,
      ],
      imports: [
        HttpClientTestingModule,
        AppRoutingModule,
        ReactiveFormsModule
      ],
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ItemComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

How come my test cannot see the base href, or what am I doing wrong? I am really not sure what to look at here to fix. I tried importing AppComponent, but that did not help.

Mocking bufio.Scanner input

I've had a lot of success defining interfaces and substituting mocks during testing, but I've hit a problem with mocking bufio.Scanner input:

file := &mockFile{
    ReadFunc: func(p []byte) (int, error) {
        reader := bufio.NewReader(bytes.NewReader([]byte(consulPropertiesFile)))
        return reader.Read(p)
    },
    CloseFunc: func() error {
        return nil
    },
}

fs := &mockFileSystem{
    OpenFunc: func(name string) (File, error) {
        return file, nil
    },
}

properties, err := readConsulPropertiesFile(fs)

While this seems to work, once the scanner has gotten to the end of my string, it just seems to return to the beginning, and reads too much (it seems to read more than a line this time around). It's like I need to manually return an EOF error at the appropriate time in my ReadFunc, but I'm not sure how to figure out when I should do that...

Scanner code (lifted from here):

f, err := file.Open("/run/secrets/consul-web4.properties")
if err != nil {
    return nil, err
}
defer f.Close()

properties := map[string]string{}

scanner := bufio.NewScanner(f)
for scanner.Scan() {
    line := scanner.Text()
    if equal := strings.Index(line, "="); equal >= 0 {
        if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
            value := ""
            if len(line) > equal {
                value = strings.TrimSpace(line[equal+1:])
            }
            properties[key] = value
        }
    }
}

I've yet to refactor the above...

I've tried the following variations on my test string:

const input = `key=value
key=value
key=value
`

const input = "key=value\nkey=value\nkey=value\n"

And I've tried bufio.Reader & io.Reader implementations.

Any help / insight appreciated!

How to test performance / load of a modern angular application

I want to load / performance test a web application which uses angular 6+ as the frontend-framework. The application is quite big and uses lots of wizards / modals etc. I want to do some "real" e2e-frontend-tests (not just testing API-calls, but also js-rendering etc.)

What are the current state-of-the-art approaches and tools to test applications like this?

Allure Command Line Tool - Plugins Not Found

I am using allure reporting tool to generate reports (protractor-Jasmine-Typescript). I am using command line tool to generate HTML reports as per the below link

https://github.com/allure-framework/allure-jasmine

The reports are getting generated fine but i am getting exceptions as below:

Could not load extension class io.qameta.allure.junitxml.JunitXmlPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.junitxml.JunitXmlPlugin

Could not load extension class io.qameta.allure.xunitxml.XunitXmlPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.xunitxml.XunitXmlPlugin

Could not load extension class io.qameta.allure.trx.TrxPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.trx.TrxPlugin

Could not load extension class io.qameta.allure.behaviors.BehaviorsPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.behaviors.BehaviorsPlugin

Could not load extension class io.qameta.allure.packages.PackagesPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.packages.PackagesPlugin

Could not load extension class io.qameta.allure.xctest.XcTestPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.xctest.XcTestPlugin

Could not load extension class io.qameta.allure.jira.JiraExportPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.jira.JiraExportPlugin

Could not load extension class io.qameta.allure.xray.XrayTestRunExportPlugin: {} java.lang.ClassNotFoundException: io.qameta.allure.xray.XrayTestRunExportPlugin

The exceptions are not there if allure-maven-plugin is used because in that case we have pom.xml to mention plugins as mentioned in below link: https://github.com/allure-framework/allure-maven

How can i get these plugins using command line tool?

Test to ensure consistency of NGINX routes

We are migrating from a monolithic site to a fairly standard front-end/back-end architecture, and we're doing it piecemeal. As such we have quite complicated routing in our NGINX conf. When we migrate a new service from old system to new, we need to redirect the route, but given we have thousands of generated urls this is not always easy to reason about.

Let's use rooms and landing-pages as an example (but we have many conflicts like this)

nginx-frontend.conf

  # landing pages - to (eg) match /meeting-rooms/paris-2e-arrondissment
  location ~* "^/([\p{L}\p{N}-]+)/([\p{L}\p{L}-]+)/?$" {
    proxy_pass http://new:3000;
  }

  # rooms - to (eg) match /rooms/12345
    location ~* "^/rooms/([\p{N}]+)/?$" {
    proxy_pass http://old:3000;
  }

The eagle eyed of you will note that the first route (landing pages) also matches /rooms/12345 which is unintended and causes errors. We have similar problems with catching legacy css (/css/bobbins.js) and all sorts of other things.

The old and new services then perform their own routing internally to generate the correct data. We have all sorts of even more legacy routes on the old server which makes turning its corresponding routes off equally dangerous/frustrating.

What I would like to do is have a list of routes with the expected service written as some sort of test (don't care which language - python, node.js or php are preferable, but I'll adopt a new one if necessary to fix this) along these lines (pseudocode)

[
  { 
     test: ['/rooms/12345/', '/rooms/12346', ...],
     expect: service.to.be(old)
  },
  {
     test: ['/meeting-rooms/paris-2e-arrondissment/', '/meeting-rooms/london', ...],
     expect: service.to.be(new)
  }
]

Then, when we change a route, we can be certain that we have not accidentally introduced a problem

We're using docker, and I'm aware I will probably have to build a complete solution rather than expecting a quick line of code.

Is there a standard way of achieving this, or a service that I can employ? If not, outlines for potential solutions will also be gratefully received.

Vuejs project with good unit and e2e tests implemented

I am looking for projects that are using Vuejs that implements good unit test and e2e test practices.

I have only been able to find tutorial and guide project. But I am looking for a full open source projects that uses extensive testing.

The purpose is to get inspiration for testing on the larger scale.

Why I get NullPointerException while mocking?

Why do I get NullPointerException?

Here is my code:

@Stateless
@LocalBean
class SomeDao {

@PersistenceContext(unitName = "some-value")
private EntityManager entityManager;

public EntityManager getEntityManager() {
    return this.entityManager;
}

public long getNextId() {
    long someLongValue = getEntityManager().someMethod();
    //some code
    return someLongValue;
}
}

class SomeTest() {
@Spy
private SomeDao dao = new SomeDao();

@Test
public void someTestMethod() {
    MockitoAnnotations.initMocks(this);
    when(dao.getNextId()).thenReturn(10L);
}
}

When I run the test I get the following exception: java.lang.NullPointerException at com.some.api.some.package.dao.SomeDao.getNextId(SomeDao.java:13) ...

Later I want to add new classes to mock, and the getNextId method will be called inside one of them.

Thank you!

How to run jasmine tests from js script

Im making a javascript code playground, and want to test customers code using jasmine, that runs in vm.runInThisContext (or simply - eval).

I take user code + test code(it should be in jasmine)

const codeToEvaluate = localStorage.getItem("userCode") + this.props.testCode["testCode"]

And if user run his code, the code should pass the tests and log on my custom console error message if it will be

if (vm.runInThisContext(codeToEvaluate) === true) {
    this.log("Oh wow, you're not entirely hopeless after all. Good job.");
    this.unlockQuest();
}

Example

user code:

const userCode = "
const rectangle = {
    color: 'red',
    width:4,
    height:4,function isBlack(rectangle) {
    return rectangle.color == 'black';
}
}; 
function isBlack(rectangle) {
    return rectangle.color == 'black';
}"

test code:

const test = "
describe("quest1", function() { 

   it("should return true if it is black",function() { 
      expect(isBlack(rectangle)).toEqual(false); 
   }); 

});
"

dimanche 27 janvier 2019

Best programming languaje for me [on hold]

What is the best programming language to work offline, with all the documentation i need in my Hard drive? And i need good libraries to connect as e client with a web site, log in, and interact with it? Please someone tell me how can I tag this question? I'm just trying to choose the best language for this. thanks.

Jest mock module resolve with variable value

Assuming I have a module which returns a promise. I want to mock different outcomes of this promise to test the function where this module is part of. I mock the module like this:

jest.mock('../request', () => {
    return () => new Promise((resolve, reject) => {
        return resolve({
            response: { ok: true }
        });
    });
});

My first test is running

test('The function resolves', () => {
const initialState = { apiData: getState('postData', {}, 'ready', 'POST') };
const store: any = mockStore(initialState);
return expect(performApiRequest('postData/', {}, { data: 'json' }) (dispatch, () => store.getState())).resolves.toBeUndefined();
});

The problem is now with testing an other function where the value that resolves is supposed to be different, for instance {response: { ok: false } }.

I already tried different things. First wrapping the mock in a function and give the response as an argument. --> fails for mocks can't take out of scope variables.

I tried to call jest.doMock within the test but this does not trigger the request correctly.

I tried to do

`
    const mockResponse = jest.fn();
    jest.mock('../request', () => {
        return () => new Promise((resolve, reject) => {
            return resolve({
                mockResponse
            });
        });
     });`

And then call mockResponse.mockReturnValueOnce(value).

No success yet. Anybody sees a way out?

unit testing async express middleware

I have the following async middleware which uses multiple try-catches to check for the response of some http calls. I wish to unit test this middleware but am encountering difficulties mocking the "next" callback. When i wrap it like so:

it('should test for auth', () => {
    logon(req, res, function() {
        expect(res.locals).toBe(true)
    })
})

it does not seem to be actually running the function and running the expect after. Any ideas on how I can mock the request, response and next objects so I can test for the final values (res.locals)? Thanks.

async function logon(req, res, next) {

if (!req.query.isAuth)
    req.locals.auth = false;
    next()
}

try {
    const getData = await http.get(/logon);
    if (getData.status == 200) {
        res.locals.auth = true;
    } else {
        res.locals.auth = false;
        try {
            const secondCall = http.get(/logon2);
            if (secondCall.data.bob) {
                return res.redirect(/home);
            }
        } catch(e) {console.error(3)}
    }
} catch(e) {console.error(e)}
next();
}