mercredi 28 février 2018

Can Spectron, mocha, and chai assert that variables have a given state in an Electron-app?

How can we assert that a javascript-variable has some expected value in an electron-app? The current testing framework is spectron, mocha, chai, chai.should(), and chai.use(chaiAsPromised).

I want to assert that the value of the global variable foo has the value 'foo'. When I try foo.should.equal('foo') I get ReferenceError: foo is not defined at Context.<anonymous> (test\spec.js:63:28)

Is there a way to force an aetest instance to run on a particular port?

Say I have some test functions like the following:

func TestMyFunction1(t *testing.T) {

    inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
    if err != nil {
        t.Fatalf("Failed to create instance: %v", err)
    }
    defer inst.Close()

    req1, err := inst.NewRequest("GET", "http://localhost:8080/api/some-resource", nil)
    if err != nil {
        t.Fatalf("Failed to create req1: %v", err)
    }
    c1 := appengine.NewContext(req1)

    resp1, err := appClient.Do(req1)

    if err != nil {
        t.Fatalf("Failed to create resp1: %v", err)
    }

    t.Log(resp1)

    // Run code and tests with *http.Request req1
    // and context.Context c1.
    // ...
}

When I run tests like these with goapp test, it appears that an aetest instance is created on a unique, random port when each test is invoked:

INFO     2018-01-29 20:56:27,504 api_server.py:205] Starting API server at: http://localhost:37243
INFO     2018-01-29 20:56:27,510 dispatcher.py:197] Starting module "default" running at: http://localhost:42184
INFO     2018-01-29 20:56:27,510 admin_server.py:116] Starting admin server at: http://localhost:43292


--- FAIL: TestMyFunction1 (2.00s)



INFO     2018-01-29 21:06:58,717 api_server.py:205] Starting API server at: http://localhost:43010
INFO     2018-01-29 21:06:58,718 dispatcher.py:197] Starting module "default" running at: http://localhost:37508
INFO     2018-01-29 21:06:58,719 admin_server.py:116] Starting admin server at: http://localhost:45493

--- FAIL: TestMyFunction2 (1.99s)

Is there a way to force an aetest instance to run on a particular port? Alternatively, is there a way to predetermine the port? It seems that goapp test wraps dev_appserver.py (which is where one would normally specify the port), and I can't specify a port when running goapp test. There is also no port property on the aetest Options struct.

Test methods fail using Storage. Illuminate\Http\Testing\imagepng() in Laravel

Hello, I'm doing TDD to test my development, my tests were passing until I decided to reinstall php to repair the sqlite driver for testing (the main driver is mysql). So when I run my hole suite of tests this error shows in every method that uses the storage:

Error : Call to undefined function Illuminate\Http\Testing\imagepng()
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:46
 {laravel}/framework/src/Illuminate/Support/helpers.php:1038
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:49
 {laravel}/framework/src/Illuminate/Http/Testing/FileFactory.php:31
 {laravel}/tests/Feature/FacilityTest.php:38

This one is a method that throws the above error (the line 38 is signaled):

/**
 * @test
 * Test for: a Facility can be registered by an admin.
 */
public function a_facility_can_be_registered_by_an_admin()
{
    /** Given a correct information for a facility */
    \Storage::fake('public');

   // Next line is 38 the problematic one:
    $data = ["name" => "Facility A", 'image' => UploadedFile::fake()->image('facility-a.jpg')];

    /** When the request is made by an admin */
    $admin = $this->createUser([], 'admin');
    $response = $this->apiAs($admin, 'POST', '/api/v1/manage/facilities', $data);

    /** Then the facility should be registered */
    $response->assertStatus(Response::HTTP_CREATED);
}

I really don't know why.


If this helps, this is my phpunit file:

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="sqlite"/>
    </php>
</phpunit>


Thanks in advance.

Creating dependent test cases in Espresso Android

I have made a simple app that allows you to choose an option from a list of radio buttons and proceed to the next activity using the next button. I'm also using Espresso to test my app. My question is, how do I write test cases such that they are dependent on one another. Example - I want test case B to run only if test case A is successful. If A fails, I don't want B to get executed. Is this possible?

public class QuestionnaireTest {

@Rule
public ActivityTestRule<QuestionnaireActivity> testRule = new ActivityTestRule<>(QuestionnaireActivity.class);

@Test //Test Case A
public void testDeviceDisplayed() {
    onView(withId(R.id.btnDevice2)).perform(click());
    }

@Test //Test Case B
public void testDeviceChecked(){
    onView(withId(R.id.btnDevice2)).check(matches(isChecked()));
    }
}

getting started with JUnit

Hi I am starting to learn junit but i Have following issues

C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
TestJunit.java:1: error: package org.junit does not exist
import org.junit.Test;
            ^
TestJunit.java:2: error: package org.junit does not exist
import static org.junit.Assert.assertEquals;
                   ^
TestJunit.java:2: error: static import only from classes and interfaces
import static org.junit.Assert.assertEquals;
^
TestRunner.java:1: error: package org.junit.runner does not exist
import org.junit.runner.JUnitCore;
                   ^
TestRunner.java:2: error: package org.junit.runner does not exist
import org.junit.runner.Result;
                   ^
TestRunner.java:3: error: package org.junit.runner.notification does not 
exist
import org.junit.runner.notification.Failure;
                                ^
TestJunit.java:4: error: cannot find symbol
@Test
^
symbol:   class Test
location: class TestJunit
TestJunit.java:7: error: cannot find symbol
assertEquals("Junit is working fine",str);
    ^
symbol:   method assertEquals(String,String)
location: class TestJunit
TestRunner.java:6: error: cannot find symbol
Result result = JUnitCore.runClasses(TestJunit.class);
    ^
symbol:   class Result
location: class TestRunner
TestRunner.java:6: error: cannot find symbol
Result result = JUnitCore.runClasses(TestJunit.class);
                    ^
symbol:   variable JUnitCore
location: class TestRunner
TestRunner.java:7: error: cannot find symbol
for (Failure failure : result.getFailures()) {
         ^
symbol:   class Failure
location: class TestRunner
11 errors

Source of learning: https://www.tutorialspoint.com/junit/junit_environment_setup.htm

I have the path:

%JUNIT_HOME%\junit-4.12

added to Path. and the system variable

JUNIT_HOME | C:\JUNIT\

Could not load TestContextBootstrapper

I have problem with my test using spring SpringRunner with the following exception:

java.lang.IllegalStateException: Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available.

at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:145)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:142)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: java.lang.NoSuchMethodError: org.springframework.util.Assert.state(ZLjava/util/function/Supplier;)V
at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:157)
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:128)
... 17 more

this is my pom.xml

<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>
    <!--dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>RELEASE</version>
    </dependency-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.4.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.4.RELEASE</version>
    </dependency>


</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

this is my class test with annotation:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ContextConfiguration(locations = {"classpath:application-context.xml"})
@ActiveProfiles("mock")
public class TpmControllerTests {

@Autowired
MockMvc mockMvc;

@Test
public void callForGatewayRegistry() throws Exception {
    GatewayRegistryAccess gatewayRegistryAccess = new GatewayRegistryAccess();
    GatewayRegistry gatewayRegistry = gatewayRegistryAccess.getById("1234GatewayId");
    Assert.assertEquals(gatewayRegistry.getGatewayUrl(), "http://localhost:8080");
}

Can I skip the bootstrapping context with no using of application-context.xml? Is it a dependency problem? Thank you!

Using selenium 3.0 with jdk1.8 and selenium webdriver beta version

List findElement = (List) driver.findElement(By.tagName("a")); List links = findElement;

            System.out.println(links.size());

            for (int i = 1; i<=links.size(); i=i+1)

            {

                System.out.println(links.get(i).getText());

            }  

When i am trying to run this code, it is showing some issues Exception in thread "main" java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.List at Home_Screen.Home.main(Home.java:60) I am running this for selenium webdriver 3.0 using google chrome

Mock function outside package

I'm developing a Django software with different apps on it. I'm testing some views and I want to mock the return of a function inside these views.

For example I have this view (located at apps.policies.views):

def upload_policy_document(request):

    # code fragment avoid

    # save document ot ipfs
    response_data = save_to_ipfs(app_name=app_name,
                                 process_instance=process_instance,
                                 file=policy_document)
    # more code avoided

    return JsonResponse(data=response_data)

The function save_to_ipfs is located at apps.utils.ipfs_storage and is the function I want to mock to return a fixed value without connecting to the IPFS.

I have some tests of this view located at apps.policies.tests.test_views. As a test example I have:

class UpdatePolicyDocumentMockCase(SimpleTestCase):

    IPFS_JSON_MOCK = {"Hash": "mockhash"}

    def setUp(self):
        # some setup before tests

    @patch('apps.utils.ipfs_storage.save_to_ipfs')
    def some_test(self, mock_method):

        mock_method.return_value = self.IPFS_JSON_MOCK
        self.assertEqual(save_to_ipfs("", "", ""), self.IPFS_JSON_MOCK)

The problem is that the mock doesn't work and it returns empty when the reurn must be the content of self.IPFS_JSON_MOCK.

I hope I've explained correctly, thanks in advance!

what's a PAC Test for a Quality / Business Analyst?

I am about to attend a PAC test for a QA/BA position, but I have no idea what it is. Could someone enlighten me on this, please?

Visual Studio 2017 is preparing tests longer than expected

From one moment (not fixed when it happened, probably, when I moved some test projects to another folder on disk) Visual Studio is taking longer than expected when I open Test Explorer and want to run tests. It takes minutes like this:

enter image description here

Why it happened and how to fix it?

How to disable test mode?

How i can disable this mode? Hide that right red blocks..enter image description here

What to do before testing an app

I am interested in testing a project in Angular 5. I have very beggining knowledges in Angular and I am able to understand more or less the project but i you tell me to develop something in Angular I won´t be able to.

My question is to test this project do I need to know very well Angular, or it is sufficient to learn about testing but nt very much about Angular?

Thanks,

Planned Exploratory Test Charters - Categorisation in JIRA

I've created a number of these over time documenting the testing of various major features, and at the moment they are all under a single 'Task' in JIRA which is a bit messy, but very easy to find as they're always in one place.

However, should these really be linked to each Story they test, or under a separate 'Requirements Trace' linked to that story?

Thank you.

Simple test bench in vhdl with generic

I have very simple 'program' written in VHDL

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std;


entity Xand is
    generic(width   : integer:=8);
    port(   clk : in std_logic;
        A,B : in std_logic_vector(width-1 downto 0);
        C   : out std_logic_vector(width-1 downto 0)
    );
end Xand;

architecture Behavioral of Xand is
begin
    C<= A and B;
end Behavioral;

and one test bench for it, where i have to use generic:

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
use ieee.numeric_std.all;

ENTITY Xand_tb IS

END Xand_tb;

ARCHITECTURE behavior OF Xand_tb IS 

    COMPONENT Xand IS
        generic(width   : integer);
        port(   clk : in std_logic;
            A,B : in std_logic_vector(width-1 downto 0);
            C   : out std_logic_vector(width-1 downto 0)
        );
    end COMPONENT;

    signal width : integer := 8;

   -- inputs
   signal clk : std_logic := '0';
   signal A, B : std_logic_vector(width-1 downto 0);

   --Outputs
   signal C : std_logic_vector(width-1 downto 0);

   constant period : time := 10 ns;

BEGIN

    -- instantiate the Unit Under Test (UUT)
   uut: Xand generic map (width => 8)
        PORT MAP (
          clk => clk,
          A => A,
          B => B,
          C => C
        );

END;

Sadly I'm not sure how to write test, which i can later watch in gtkwave for my unit using generic parameter width. Well written test that will make for an example to another tests would be great.

Tools to automate server performance capturing and report it on dash board

Please let me know if there is any tool for the below performance load test

Capture CPU, Memory, Disk utilization of servers during the load test period ( 2 hours) and report it in a graph format.

Thank You

RestAssured - assert body when response is a text/plain

In the controller I return ResponseEntity with body as a String:

    @RequestMapping(path = "/message", method = RequestMethod.POST)
    public ResponseEntity<String> sendMessage(){
        return new ResponseEntity<>("message sent", HttpStatus.OK);
    }

The response happens to be a text/plain. When I test it using RestAssured, I do:

    RestAssured
            .given()
            .when()
            .post(URL + "/message")
            .then()
            .assertThat()
            .statusCode(200)
            .contentType("text/plain")
            .body(Matchers.is("message sent"));

Test fails with this message:

Expected: is "message sent"
Actual: message sent

Does anyone has idea how can I get rid of " " or parse String to text/plain? I also tried using other Hamcrest Matchers but none of them worked for me.

Testing whether a webhook route is called in Laravel

I've developed a package that creates a route to listen for SNS webhooks, and I would like to add some tests to ensure that it works properly.

I am stuck on being able to detect if a specific route (the webhook receiver) is called while running the testsuite.

The Laravel documentation describes how to test your own routes through $this->get('/'), but the webhook situation is different as it is being requested by an external service.

Another question has been asked that is similar but differs in that the question asks about calling the route through Guzzle.

Create test hierarchy with @TestFactory

I'm using the Junit 5 annotation @TestFactory to generate several tests like this :

@TestFactory
public Collection<DynamicTest> myTest() throws IOException {
    return fetchSomeTests().stream()
            .map(test -> {
                return dynamicTest(test.get("testDescription"), () -> doMyTest(test));
    }).collect(Collectors.toList());
}

Is it possible to organize generated tests in groups, just like when you use different classes of @Test ?

Iterate Element in Nightwatch

I would like to iterate the xpath element and compare the string. The xpath element has similar format.

for (var i = 0; i < jsonObj.Sheet1.length ;++i) { 
 selector = new String('//*[@id="SearchListGridView_DXDataRow' + i + '"]/td[4]');
 browser.expect.element(selector).text.to.contain(jsonObj.Sheet1[i].Account)
} 

But return me error saying text is not element. Please help on this.

Workaround for parameters, that can be set only once in system while creating tests in Selenium Webdriver

I have little problem with creating functional tests in my application. In this app we have few parameters that can be set only once, after setting it i cannot turn of new functionality. The main problem is that before turning on this parameter on interface some of processes may work different, than after checking it. Notice, that there is few parameters like this, so i have big problem with creating tests that must check every single configuration of this parameters.

Also there is one more condition for my test framework, that there must be at least 4 tests that are running in the same time (parallelism), so even if i solve problem with making good order of tests or making some backups/snapshots of database in choosen moments there is a chance, that tests may start restoring database to choosen moment while another tests is running or working on specified configuration.

Did anyone of you faced with problem like that? Any suggestions that may give me a little help will be appreciated.

Regards.

mardi 27 février 2018

Is it possible to open a screen directly in XCUITest?

I have 3 screens, lets say,

  1. Login
  2. Forgot Password
  3. Help screen

By default the Login screen open when the app starts. The Forgot Password screen is shown when you click on the Forgot Password button, and Help Screen opens when the Help link is clicked.

Can I somehow open the the Forgot Password Screen directly without going through the procedure of clicking the button using XCUITest?

I am suggesting something in the same lines as passing an adb intent to open a View directly.

How to set up test environment web development

Hi I am learning Django and very new to web development and programming in general.

I have seen people using 2-3 environments/subdomain I am not sure what it is called.

For example if website is www.mydomain.com, one would be using www.qa.mydomin.com or www.test.mydomain.com.

are thse envoirnment/subdomain are mapped to server with single ip address or are they different servers. Is it possible to map them to single server.

It'd be great if someone could explain this in context of Django and digital ocean droplet server.

Ionic 3 - Angular when import TestBed get Error : afterAll\nUncaught

I'm working on an Ionic 3 App and I have a problem when I want to use TestBed class. I use these commands to create the project.

ionic start myApp tabs
npm install karma-cli -g
npm install karma --save-dev
npm install jasmine --save-dev
npm install karma-jasmine --save-dev
npm install @types/jasmine --save-dev
npm install jasmine-core --save-dev
npm install ts-node --save-dev
npm install angular-cli --save-dev

I use karma to create this karma.conf.js :

module.exports = function(config) {
  config.set({
    basePath: '',

    frameworks: ['jasmine'],

    files: [
      'src/**/*Spec.js'
    ],

    exclude: [
    ],

    preprocessors: {
    },

    reporters: ['progress'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity
  })
}

I create the src/app/pages/home/homeSpec.js file with this content :

import { TestBed } from '@angular/core';

describe("some tests", () => {

  it("Vrai", function () {
    expect(true).toEqual(true);
  });

});

I get the following output when I use karma start :

------------------- without TestBed import ----------------
27 02 2018 23:45:55.793:WARN [karma]: No captured browser, open http://localhost:9876/
27 02 2018 23:45:55.807:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
27 02 2018 23:45:55.808:INFO [launcher]: Launching browser Chrome with unlimited concurrency
27 02 2018 23:45:55.812:INFO [launcher]: Starting browser Chrome
27 02 2018 23:45:57.600:INFO [Chrome 64.0.3282 (Mac OS X 10.13.3)]: Connected on socket ysC5F7d28isYt8oAAAAA with id 47800734
Chrome 64.0.3282 (Mac OS X 10.13.3): Executed 1 of 1 SUCCESS (0.002 secs / 0 secs)

------------------- with TestBed import ----------------
27 02 2018 23:46:04.564:INFO [watcher]: Changed file "/Volumes/JedemaKey/ionic_book/Chapitres/ionic/testtest/myApp/src/pages/home/homeSpec.js".
Chrome 64.0.3282 (Mac OS X 10.13.3) ERROR
  {
    "message": "An error was thrown in afterAll\nUncaught SyntaxError: Unexpected token {",
    "str": "An error was thrown in afterAll\nUncaught SyntaxError: Unexpected token {"
  }
Chrome 64.0.3282 (Mac OS X 10.13.3): Executed 0 of 0 ERROR (0.018 secs / 0 secs)

Why I get this error ? How can I import TestBed class ?

Test Boolean Values in python with single output value

I have a list which has different Boolean values.

x = [True, True, True, True, False, False, True, False]

i want to check that if there is any value in the list is "False" then I want a final output value to be "True". If there is no "False" or all "True" value then the final output will be "False".

Something like this,

#x has False value 
#>>> a = True (a is a variable)
# x doesn't have False or all True
#>>> a = False

Please help!

Eager load in JPA @Transactional test

I am trying to do a test where the data from one entity is loaded eager, so I have a code like the following:

Entity:

@Entity
@Table(name = "tableA")
@NamedEntityGraph(name = "tableA.tableB", attributeNodes = [NamedAttributeNode("tableB")])
class TableA (

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int = 0,

    @JoinColumn(name = "table_b_id", referencedColumnName = "id")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    var tableB: TableB? = null
)

Repository:

@Repository
interface tableARepository: JpaRepository<TableA, Int>, JpaSpecificationExecutor<TableA>{

    @EntityGraph(attributePaths = [ "tableB" ])
    fun findByModelId(modelId: Int) : List<DispersionDetail>
}

Test:

@Test
@Transactional
fun disperserTest(){
    //Here the code to create a tableA and the tableB
    val tableAList = tableARepository.findAll()
}

The problem is that when debug my code the result of the tableAList the attribute tableB is null but when delete the @Transactional annotation from the test then tableB is not null and is loaded eager just how I want.

My question is why this happened and how can load tableA with all his relations (tableB) with the @Transactional annotation in the test

JavaFX & TestFX

I have already gone through the limited documentation and examples that are provided but I am unsure how to carry out basic tests.

Tests such as checking how many components are contained in a ScollPane, what the labels of the different tabs are etc.

How can I carry out tests like the ones I've listed above? Are there any good extensive TestFX examples that I can look into?

Set a variable based on a py.test (testinfra) check output

I am trying to make a testinfra test file more portable, I'd like to use a single file to handle tests for either a prod / dev or test env. For this I need to get a value from the remote tested machine, which I get by :

def test_ACD_GRAIN(host):
    grain = host.salt("grains.item", "client_NAME")
    assert grain['client_NAME'] == "test"

I'd need to use this grain['client_NAME'] value in different part of the test file, therefore I'd like to store it in a variable.

Anyway to do this ?

Issues with system test setup using Capybara and Selenium on existing Rails 5.1 app

I'm attempting to set up system tests with Capybara and Selenium on an existing Rails 5.1 app that already had capybara based feature tests. Here's what I've done so far.

In the gem file under group :development, :test:

gem 'chromedriver-helper'  
gem 'selenium-webdriver'
gem 'rack_session_access'

In the environments/development.rb and environments/test.rb:

config.action_mailer.default_url_options = { host: 'localhost:3000' } 

In the spec\rails_helper.rb:

Capybara.register_driver :selenium do |app|
  Capybara::Selenium::Driver.new(app, browser: :chrome)
end

Capybara.configure do |config|
  config.default_max_wait_time = 10 # seconds
  config.default_driver = :selenium
  config.app_host = 'http://localhost:3000'
  config.server_host = 'localhost'
end

The issues I'm having are both with new systems tests and old feature tests.

With the system tests it appears that Capybara isn't creating a page object as I get undefined local variable or method 'page' Additionally when I duplicate the same test under the feature test directory I don't have this issue.

With the old Capybara feature tests, working with the rackTest driver, a Chrome window opens but I get No route matches [GET] "/rack_session/edit"

config.middleware.use RackSessionAccess::Middleware is already present in the environments/test.rb

Example system test:

require 'rails_helper'

describe User do
  let(:user) { create :user }
  let(:membership) { create :membership, admin: true}
  let(:admin) { create :user, memberships: [membership] }

  context 'viewing the index' do
    it 'directs you to the appropriate page' do
      set_current_user(admin)
      visit root_url
      click_button 'Manage Users'
      expect(page.current_url).to end_with users_path
      expect(page).to have_selector 'h1', text: 'Users'
    end
  end
end

Example feature test:

require 'rails_helper'

describe 'edit an assignment' do
  let(:roster) { create :roster }
  let(:user) { create :user, rosters: [roster] }
  before :each do
    Timecop.freeze Date.new(2018, 1, 10)
    set_current_user(user)
  end
  after :each do
    Timecop.return
  end

  context 'returns the user to the appropriate index page' do
    let(:date_today) { Date.new(2017, 4, 4) }
    let(:start_date) { Date.new(2017, 3, 31) }
    let(:month_date) { date_today.beginning_of_month }
    it 'redirects to the correct URL' do
      visit roster_assignments_url(roster, date: date_today)
      visit new_roster_assignment_url(roster, date: start_date)
      click_button 'Create'
      expect(current_url)
        .to eq roster_assignments_url(roster,
                                      date: month_date)
    end

In the spec_helper:

def set_current_user(user)
  page.set_rack_session user_id: user.id
end

Dynamically set a XML tag value

I am trying automate testing using Karate.

I have a XML payload.

I have a static XML payload which I am readying from a file and I want to call my service in loop.

For each call I would like to replace value for a tag name dynamically.

How would I achieve this?

e.g.

Below is my Main Feature which calls my common feature in loop

Feature: Loop Call
Background:
* def common = call read('classpath:CommonFeatures.feature')

Scenario:
* table table
    | payload_file    | field_tag  | field_value |
    | 'HappyPath.xml' | 'car_fuel' | 'Gas'     |
    | 'HappyPath.xml' | 'car_color'| 'Red'     |

* def response = call read('classpath:Car.feature')  table

Car.feature

Feature: Common
Scenario:
    * print payload_file
    * print field_tag
    * print field_value
    * xml payload = read('classpath:/payload/'+payload_file)
    * print payload
    * set payload/$field_tag = field_value

This is where I have issue setting the field_tag value.

I have other option to do this like writing a small java script method to replace the tag value or a small java class which use DOMParser or SAXParser to perform the same.

However I would like to know if there is any karate in build way to perform the same.

Also while using java script method to replace the tag value if I am using var parser = new DOMParser(); and it seems DOMParser is not available to use. Is there a way to make this available?

Ruby On Rails testing User Model with RSpec - password and password_confirmation doesn't work properly

it's my first post. I start to learn Ruby and Ruby On Rails framework.

I want to test User Model with RSpec and i have problem with pass validation of password and password_confirmation.

Code: https://github.com/paw3lgora/gCMS/blob/master/spec/models/user_spec.rb

I have problem with line: it { should validate_confirmation_of(:password) }

I don't wanna use devise gem or has_secure_password method from BCrypt because i learn Ruby and I want to implement my authentcation systems from scratch and add Argon2 in the future.

This give me error like:

1) User validation password should validate that :password_confirmation matches :password Failure/Error: it { should validate_confirmation_of(:password) }

   User did not properly validate that :password_confirmation matches
   :password.
     After setting :password_confirmation to ‹"some value"›, then setting
     :password to ‹"different value"›, the matcher expected the User to be
     invalid and to produce the validation error "doesn't match Password"
     on :password_confirmation. The record was indeed invalid, but it
     produced these validation errors instead:

     * name: ["Nazwa użytkownika nie może być pusta.", "Nazwa użytkownika
       jest za krótka. Minimum 2 znaki."]
     * email: ["Nie podałeś emaila.", "Email jest za krótki. Minimum 5
       znaków.", "Podałeś złą nazwę użytkownika."]
     * password_confirmation: ["Hasła nie pasują do siebie."]
 # ./spec/models/user_spec.rb:27:in `block (4 levels) in <top (required)>'

Help me guys! :)

Simulate random connection problems (web app testing)

I'm trying to debug a problem that is possibly caused by random internet connection interruptions during making multiple AJAX requests, but it's impossible to pinpoint the exact place that causes trouble. In Chrome dev tools you can toggle "Offline" checkbox to simulate no internet connection, but you need to do this manually. Is there any tool that would allow me to either cause the connection to turn on and off randomly or to define programmatically when to turn it on and off (e.g. at some interval)?

Difference between Behaviour-driven development (BDD) and Behaviour-Driven Testing (BDT)

I am looking into different software testing techniques and I have come across Behaviour-Driven Testing (BDT) and from what I understood is that it’s just the testing aspect of BDD and can be used without the BDD.

But when I started looking into Behaviour-driven development (BDD), I’ve noticed that everyone seems to angle it as a software testing technique rather than a software development process.

So I have two following questions:

1 - Is there such thing as Behaviour-Driven Testing (BDT) in practice?

1.1 - If YES - Is there any difference between BDD and BDT?

1.2 - If NO - would you classify BDD as a software testing technique?

Here is some of the information I have been reading on BDT:

http://www.womentesters.com/behaviour-driven-testing-an-introduction/ http://ithare.com/bdt-automating-your-application-testing-in-behavior-driven-way/ https://www.infostretch.com/blog/automated-testing-using-bdt-behavior-driven-testing/ http://testoptimal.com/tutorials/BDT_IDE.html#/3 http://www.cyreath.co.uk/papers/Cyreath_An_Introduction_to_BDT.pdf https://www.thoughtworks.com/insights/blog/build-right-regression-suite-using-behavior-driven-testing-bdt

Jest runs no tests with React application

I have the following simple test in a t.test.js file in my React repo

test('sum', () => {
  expect(1+1).toBe(3);
});

I followed the steps to set up Jest using the official guide.

However, when I run npm test, nothing happens. This is the output I get before Jest exits:

> @ test
> jest

Using Jest CLI v0.8.2, jasmine1

What could be the problem? No tests are being run in my repository. Here is a dump of my package.json if necessary:

{
  "private": true,
  "engines": {
    "node": ">=5.0 <6",
    "npm": ">=3.3 <4"
  },
  "dependencies": {
    "@google/maps": "^0.4.5",
    "auth0-lock": "^10.24.3",
    "autosuggest-highlight": "^3.1.1",
    "aws-sdk": "^2.202.0",
    "babel-polyfill": "6.9.1",
    "babel-runtime": "6.9.2",
    "bluebird": "3.1.1",
    "body-parser": "^1.18.2",
    "classnames": "2.2.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.3",
    "cron": "^1.3.0",
    "dotenv": "^2.0.0",
    "downloadjs": "^1.4.7",
    "eventemitter3": "1.1.1",
    "express": "4.13.3",
    "express-formidable": "^1.0.0",
    "express-jwt": "^5.1.0",
    "fastclick": "1.0.6",
    "fbjs": "0.5.1",
    "fetch-jsonp": "^1.1.3",
    "flux": "2.1.1",
    "formsy-react": "^0.19.5",
    "front-matter": "2.0.1",
    "fuse.js": "^2.5.0",
    "google-libphonenumber": "^3.0.12",
    "google-map-react": "^0.27.0",
    "google-maps-react": "^1.1.2",
    "history": "1.16.0",
    "intercom-client": "^2.9.2",
    "isomorphic-style-loader": "^4.0.0",
    "jade": "1.11.0",
    "json-loader": "^0.5.7",
    "mailchimp-api-v3": "^1.8.0",
    "markdown": "^0.5.0",
    "mixpanel": "^0.8.0",
    "mixpanel-browser": "^2.17.1",
    "moment": "^2.20.1",
    "moment-timezone": "^0.5.14",
    "mongodb": "2.1.7",
    "morgan": "^1.9.0",
    "node-fetch": "1.3.3",
    "normalize.css": "3.0.3",
    "passport-auth0": "^0.6.1",
    "passport-http": "^0.3.0",
    "rc-progress": "^2.2.5",
    "react": "^0.14.9",
    "react-addons-create-fragment": "^0.14.8",
    "react-autosuggest": "^9.3.4",
    "react-day-picker": "^2.4.0",
    "react-dom": "^0.14.9",
    "react-redux": "^4.4.1",
    "react-routing": "0.0.6",
    "react-scrollable-anchor": "^0.5.0",
    "react-share": "^1.19.1",
    "react-stripe-checkout": "^1.8.0",
    "redux": "^3.3.1",
    "sendgrid": "^2.0.0",
    "source-map-support": "0.4.0",
    "stripe": "^4.25.0",
    "tempy": "^0.2.1",
    "twilio": "^2.9.1",
    "twitter": "^1.7.0",
    "underscore": "^1.8.3",
    "whatwg-fetch": "0.10.1",
    "xhr2": "^0.1.3"
  },
  "devDependencies": {
    "assets-webpack-plugin": "^3.4.0",
    "autoprefixer": "^6.1.2",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-eslint": "^6.0.4",
    "babel-jest": "^22.4.1",
    "babel-loader": "^6.2.4",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-rewire": "^1.0.0-rc-3",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-react-constant-elements": "^6.8.0",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-react-remove-prop-types": "^0.2.7",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-node5": "^11.1.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.26.0",
    "babel-template": "^6.26.0",
    "babel-types": "^6.26.0",
    "browser-sync": "^2.23.6",
    "css-loader": "^0.28.10",
    "csscomb": "^3.1.8",
    "del": "^2.2.0",
    "eslint": "^1.10.3",
    "eslint-config-airbnb": "^2.1.1",
    "eslint-loader": "^1.1.1",
    "eslint-plugin-react": "^3.11.3",
    "extend": "^3.0.0",
    "file-loader": "^0.8.5",
    "gaze": "^0.5.2",
    "git-repository": "^0.1.1",
    "glob": "^6.0.1",
    "jest": "^22.4.2",
    "jest-cli": "^0.8.2",
    "jscs": "^2.7.0",
    "mkdirp": "^0.5.1",
    "ncp": "^2.0.0",
    "postcss": "^5.2.18",
    "postcss-import": "^7.1.3",
    "postcss-loader": "^0.8.0",
    "precss": "^1.3.0",
    "react-test-renderer": "^16.2.0",
    "react-transform-catch-errors": "^1.0.0",
    "react-transform-hmr": "^1.0.1",
    "redbox-react": "1.2.0",
    "replace": "^0.3.0",
    "superagent": "^3.8.2",
    "supertest": "^3.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.0",
    "webpack-hot-middleware": "^2.21.0",
    "webpack-middleware": "^1.5.1",
    "webpack-node-externals": "^1.6.0"
  },
  "babel": {
    "presets": [
      "react",
      "node5",
      "stage-0"
    ],
    "env": {
      "test": {
        "plugins": [
          "rewire"
        ]
      }
    },
    "plugins": [
      "transform-class-properties"
    ]
  },
  "jest": {
    "rootDir": "./src"
  },
  "scripts": {
    "lint": "eslint src tools && jscs src tools",
    "csslint": "csscomb src/components --lint --verbose",
    "csscomb": "csscomb src/components --verbose",
    "test": "jest",
    "clean": "babel-node tools/run clean",
    "copy": "babel-node tools/run copy",
    "bundle": "babel-node tools/run bundle",
    "build": "babel-node tools/run build",
    "deploy": "babel-node tools/run deploy",
    "start": "babel-node tools/run start"
  }
}

Spring MockMvc testing with Java based config

I am using MockMvc for testing web application, but have faced with some issues.

When I tried to run simple request without getting any bean from appContext it works perfect, but for example get bean of password encoder from appContext - returns null. So, how can I load my beans to application context?

LoginTest.class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class LoginTest {

private static String user = "bla@bla.com";
private static String pass = "bla";
private static String source = "API";

private MockMvc mockMvc;

@Before
public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(new AuthController()).build();
}

@Test
public void requestScope() throws CustomException {
    try {
        mockMvc.perform(post("/getToken").contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .content(EntityUtils.toString(new UrlEncodedFormEntity(Arrays.<BasicNameValuePair>asList(
                        new BasicNameValuePair("email", user),
                        new BasicNameValuePair("password", pass),
                        new BasicNameValuePair("source", source),
                        new BasicNameValuePair("redirect", "/")
                ))))).andExpect(status().isOk());
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

}

My console output:

    org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1303)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:977)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:160)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at LoginTest.requestScope(LoginTest.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.ExceptionInInitializerError
    at main.java.controller.AuthController.getToken(AuthController.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    ... 41 more
Caused by: java.lang.NullPointerException
    at main.java.service.context.ApplicationContextService.getBean(ApplicationContextService.java:30)
    at main.java.conf.TokenAuthenticationService.<clinit>(TokenAuthenticationService.java:31)
    ... 53 more

AuthController.class

@Controller
@RequestMapping("/")
public class AuthController {

    private static JWTConfig config = ConfigService.get().getJWTConfig();
    private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();

    // Get a new JWT token for a given email/password
    @RequestMapping(value = "/getToken", method = RequestMethod.POST)
    @ResponseBody
    public String getToken(
            @RequestParam(value = "email") String user,
            @RequestParam String password,
            @RequestParam String source,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String jwtAuthToken = TokenAuthenticationService.getAuthToken(user, password, source);
            if (source.equals("web")) {
                response.addCookie(new Cookie(config.cookiesString, jwtAuthToken));
            } else {
                response.addHeader(config.headerString, config.tokenPrefix + " " + jwtAuthToken);
            }
            JsonObject jwtData = new JsonObject();
            jwtData.addProperty("jwt", jwtAuthToken);
            return gson.toJson(jwtData);
        } catch (Exception e) {
            return Logger.getExceptionJsonResponse("[AuthController] Exception in getToken method.", e, response);
        }
    }
}

TokenAuthenticationService

public class TokenAuthenticationService {

    private static JWTConfig config = ConfigService.get().getJWTConfig();
//    private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private static PasswordEncoder passwordEncoder = ApplicationContextService.getBean(PasswordEncoder.class);

    public static String getAuthToken(String username, String password, String source) throws Jp3Exception {
        User user = new UserServiceImpl().getUserByEmail(username, true);
        if (user == null) {
            String message = "Wrong username.";
            JP3Logger.info("[TokenAuthenticationService] Cannot create auth token for user `" + username + "`.");
            throw new Jp3Exception(message);
        }
        if (!passwordEncoder.matches(password, user.getPassword())) {
            String message = "Wrong user password.";
            JP3Logger.info("[TokenAuthenticationService] Cannot create auth token for user `" + username + "`.");
            throw new Jp3Exception(message);
        }
        UUID jwtId = UUID.randomUUID();
        String sub = getSubject(source);
        // Expiration date equals null if expiration time would be null
        Date exp = config.expirationTime != null ? new Date(System.currentTimeMillis() + config.expirationTime) : null;
        String permissions = new UserManagementServiceImpl().getUserPermissions(user.getId(), false).toString();
        permissions = permissions.replace("{", "[").replace("}", "]").replaceAll("\"", "");
        String jwt = Jwts.builder().setIssuer(config.issuer).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(exp)
                .claim("jwtid", jwtId).setSubject(sub)
                .claim("_id", user.getId())
                .claim("email", user.getUsername())
                .claim("permissions", permissions)
                .signWith(SignatureAlgorithm.HS256, config.secret).compact();

        //Add user to Spring Security Context Holder
        //UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, password, Collections.emptyList());
        //Authentication auth = authenticationManager.authenticate(authToken);
        //SecurityContextHolder.getContext().setAuthentication(auth);

        return jwt;
    }

ApplicationContextService

public class ApplicationContextService implements ApplicationContextAware {

    private static ApplicationContext appContext;
    private static long lastFailedDbConnectTime = 0;
    private static long checkConnectionTimeframe = 1000 * 30;// 1 min frame before the next check

    public static ApplicationContext getApplicationContext() {
        return appContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appContext = applicationContext;
    }

    public static void setApplicationContextStatic(ApplicationContext ac) {
        appContext = ac;
    }

    public static <T> T getBean(Class<T> clazz) {
        return appContext.getBean(clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanId) {
        return (T) appContext.getBean(beanId);
    }

   public static boolean isMainDataBaseAvailable() {
        try {
            if ((System.currentTimeMillis() - lastFailedDbConnectTime) < checkConnectionTimeframe) {
                return false;
            }
            HikariDataSource hikariCPMain = (HikariDataSource) appContext.getBean("HikariCPMain");
            long timeout = hikariCPMain.getConnectionTimeout();
            hikariCPMain.setConnectionTimeout(9500);
            hikariCPMain.getConnection().close();
            hikariCPMain.setConnectionTimeout(timeout);//restore default DB timeout
            return true;
        } catch (Exception e) {
            JP3Logger.error("[ApplicationContextService] Exception in isMainDataBaseAvailable method. Cannot connect to main database.", e, false);
            //HikariDataSource hikariCPAlternative = (HikariDataSource) appContext.getBean("HikariCPAlternative");
            lastFailedDbConnectTime = System.currentTimeMillis();
            return false;
        }
    }

    public static HikariDataSource getHikariDataSource() {
        return (HikariDataSource) appContext.getBean(ApplicationContextService.isMainDataBaseAvailable() ? "HikariCPMain" : "HikariCPAlternative");
    }

Seems that application context doesn`t have proper beans, or even equal null. Please help me, I am stuck with it.

how to develop graphics benchmarking app using opengl?

I know some basic opengl and have made basic simulations like house, teapot etc. What are the blogs, books or videos that go into detail about how to develop benchmarking apps using c++. The best way to test them. Do I need to use any kind of automation tool like jenkins for testing ?

kotlin: how to inherit from Spek class

I want to have a common fixture for my tests:

@RunWith(JUnitPlatform::class)
abstract class BaseSpek: Spek({

    beforeGroup {println("before")}

    afterGroup {println("after")}
})

and now I want to use that spec:

class MySpek: BaseSpek({
    it("should xxx") {}
})

but i got compilation error due to no-arg BaseSpek constructor. what's the correct way of achieving what i need?

Is the "voter" in n-version programming a person or a function in a code?

I've been reading about N-version programming for my reporting in class. From what I learned on the slides, NVP is based on the principle of design diversity, that is coding a software module by different teams ofprogrammers, to have multiple versions.

Is the "voter" a person who judges the algorithm made by different teams or a method/function that chooses the best one that provide better software reliability?

Image here: N-version programming

Mock an interface instantiation in a function call argument list with phpunit

I'm bit new to phpunit .I was trying to cover this function .

public function add(AddressInterface $address) : array
{
    $this->data[] = $address;
    return $this->data;
}

My test function is as follows

public function testAdd()
{
    $collection = new AddressCollection();
    $collection->add($this->createMock(AddressInterface::class));
}

and the namespaces are same. But whenever I try running the phpunit , I'm getting this error . TypeError: Argument 1 passed to ValidateAddress\Model\AddressCollection::add() must be an instance of AddressInterface, instance of Mock_AddressInterface_65a1b00b given, called in validateaddress/tests/Model/AddressCollectionTest.php

Any idea why this is happening? The mocked instance cannot replace the instance of AddressInterface in original add() function version. Any help is appreciated!

How to determine if a ZPL II label has been produced based on the requested DPI

Overview
I need to verify that the label I have requested when also submitting the specific DPI, has returned a label in the same DPI.

So for example:
I want a label which is 300dpi. I send my request and the code for the ZPL II is returned. How can I now verify that this code for the label is for a 300 dpi label please?

Testing android app. Trying to mock getSystemService.

Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually. We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before.

The method I'm trying to test:

public boolean isGPSEnabled()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return GPSEnabled;
}

This method checks if the android device got the GPS enabled and returns true if it is, false if not. I'm trying to mock the LocationManager and the Context, and this is what I have so far:

@RunWith(MockitoJUnitRunner.class)

public class IsGPSEnabledTest
{

    @Mock
    LocationManager locationManagerMock = mock(LocationManager.class);
    MockContext contextMock = mock(MockContext.class);

    @Test
    public void testGPSEnabledTrue() throws Exception
    {
        when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock);
        when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);        

        MapsActivity activity = new MapsActivity();
        assertEquals(true, activity.isGPSEnabled());
    }
}

When I run this test I get this error:

"java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked."

Any help on this would be appreciated.

Angular Excluding External Tests

I have an Angular project in a Git repository, which has a Git Submodule which has its own Typescript tests (à la xyz.spec.ts). The Submodule is in /src/external/[submodules]

When I run npm test, I get an error that it cannot find mocha, etc, to run the tests for the submodule.

So after much googling and testing, I added
"exclude": ["external"] to my src/tsconfig.spec.json
and

"test": {
    "codeCoverage" : {
      "exclude" : ["src/external/**/*"]
    },
    ...
  }

to .angular-cli.json

Now when I test I get:

WARNING in ./src/external/api/src/api/models/index.spec.ts
Module build failed: Error: [path to repo]\src\external\api\src\api\models    \index.spec.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property`.

How do I exclude a set of files from testing (and hopefully linting) correctly and still keep them for the build?

How to control ParallelSuitethread count?

I have following code:

@RunWith(ParallelSuite.class)
@Suite.SuiteClasses({Test1.class,
        Test2.class,
        Test3.class,
        Test4.class,
        Test5.class,
        Test6.class,
        Test7.class})
public class ParallelRunner {
}

I ran it and figured out that only 3 test run in parallel. These test anough long - 15+ seconds

Is it OS scheduler issue or junit thread pool limit?

How can I configure thread pool limit ?

JUnit @RepeatedTest for concurrent execution

I've read following article and I understand that I can ask junit to execute test several times by adding following annotation:

@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)

But I want to start these 3 time in parallel.
Is it posssible?

P.S. I want to check that tests pass correctly for 10+ threads

Are teams adopting BDD for regression testing?

Have been hearing a lot about BDD with Selenium being adopted for regression testing. Are teams using BDD for writing regression tests? I am asking about automating test cases for a decent consumer based application like a banking app.

Hot Reload during Unit testing

I develop right now a small flutter app. I think as everyone, I fell in love with the hot reload feature.

So now I'm wondering if there is any possibility to have the same developer experience during unit test. Do have to turn a flag somewhere or is it right know just no possible.

If is not possible, are there any plans to make it possible?

Is there any hook triggered when a spring integration flow finishes in testing with the OnlyOnceTrigger?

In testing for projects with spring-integration, with the OnlyOnceTrigger, it is expected that a flow will finish soon. However I cannot find a way to determine when thus I have to use Thread.sleep(n) to wait for enough time, which is quite inefficient. Any suggestion with this issue?

Missing required parameters for [Route] unit testing

I have this piece of code for feature test for controller store method

$response= $this->post(route('contact.store'),[$client->value])

but I got this error

Missing required parameters for [Route: contact.store] [URI: client/{clientValue}/contact].

How I can fix this ?

lundi 26 février 2018

How to stub a function that responds with an HTTP response?

I am using ExpressJS and want to stub a function that responds with an HTTP response as a part of a router. In particular, it is a request to Amazon S3 that I am trying to stub.

app.get('/', (req, res, next) => {
  s3.getSignedUrl('putObject', (err, url) => {
    res.json({ url: url });
  });
};

I am trying to stub getSignedUrl using sinon.

sinon.stubs(s3, 'getSignedUrl').returns({})

How can I properly stub this method? I don't want to make the request to S3 every time.

How to pass command line arguments into Arquillian Tests in IntelliJ?

I have a pretty basic file IO command line Java application that I am creating in IntelliJ IDEA. I want to create tests to run so I do not have to manually change the Command Line Arguments (String [] args) under Run/Edit Configurations/Configuration tab --> Program Arguments. I bascially want to be able to run a test after any serious changes that I make to ensure all of my different flagging options and file paths that are being passed in are not failing.

How can I do this simply?

Cucumber Feature file does not see "step" file

This is only my second day with Cucumber. I have created the test file and the step file. Cucumber starts up and runs, but it continues to tell me to write a step file. Is there a naming convention for the files, or do I need to point to the step file somehow? I am trying to follow a tutorial.

Thank you

Cucumber: Version 3.1.0

Ruby version: 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin16]

rspec-core 3.7.1

 test/features/step_definitions/test_step.rb


require 'watir'
require 'colorize'

browser = Watir::Browser.new


Given(/^I am on Guru99 Demo Page$/) do

  browser.goto "http://demo.guru99.com"

 end


 When (/^Enter blank details for login$/)do
   browser.text_field(:name,"emailid").set (" ")
   browser.button(:name,"btnLogin").click 
 end

 Then (/^Show error message$/)do
   puts 'Email is Required!'.red
   browser.close
 end

And my Test File:

test/features/test.feature

Feature: guru99 Demopage Login
 In order to Login in Demopage we have to enter login details


 Scenario: Register On Guru99 Demopage without email

 Given  I am on the Guru99 homepage

 When enter blank details for Register

 Then error email shown

Here the results in the console when I run Cucumber.

ZeroCalms-MacBook-Pro:features ZeroCalm$ cucumber test.feature

Feature: guru99 Demopage Login
 In order to Login in Demopage we have to enter login details

  Scenario: Register On Guru99 Demopage without email # test.feature:5
    Given I am on the Guru99 homepage                 # test.feature:7
    When enter blank details for Register             # test.feature:9
    Then error email shown                            # test.feature:11

1 scenario (1 undefined)
3 steps (3 undefined)
0m0.026s

You can implement step definitions for undefined steps with these 
snippets:

Given("I am on the Guru{int} homepage") do |int|
  pending # Write code here that turns the phrase above into concrete 
  actions
end

When("enter blank details for Register") do
  pending # Write code here that turns the phrase above into concrete 
  actions
end

Then("error email shown") do
  pending # Write code here that turns the phrase above into concrete 
  actions
end

Unit testing capture failure not shown in istanbul code coverage

I'm trying to capture an error with my tests. I have istanbul showing that a current path is not covered by my tests. I think I have it covered but I'm curious why it's not showing in my coverage report.

This is the bit of code i'm testing, It says that my error if route is never covered.

pool.getConnection((err, connection) => {
if (err) {
  console.log(err.message)
  return false
}
else{
   console.log('Connected!!');
 }
});

and here is the test I have for that

it("Should fail to provide a test database connection" , function(done){
let pool  = mysql.createPool({
  connectionLimit : 200,
  host     : '***',
  user     : 'correctuser',
  password : 'WRONGPASSWORD',
  database : 'db'
});
pool.getConnection(function(err, connection) {
  if(err){
    console.log(err.message);
    done();
  }
});
})

Validate date format oracle

I would like to validate date column of a table with format 'YYYY-MM-DD HH24:MM:SS'. The query i used so far is

select count(*) from table-name where not regexp-like(datefield,'/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/'

I would like to validate using a different method for the above requirement, like using sysdate format. Could someone please help me.

Thanks

How to use RxIdler?

Could someone explain to me how to use RxIdler? I do not understand how it works or even how to set it up.

What I do understand is it converts RxJava Schedulers to IdlingResource so that Espresso testing could be done with RxJava. I may be also wrong about this so please could someone explain this to me?

Thank you in advance.

Asynchronous Javascript code testing using Jest works when it is not supposed to

Jest's docs provides a negative example of what not to do when testing asynchronous code. I implemented it this way:

const expect = require('expect');

function fetchData(cb) {
    setTimeout(cb('peanut butter2'), 1500);
}

test('the data is peanut butter', () => {
    function callback(data) {
        expect(data).toBe('peanut butter');
    }

    fetchData(callback);
});

I ran npx jest test.js, and this was the output:

Fabians-MacBook-Pro:playground fabian$ npx jest test.js
 FAIL  ./test.js
  ✕ the data is peanut butter (6ms)

  ● the data is peanut butter

    expect(received).toBe(expected)

    Expected value to be (using Object.is):
      "peanut butter"
    Received:
      "peanut butter2"

      at callback (playground/test.js:9:22)
      at fetchData (playground/test.js:4:16)
      at Object.<anonymous>.test (playground/test.js:12:5)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.866s, estimated 1s
Ran all test suites matching /test.js/i.

I don't understand the results.

  1. Why does it work even though I didn't call done(), as Jest recommends you do for testing asynchronous code? I'm pretty sure setTimeout is asynchronous, because I tested it in a blank test script using console.log() statements, and the second one fired before the first one which was enclosed in a setTimeout function.

  2. Furthermore, the test failed in 0.866s, when my timeout was set to 1500ms. How could Jest have received the incorrect callback data (peanut butter2) when my callback should not even have been called?

Unable to locate element using Selenium Webdriver

I am having sticky nav bar which has few list elements where each contains href element. When I tried to locate element I am getting the error. Following is my HTML code :

 <div class="nav" id="sticky">
                <div class="container">
                    <ul class="main-nav">
                        <li><a href="Dashboard.aspx">Dashboard</a></li>
                        <li><a href="../MEFAcademicDash/StudentUI/StudentHome.aspx"
                            title="Academic Dashboard">Academic</a></li>
                        <li><a href="Notices.aspx">Notices</a></li>

I want to locate Academic through Webdriver, I am getting the error like this Unable to locate the element. org.openqa.selenium.NoSuchElementException: Unable to locate element: /html/body/div/form/div[5]/div[1]/ul/li[2]/a

Katalon studio Unable to set text (Root cause: Element is not currently interactable and may not be manipulated

Hi guys i am using katalon studio and whiling passing text via set text email to email input field i am getting this issue:

Test Cases/Valid_Login FAILED because (of) Unable to set text 'usman@myfake.tk' of object 'Object Repository/Page_Webtalk  Communicate Better/input_email' (Root cause: org.openqa.selenium.InvalidElementStateException: Element is not currently interactable and may not be manipulated
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
System info: host: 'USMAN', ip: '192.168.11.206', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_102'
Driver info: com.kms.katalon.core.webui.driver.firefox.CGeckoDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 58.0.2, javascriptEnabled: true, moz:accessibilityChecks: false, moz:headless: false, moz:processID: 5508, moz:profile: C:\Users\usmanPC\AppData\Lo..., moz:webdriverClick: true, pageLoadStrategy: normal, platform: XP, platformName: XP, platformVersion: 6.3, proxy: Proxy(direct), rotatable: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}}
Session ID: d28ee92a-cfee-47ad-b6a2-46c705493a4e)

Test Cases/Valid_Login.run:31

Generated code is below:

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as MobileBuiltInKeywords
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSBuiltInKeywords
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUiBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
import org.openqa.selenium.Keys as Keys

WebUI.openBrowser('')

WebUI.navigateToUrl('https://dev.webtalk.co/')

WebUI.click(findTestObject('Page_Webtalk  Communicate Better/a_Login'))

WebUI.waitForElementPresent(findTestObject('Page_Webtalk  Communicate Better/input_email'), 5)

WebUI.setText(findTestObject('Page_Webtalk  Communicate Better/input_email'), 'usman@myfake.tk')

WebUI.setText(findTestObject('Page_Webtalk  Communicate Better/input_login_password'), 'Pmasuaar1@#$')

WebUI.click(findTestObject('Page_Webtalk  Communicate Better/input_login_button'))

WebUI.click(findTestObject('Page_Webtalk  Communicate Better/button_Talk'))

WebUI.closeBrowser()

Jest snapshot test - Error occurs when creating new object in componentDidMount()

I have a component whose root DOM element is a <canvas>. I use the componentDidMount() method to draw an image on the canvas; However, I am using a 3rd-party library, and when the test attempts to create a new object derived from that library, I receive the following error during my test:

TypeError: QR is not a constructor

QR is the name of the class used to instantiate the object from. Here is my component (note that when running the app, there is no error regarding the QR object, it only occurs during the test).

QRCode.js:

import React, { Component } from 'react';
import * as QR from 'qrious';

export class QRCode extends Component {

    render(){
        return (
            <canvas className='QRCode'>
            </canvas>
        );
    };

    componentDidMount() {
        this.drawQRCode();
    }

    drawQRCode() {
        ...
        // the error is occuring here
        let qr = new QR({
            element: canvas,
            value: 'http://example.com/',
            size: canvasSize,
            level: 'H',
            foreground: '#2B2F2B'
        });
        ...
    }

}

QRCode.test.js:

import { QRCode } from './QRCode';
import renderer from 'react-test-renderer';

describe('QRCode', () => {

    it('renders correctly (snapshot test)', () => {
        const tree = renderer
            .create(<QRCode />)
            .toJSON();

        expect(tree).toMatchSnapshot();
    });

});

I tried adding import * as QR from 'qrious'; to the top of the QRCode.test.js file, but it made no difference.

How to delete email from a MailChimp list using the API/Gibbon?

I want to delete user's email from my list in MailChimp using the API or Gibbon. However, there's no documentation about this in Gibbon repo.

As of now, I can only delete the email from the MailChimp website.

Method not found - PHPUnit Confusion

Code

class Rechner {

    public function add($a, $b){
        return $a + $b;
    }

My TestCase

class RechnerTest extends PHPUnit\Framework\TestCase
{

    public $calculator;

    protected function setUp ()
    {
        $this->calculator = new Rechner();
    }

    protected function tearDown ()
    {
        $this->calculator = NULL;
    }

    public function testAdd ()
    {


        $result = $this->calculator->add(1, 2);
        $this->assertEquals(3, $result);
    }

}

Error Output

Error: Class 'Rechner' not found

Composer.json file

{
  "autoload":{
    "psr-0" :{
      "":"src"
    },
    "classmap": [
      "tests"
    ]
  },
  "require": {
    "phpunit/phpunit": "^6.5",
    "authorizenet/authorizenet": "^1.9"
  }
}

My Problem

I am trying to figure out why the Method is not found.

If i try to require __DIR__ the 'Recher.php' does not show up, only the test case...and thats the one i don't need. Im am not sure what to do.

Jersey client testing


I have a Jersey client which performs post request to some black box service.
Also I have POJO mapping feature enabled.
My question is: how can I test this Jersey client?
I have integration tests already, they are calling real black box service.
Now I need to test black box service without calling real black box service.
Maybe there is some possibility to mock JSON response?

Environment: jersey-client and jersey-json versions - 1.19.1.

Is there any API to test the Windows application?

I'm doing manual testing on Windows Application(Desktop) written in c++ in 2000. This application uses OpenGL to draw Image(UI). The application is very old and I was thinking to do automation that would perform the mouse click, keyboard, position identification of content and then test it using a mouse. AutoIT does not work because the Window varies over execution and functionalities. Please tell me if there is any API, written especially c++, c# or any other language which can do unit testing on Windows Application. I use the windows 7 to perform the testing.

Android espresso detect subview is gone

I want to check if a subView "B" is gone or visible in the view "A".

To check if the subView is visible in A, I'm doing this and it works well :

mainView.check(matches(allOf(isDisplayed(), hasDescendant(withId(R.id.subViewB)))));

But to check if "subViewB" is gone, I have crash for every things I tested. I can't used "not(isDisplayed())" because with "GONE" the subView B can't be found and so it crash. I see I can use "doesNotExist", but I have no idea how to do that for a subView. I can't do onView(mySubview).doesNotExist because I want to check if the specific subView of my view A does not exist and no the others.

How do I create a loop that continuously tests output of a program I am testing?

I am black box testing a wide range of data on a program. How could I create a loop that continuously scans the input into the program being tested and prints out each result?

dimanche 25 février 2018

JSONPath unable to parse when expression contains hyphen

I am using codeception for testing my JSON API laravel project. I am using codeception's JSONPath functions to check the structure of the responses. I am unable to parse the expression when it contains a hyphen. Json Path uses hyphen as a subtraction operator, but in this case I have used it as a string. I know putting the substring containing hyohen inside double quotes("") inside the whole expression in single quote should do that. but its not working.

here is the function on my api test suite SomeTestCest.php

public function someTest(ApiTester $I)
{
    $I->sendGET('/teachers/122');
    //used double quotes as it contains hyphen
    $I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships."high-schools"');
}

here is a sample response from the get request in the test.

{
    "data": {
        "type": "teachers",
        "id": "122",
        "attributes": {
            "fullname": "Rhoda Frami",
        },
        "relationships": {
            "high-schools": {
                "data": null
            },
            "subjects": {
                "data": null
            }
        },
        "links": {
            "self": "http:\/\/api.project:81\/teachers\/122"
        }
    }
}

when i run the tests using following

php codecept run tests/api/resources/SomeTestCest.php --steps --verbose

it throws an error

There was 1 failure:

---------
1) SomeTestCest:
 Test  tests/api/resources/SomeTestCest.php:someTest
 Step  See response json matches json path "$.data.[*].relationships."high-schools""
 Fail  Received JSON did not match the JsonPath `$.data.[*].relationships."high-schools"`.
Json Response: 
    {
    "data": {
        "type": "teachers",
        "id": "122",
        "attributes": {
            "fullname": "Rhoda Frami",
        },
        "relationships": {
            "high-schools": {
                "data": null
            },
            "subjects": {
                "data": null
            }
        },
        "links": {
            "self": "http:\/\/api.project:81\/teachers\/122"
        }
    }
}

i have tried following ways as well

$I->seeResponseJsonMatchesJsonPath("$.data.[*].relationships.'high-schools'");

$I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships."high-schools"');

$I->seeResponseJsonMatchesJsonPath('$.data.[*].relationships.high-schools');

$I->seeResponseJsonMatchesJsonPath("$.data.[*].relationships.high-schools");

and its either this error. I know its because the hyphen is not parsed as its intended.

There was 1 error:

---------
1) SomeTestCest: 
 Test  tests/api/resources/SomeTestCest.php:SomeTest

  [Flow\JSONPath\JSONPathException] Unable to parse token high-schools in expression: .data.[*].relationships.high-schools 

So i checked with the base package JSONPath that is being used by codeception and found that it was working as intended.

$data = ['people' => [['high-schools' => 'Joe'], ['high-schools' => 'Jane'], ['high-schools' => 'John']]];
$result = (new \Flow\JSONPath\JSONPath($data))->find('$.people.*."high-schools"');
print_r($result);

here is the result

Flow\JSONPath\JSONPath Object
(
    [data:protected] => Array
        (
            [0] => Joe
            [1] => Jane
            [2] => John
        )

    [options:protected] => 0
)
=> true

So my question is how to parse a json string that contains a hyphen(-) to check the structure of json using Codeception with Json Path?

Thank you

Unit Testing RxJava doOnSubscribe and doFinally

How do I create a unit test that a certain side effect is done on doOnScubscribe and doFinally of an rxjava chain?

For Example:

Observable.requestSomeValueFromWeb()
            .doOnSubscribe(() -> showLoading = true)
            .doFinally(() -> showLoading = false)
            .subscribe(result -> doSomething(result), error -> doErrorHandling(error));

how do I test in the scenario above that the "showLoading" was set to true on subscribe and false when the observable was disposed?

Thanks in advance.

Throwing Exceptions with Mockito in Kotlin

I am using Kotlin and am trying to throw an Exception on a specific method invocation but always get the following error

Checked exception is invalid for this method!
Invalid: exceptions.ServiceException

This is the test

val client : IClient = Mockito.spy(Client(Cnf("https://:region.example.com", key)))


@Test(expected = ServiceException::class)
fun test400ResponseFrom() {
    val url = "https://example.com/example/user/v3/user/by-name/JACKAPPLE"

    Mockito.doThrow(ServiceException("Bad Request")).`when`(client).makeRequest(url ,riotkey)
    client.getUserDataByNameAndRegion("jackapple", "BR")
}

Basically the getUserDataByNameAndRegion method will invoke the makeRequest method and with this test I want to validate that the method is handling the result of the stubbed method correctly.

The original method looks like this

@Throws(NotFoundException::class, ServiceException::class)
fun makeRequest(url: String, key : String) : String {
    val con = prepareConnection(url, key)
    val statusCode = con.responseCode
    when {
        (statusCode == 400) -> throw ServiceException("Bad Request")
        (statusCode == 401) -> throw ServiceException("Unauthorized")
        (statusCode == 403) -> throw ServiceException("Forbidden")
        (statusCode == 404) -> throw NotFoundException("Data not Found")
        (statusCode == 415) -> throw ServiceException("Unsupported Media Type")
        (statusCode == 429) -> throw ServiceException("Rate limit exceeded")
        (statusCode == 500) -> throw ServiceException("Internal Server Error")
        (statusCode == 502) -> throw ServiceException("Bad Gateway")
        (statusCode == 503) -> throw ServiceException("Service unavailable")
        (statusCode == 504) -> throw ServiceException("Gateway timeout")
        (statusCode == 200) -> {
            return getStringResponseFromConnection(con)
        }
        else -> {
            throw ServiceException("Respondend with Statuscode ${statusCode}")
        }
    }
}

Test angular for observable

I'm trying to test only the function calculateExchangeCurrency

@Input() referenceText;
@Input() exchangeText = 55; // ONLY TO CHECK IF TEST COMMANDS READ CORRECTLY
// More data...
public calculateExchangeCurrency() {

  let referenceNumber = parseFloat(this.referenceText.replace(/,/g,''))
  return Observable
    .interval(this.timeToOtherRequest)
    .startWith(0)
    .flatMap(() => this.exchangeService.getExchange('USD', 'EUR'))
    .subscribe(response => {
        console.log('here');
        this.exchangeText = response.rates['EUR'] * referenceNumber;
        console.log(this.exchangeText);
    });

}

This function only needs the parameter referenceText and Its purpose is to calculate the variable exchangeText, this variable is inserted in html via ngModel:

<input type = "text" class = "form-control result-exchange" [ngModel]="exchangeText | number" placeholder = "EUR" disabled>

TEST

  • The function consumes a service and I know that I need to create a fake response for this service exchangeService, for that with spyOn I created a fake response

  • I'm going to test if the variable exchangeText calculated in the function is on the html, for that motive I read from result-exchange class

code:

// Fake data for service
let testExchange = {
  rates: {
    EUR: 0.851256
  }
};

describe('HomeComponent', () => {

  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let exchangeService: ExchangeService;
  let el: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, TextMaskModule, HttpModule],
      declarations: [ HomeComponent ],
      providers: [ ExchangeService ]
    })

    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    exchangeService = TestBed.get(ExchangeService);

  });

  it('should calculate number', () => {
    fixture.detectChanges();

    //  Unique input that needs the function
    component.referenceText = '456.5';

    // Create fake response of service
    let spy = spyOn(exchangeService, 'getExchange').and.returnValue(of(testExchange));
    component.calculateExchangeCurrency();

    // Wait the page is loaded
    fixture.whenStable().then(() => {
      fixture.detectChanges();

      // Get result from html
      el = fixture.debugElement.query(By.css('.result-exchange'));

      // Test
      expect(el.nativeElement.value).toBe('396.259');
    })

  });

});

RESULT

enter image description here

Problems:

  • In console I realize the test enter to the function but no replace the service for the fake response, It consumes from my real service because 0.851256*456.5 = 388.598 != 371.259

  • Expected '55' to be '396.259'. It means the input with class exchangeText never is updated. Because it needs to be 371.259 in theory, but if the fake service works well then It needs to be 388.598

I'm learning test in angular, sorry if I made mistakes. Will be ok If also there are suggestions.

spring rest testing @JsonFormat annotation

I need to test if my endpoint /people return correct json values. I use in my Person model `@JsonFormat annotation, when I use Postman or browser it produces correct date in format "dd-MM-yyyy".

Example:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
private LocalDate birthDate;

And output is correct in json-> birthDate: "01-01-2000"

But if I want to test my controller, it produces me following error:

Expected: is "01-01-2000"
 but: was <{year=2000, month=JANUARY, monthValue=1, dayOfMonth=1, 
 chronology={id=ISO, calendarType=iso8601}, leapYear=true, 
 dayOfWeek=SATURDAY, dayOfYear=1, era=CE}>

I don't know where is the problem.

Thanks in advance!

Vue.Js teting with jest error axios

I'm writing test for components which uses axios. I got:

TypeError: Cannot read property 'get' of undefined

after yarn test. I tried to import axios to my *spec.js files, but it doesn't work. What should i do to pass that tests?

After "disable beta testing" in google play console, how to enable again?

My app is unloaded as beta release, tester can download and test the uploaded apk. After i pressed the "DISABLE BETA TESTING" button, and save it, the link for download apk become not available.

I don't know to enable the test again, because the "DISABLE BETA TESTING" button has not changed, it is always "DISABLE BETA TESTING", and I cannot found button like "ENABLE...", so, how can i enable the test to allow the download link available to tester again?

samedi 24 février 2018

get javax.validation instead of org.hibernate.exception ConstraintViolationException

While using Spring Boot I get DataIntegrityViolationException whichs getCause() method returns org.hibernate.exception.ConstraintViolationException. I want to make it returns javax.validation.ConstraintViolationException instead, this one has methods more specified for extracting constraint violations. How can I do that?

I have these dependencies on my classpath and my application.properties file is empty right now.

spring-boot-starter-jpa-1-5-10 hibernate.validator-5-3-6 hibernate-entitymanager-5-0-12 hibernate-core-5-0-12

Jest - why mocked function still calls old function?

I've got a Todo React Component that does an API call inside componentDidMount and once the data is loaded, it will display it on the screen. While loading a text informing user about fetching will be shown.

Here is my todo.test.js:

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { mount, shallow, render } from 'enzyme';
import Todo from '../components/Todo';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import toJson from 'enzyme-to-json';
import {getTodos} from '../helpers/todo';

Enzyme.configure({ adapter: new Adapter() });

const mockTodos = { data: [{
    "id": 4404,
    "status": "active",
    "text": "Shopping List"
}]};

jest.mock('../helpers/todo', () => ({
    getTodos: jest.fn(() => {
        return Promise.resolve(mockTodos);
    })
}));

describe('Todo', () => {
    it('works', () => {
        const component = mount(<Todo timeout={2000} />);
        expect(toJson(component)).toMatchSnapshot();

        component.find("button").simulate("click");
        expect(toJson(component)).toMatchSnapshot();
    });
});

here is my helpers/todo.js:

const mockTodos = { data: [{
    "id": 7727,
    "status": "completed",
    "text": "Mocked Completed Todo"
}]};

export const getTodos = () => {
    console.log("[][] Get Todos");

    return new Promise((resolve, reject) => {
        resolve(mockTodos);
    });
};

and here is my todo.js component:

import React from 'react';
import PropTypes from 'prop-types';
import TodoItem from './TodoItem';
import {getTodos} from '../helpers/todo';

class Todo extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            todos: [],
            error: false,
            loading: true
        };
        this.cancelAjaxRequests = false;
        this.callApi = this.callApi.bind(this);
    }

    callApi() {
        getTodos().then((json) => {
            if (!this.cancelAjaxRequests) {
                this.setState({
                    todos: json.data,
                    loading: false
                });
            }
        });
    }

    componentDidMount() {
        getTodos().then((json) => {
            if (!this.cancelAjaxRequests) {
                this.setState({
                    todos: json.data,
                    loading: false
                });
            }
        });
    }

    componentWillUnmount() {
        this.cancelAjaxRequests = true;
    }

    render() {
        let content;

        // TODO: add error handling

        if (this.state.loading) {
            return (
                <div>
                    <div>
                        <button id="update-data" onClick={this.callApi}>Update State</button>
                    </div>
                    <p>Todos are being fetched...</p>
                </div>
            );
        }

        return (
            content ||
            <div>
                <div>
                    <button id="update-data" onClick={this.callApi}>Update State</button>
                </div>
                <p><b>{this.state.todos.length}</b> todos fetched so far</p>
                {this.state.todos.map(
                    (todo) => <TodoItem key={todo.id} id={todo.id} status={todo.status} text={todo.text} />)}
            </div>
        );
    }
}

Todo.proptypes = {
    timeout: PropTypes.number
};

export default Todo;

When running the tests the message from console.log("[][] Get Todos"); is displayed.

Aren't mocks supposed to actually mock the given function and not to call the original one? Why is it calling my getTodos function?

Shouldn't only stick to return Promise.resolve(mockTodos); from jest.mock ?

Is It Possible To Extend A Jest / Expect Matcher

I would like to extend Jest's isEqual matcher so that the expected value is transformed before comparison (this allows me to use multiline strings in tests). All I need to do is run the expected value through a the indentToFirstLine function from the lib: indent-to-first-line before passing it to isEqual. Obviously I don't want to have to do this everywhere I need it, so it makes sense to fold this into a matcher, and as I want identical functionality to Jest / Expect's isEqual matcher, it makes sense to utilise that.

I've tried the following:

import indentToFirstLine from 'indent-to-first-line'
import expect from 'expect'

const toEqualMultiline = (received, expectedTemplateString) => {
  const expected = indentToFirstLine(expectedTemplateString)
  return expect(received).toEqual(expected)
}

export default toEqualMultiline

However expect(received).toEqual(expected) doesn't return a value, so the value returned from my matcher in undefined, causing Jest to error:

Unexpected return from a matcher function. Matcher functions should return an object in the following format: {message?: string | function, pass: boolean} 'undefined' was returned

Is it possible for me to use toEqual from within my own matcher?