dimanche 31 mai 2020

Which framework is better for UI Testing React testing library or python robot framework?

Can someone please help me with this, Which framework we can use for UI testing i.e React testing library or Python robot framework? As per my understanding if we are proceeding with multiple data-driven operations python robot framework is better then react testing library.

H2 ApplicationContext Fails when creating multiple tables

Encountered the following problem during unit testing with Spring-boot/H2 database:

Once I define more than one table in my schema.sql file - getting an error:

java.lang.IllegalStateException: Failed to load ApplicationContext


Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker': Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/Users/hiddenpath/target/test-classes/schema.sql]: # DROP TABLE IF EXISTS User; nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "[*]# DROP TABLE IF EXISTS USER"; SQL statement:
# DROP TABLE IF EXISTS User [42000-200]

Scemas I have in schema.sql file :

CREATE TABLE User
(
    id      int auto_increment primary key,
    name    varchar(20) not null,
    surname varchar(20) not null,
    role    varchar(20) not null,
    email   varchar(30) not null
);

create table Dashboard
(
    id              int auto_increment primary key,
    name            varchar(20) not null,
    creation_date   datetime    not null,
    due_date        datetime    null,
    completion_date datetime    null
);

create table dashboard_user
(
    dashboard_id int null,
    user_id      int null,
    constraint dashboard_user_dashboard_id_fk
        foreign key (dashboard_id) references dashboard (id),
    constraint dashboard_user_user_id_fk
        foreign key (user_id) references user (id)
);

What's strange is that no error happening when i have only User table in the schema.sql, but problem appears once add more tables.

My properties file looks as follows:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.h2.console.path=/h2
spring.datasource.schema=classpath*:schema.sql
spring.datasource.data=classpath*:data.sql
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=false

Appreciate your help

How to copy data in excel format and paste in multi line text box with formatting in selenium

I need a help on the below scenario.

Scenario: I need to copy the range of data (E.g.- C3:E3) from excel and paste it in multi line text box. Here I cannot add the data in a list and paste it in multiline textbox since this multiline textbox will only allow the excel formatted range data.

To be more precise, There is a form which has multi line text box, button and a grid. When you paste the data( i.e range of data from excel) into the multi line text box and click on the button then the data will be displayed in the grid. Here, if you manually enter any data in multi line text box and click on the button then the data will not be imported in the grid, since we have not pasted the data from the excel.

Please let me know how can I achieve the above scenario using selenium c#

How can I trigger automation repo's test, once backend repo build is done

Backend config is working and building perfectly, now i want to trigger automation repo build. I have separate config for that as well, that uses cypress orb (circleci)

Add a Variable to JMeter Pre/Post Processor and Use it on If Controller

I am trying to run 5 Thread Groups.

  1. CreateAssets (This thread group creates assets)
  2. SearchAssets (This thread group searches for assets continuously created before till all get available)
  3. UpdateAssets (This thread group updates the assets which created before)
  4. SearchUpdatedAssets (This thread group searches for updated assets continuously till all get available)
  5. DeleteAssets

How I wants this to work is,

  • Run 1 and 2 Threads Parrallaly.
  • Once 1 and 2 is done, Start 3 and 4 Threads Parralally.
  • Once 3 and 4 is done, Run Thread 5.

So far what I thought was to add if controller into thread 3 and 4, set a flag on the top threads and set that flag true once thread 1 and 2 are done, and add that condition to if controller.

Really appreciate if anyone can help me with this.

Thanks in advance.

Which order when refactoring ReactJs App (Starting with tests, hooks and redux)

I created a React Application. Now, time has come to start with refactoring and make it stable for the enhancements in the future. I would like to:

  • Add tests (at the moment I do not have tests in my code)
  • Switch to Hooks API (at the moment I use classes)
  • Introduce Redux for state handling

Usually I would say, that it makes sense to start with a test-coverage and afterwards refactor with Hooks and Redux. But I am not sure, if the changes which comes with redux and hooks let me still make use of the test-cases or if I have to rewrite a large part of the tests.

In which order would you introduce these three basic changes?

Thanks a lot

What does this errorcode mean? JUnit 5 / eclipse 2020-03 (4.15.0)

I am trying to test a class in Java with JUnit 5 and get a long error list. I cannot quite understand what is going wrong.

java.lang.NoClassDefFoundError: org/junit/platform/commons/util/Preconditions
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:83)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:67)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.<init>(JUnit5TestLoader.java:34)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at java.base/java.lang.Class.newInstance(Class.java:584)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:371)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:366)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:310)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:225)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.ClassNotFoundException: org.junit.platform.commons.util.Preconditions
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 13 more

Does anyone have an idea what the problem could be?

Cannot run Jest tests

I'm trying to learn Jest to do which I'm trying to test some stuff in my React application. It doesn't matter what tests they are, whether it's simple snapshots, or some test for authentication, or a 1+1=2 kind of test. Everything fails.

After running npm run test all I get is this:

● Test suite failed to run

    Cannot find module 'jest-matcher-utils' from 'to-be-in-the-dom.js'

    However, Jest was able to find:
        './to-be-in-the-dom.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

    However, Jest was able to find:
        './index.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

    However, Jest was able to find:
        'dist/extend-expect.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
      at Object.<anonymous> (../../node_modules/@testing-library/jest-dom/dist/to-be-in-the-dom.js:8:25)
    ```

This is my package.json:

{
  "name": "test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.4.1",
    "firebase": "^7.14.6",
    "jest-matcher-utils": "^26.0.1",
    "leaflet-geosearch": "^2.7.0",
    "mdbreact": "^4.26.0",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-bootstrap-range-slider": "^0.3.2",
    "react-bootstrap-star-rating": "^3.5.5-alpha.0.3",
    "react-burger-menu": "^2.6.13",
    "react-dom": "^16.13.1",
    "react-final-form": "^6.4.0",
    "react-hook-form": "^5.6.1",
    "react-icons": "^3.10.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1",
    "weather-icons": "git+https://github.com/erikflowers/weather-icons.git"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.11.0",
    "react-addons-test-utils": "^15.6.2",
    "react-test-renderer": "^16.13.1",
    "babel-jest": "^25.5.1"
  },
  "description": "This project was bootstrappd with [Create React App](https://github.com/facebook/create-react-app).",
  "main": "index.js",
  "author": "",
  "license": "ISC"
}

I've tried to edit this: "test": "react-scripts test" to: "test": "jest"

This allows some snapshots to get tested, but 18 tests fails with:

● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\Users\Kalle\Desktop\Skola\1dv430\atriptomemorylane\src\components\__test__\firebase.auth.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { signInWithEmailAndPassword, signOutFirebase, isAuthenticated } from "../../config";
                                                                                                    ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

For good measure, I'll toss one test in, with some redacted data:

test("signInWithEmailAndPassword should throw error with wrong credential", async () => {
  let error = "";
  try {
    await firebase
      .auth()
      .signInWithEmailAndPassword("xxx@gmail.com", "xxx");
  } catch (err) {
    error = err.toString();
  }

  expect(error).toEqual(
    "Error: The password is invalid or the user does not have a password."
  );
});

Hope someone can point out what I'm doing wrong. This is driving me nuts!

no tests found with test runner JUnit 5

I wanted to test my classes in Java using JUnit 5, in Eclipse. all the files are in the same package. My test file is correct (syntax wise) and i get no errors from eclipse regarding the file itself. Only when i try to run the testfile, do i get the error: No tests found with test runner JUnit 5

I am really frustrated because i cannot seem to find the issue. i have included the JUnit-Library in my module path. I dont know if posting my code makes any sense, because i think it might be a different issue. Does anyone have any experience with this kind of error?

Load H2 source data from custom sql with Spring

Having a problem with H2 set up in Spring. I placed all my sql data into one file named data.sql, however when I change it to anything else - it cannot be identified. Any idea how to set up multiple separate files?

Let's say i have a table User and some data inserted, but aiming to have 2 separate files, e.g. user-schema and user-data, and so on - multiple schema files with same number of insert data files.

My current spring.properties looks as follows:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.h2.console.path=/h2

My current data.sql looks as follows:

DROP TABLE IF EXISTS User;

CREATE TABLE User
(
    id      INT AUTO_INCREMENT PRIMARY KEY,
    name    VARCHAR(20) NOT NULL,
    surname VARCHAR(20) NOT NULL,
    role    VARCHAR(20) NOT NULL,
    email   VARCHAR(30) NOT NULL
);

INSERT INTO User (name, surname, role, email)
VALUES ('Thor', '', 'admin', 'thor@marvel.com'),
       ('Hulk', '', 'user', 'hulk@marvel.com'),
       ('Venom', '', 'user', 'venom@marvel.com'),
       ('Spider', 'Man', 'user', 'spider-man@marvel.com'),
       ('Super', 'Man', 'user', 'super-man@marvel.com');

Formula to fins this scenario

Let’s suppose a case; “I am the owner of an old grocery shop. Customers used to come to my shop and purchase the item they required. As per the current scenario, when there are several options for a customer to buy the products in online mode along with the home delivery facility, I also felt that our shop should also be upgraded in such manner so that I can also provide home delivery and online payment options to my customers. In short, I want software that can be upgrading my shop up to the next level through online order, payment, and home delivery system.” Based on the mentioned scenario, give the answers to the following questions: a) As a software developer, how you will analyze the functional and non-functional requirements for the mentioned scenario? b) As a software developer, how you plan and estimate the cost of the project? c) How the agile process can be helpful in this scenario?

Why is `TypeError: firebase.initializeApp is not a function` occurring only when @firebase/testing is imported in a submodule to a cypress plugin?

I am using Cypress to test an app and using Cypress Tasks to run backend database seeding.

The backend is a locally emulated Firestore database.

Usually, I am able to run initializeAdminApp() without problems, from my Cypress plugins file. I am using the new built-in TS capabilities of Cypress.

When I import @firebase/testing in my plugins/index.ts file, there is no issue at all.

But if I instead import @myapp/testing which imports @firebase/testing and runs initializeAdminApp(), I get TypeError: firebase.initializeApp is not a function.

So I was able to fix the issue by simply adding this to my plugins/index.ts file:

import * as testing from '@firebase/testing';
testing;

And then the rest of the code (that was crashing before with that error) suddenly works fine.

I've even console logged the testing object from my submodule. It shows all the property keys as per normal.

Simply importing it and referencing the imported variable in a pointless expression, makes the function not crash when imported and used in a submodule.

Using an NX monorepo. Any ideas appreciated!

After downloading "Windows SDK Installer for windows 10" i cannot find the inspect tool in Windows Kits folder

I have downloaded windows SDK Installer from the following URL "https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/"

I have downloaded in my downloads folder. when I open the windows kits folder> 10 > Windows SDK, I can only see the following folders. Here there is no inspect tool. Can anyone know the solution for this problem.

After opening the windows SDK the folder structure looks like : Installers (Folder) Redistributable (Folder) User Experience manifest (XML Document) WinsdksetUp (Application)

samedi 30 mai 2020

Setting timestamp as a number but recieving as undefined

Result of Test:

FAIL ./block.test.js Block √ has a timestamp, lastHash, hash, and data property (28 ms) genesis() √ returns a Block instance (3 ms) × returns the genesis data (21 ms)

● Block › genesis() › returns the genesis data

expect(received).toEqual(expected) // deep equality

- Expected  - 2
+ Received  + 2

- Object {
+ Block {
    "data": Array [],
    "hash": "hash-one",
    "lastHash": "-----",
-   "timesamp": 1,
+   "timestamp": undefined,
  }

  26 |
  27 |         it('returns the genesis data', () => {
> 28 |             expect(genesisBlock).toEqual(GENESIS_DATA);
     |                                  ^
  29 |         });
  30 |     });
  31 | });

  at Object.<anonymous> (block.test.js:28:34)

console.log genesisBlock Block { timestamp: undefined, lastHash: '-----', hash: 'hash-one', data: [] }

  at Suite.<anonymous> (block.test.js:21:17)

Running Tests with MockitoJUnitRunner fails verify asserts

Is there a way to mock a Repository without the @RunWith(MockitoJUnitRunner) annotation on the class?

I have a test that passed without the annotation but fails with it. Without it, my repo test doesn't work. It's a catch 22.

When I use that annotation, my when() methods in my tests no longer stub behavior, mocks do nothing, and despite setting break ppoints and those breakpoints being hit (indicating the line/method is run), verify(..., times(x)) statements say the mocked object never interacted with that method. I've been pulling my hair out on why using the @RunWith(MockitoJUnitRunner) annotation would make the most simple parts of Mockito not work.

I can't find any threads asking about this but maybe someone knows better keywords to use. Does this sound like a known issue?

Here is my test:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

// toggling this below annotation is the source of grief.
//@RunWith(MockitoJUnitRunner.class)
public class LoadEditEntityChangeLogServiceImplTest {

    @InjectMocks
    private ServiceImpl serviceMock;

    @Mock
    private EditStepRepository editStepRepository;

    @Mock
    private EditMapper editMapper;

    @Before
    public void init() {
        initMocks(this);
    }


    @Test // when the RunWith is commented out, this passes. When it is not, the test fails the verify assert. 
    public void mapEditEntityFromAction_Test() {
        EditDTO editDTO = Mockito.mock(EditDTO.class);
        when(editDTO.getSysNum()).thenReturn((long)7334);

        EditEntity editEntity = new editEntity();
        editEntity.setSysNum(editDTO.getSysNum());

        when(editMapper.mapToEntity(eq(editDTO))).thenReturn(editEntity);

        editEntity response = serviceMock.mapEditEntityFromAction(editDTO);

        verify(loadEditMapper, times(1)).mapToEntity(eq(loadEventDTO));
        assertEquals(loadEventDTO.getSystemNumber(), response.getSystemNumber());
    }

    @Test // this will fail without the @RunWith as the mocked repo will be null and throws NullPointerException when used.
    public void updateConvertedEventSegment_Test() {
        EditEntity editEntity = new EditEntity();
        EditStepEntity editStepEntity = new EditStepEntity();
        editEntity.setEditStep(editStepEntity);

        doReturn(editStepEntity).when(editStepRepository).save(any());

        serviceMock.updateEditStep(editEntity);

        verify(editEntity, times(1)).getEditStep();
        verify(editStepRepository, times(1)).save(eq(editStepEntity));
    }
}

Testing argument using Python Click

I have a command-line script with Python-click with an argument and option:

# console.py
import click

@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
    "-m",
    "--max-size",
    type=int,
    help="Max size in megabytes.",
    default=20,
    show_default=True,
)
def main(filepath: str, max_size: int) -> None:
    max_size_bytes = max_size * 1024 * 1024  # convert to MB
    if filepath.endswith(".pdf"):
        print("success")
    else:
        print(max_size_bytes)

Both the argument and option have default values and work on the command-line and using the CLI it behaves as expected. But when I try testing it following Click documentation and debug it, it does not enter the first line:

# test_console.py
from unittest.mock import Mock

import click.testing
import pytest
from pytest_mock import MockFixture

from pdf_split_tool import console

@pytest.fixture
def runner() -> click.testing.CliRunner:
    """Fixture for invoking command-line interfaces."""
    return click.testing.CliRunner()

@pytest.fixture
def mock_pdf_splitter_pdfsplitter(mocker: MockFixture) -> Mock:
    """Fixture for mocking pdf_splitter.PdfSplitter."""
    return mocker.patch("pdf_split_tool.pdf_splitter.PdfSplitter", autospec=True)

def test_main_uses_specified_filepath(
    runner: click.testing.CliRunner,
    mock_pdf_splitter_pdfsplitter: Mock, 
) -> None:
    """It uses the specified filepath."""
    result = runner.invoke(console.main, ["test.pdf"])
    assert result.exit_code == 0

I couldn't see why it is giving since the debugger did not enter the first line of function main(). Any ideas of what could be wrong?

Jest with globalsetup doesn't see tests

Say I have the following test:

describe('foo', () => {
    it('bar', () => {
        expect(1).toBe(2)
    })
})

in a file named foo.application.test.ts

And the following command in my package.json:

jest --testRegex '.*.application.test.ts'"

Running these tests fails, as you would expect. However, changing my command to:

jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'"

Results in no tests being run at all ( the global setup file does exist), with the following log:

yarn run v1.22.4
$ jest --globalSetup ./tests/support/instantiateApplicationTests.ts --testRegex '.*.application.test.ts'
✨  Done in 0.81s.

How am I misusing globalsetup here?

How to test member-wise equality operator?

I have a structure of three members { xx, xy, yy } and an overloaded == operator that member-wise tests if corresponding members of left-hand and right-hand expressions are either equal within some precision, or are both NaNs. Quite trivial.

For my test case, I wanted to target a typo situation, where I mistakingly compare wrong members. Maybe, I compare xx from left-hand expression with xy from right-hand expression. Maybe, I forgot to compare yy at all.

Since I'm using C++20, I don't know if it's even possible to construct a compile-time proof of correctness of == operator (and if I even should). Trying to solve this in usual manner, I find myself enumerating all possible permutations:

EXPECT_EQ(C{1, 2, 3}, C{1, 2, 3});
EXPECT_NE(C{1, 2, 3}, C{1, 3, 2});
EXPECT_NE(C{1, 2, 3}, C{2, 1, 3});
EXPECT_NE(C{1, 2, 3}, C{2, 3, 1});
EXPECT_NE(C{1, 2, 3}, C{3, 1, 2});
EXPECT_NE(C{1, 2, 3}, C{3, 2, 1});
EXPECT_NE(C{1, 2, 3}, C{1, 2, nan});
EXPECT_NE(C{1, 2, 3}, C{1, nan, 3});
EXPECT_NE(C{1, 2, 3}, C{nan, 2, 3});
// ...

EXPECT_NE(C{1, 3, 2}, C{1, 2, 3});
EXPECT_EQ(C{1, 3, 2}, C{1, 3, 2});
// ...

Such code is quite ugly, and if I replicate the same with nested loops:

for (T lxx = 1; lxx <= 3; lxx += 1) {
  for (T rxx = 1; rxx <= 3; rxx += 1) {
    for (T lxy = 1; lxy <= 3; lxy += 1) {
      for (T rxy = 1; rxy <= 3; rxy += 1) {
        // ...

it just seems that I am reimplementing equality operator in test, which misses the point of testing.

How do I do this correctly? Am I missing some edge cases maybe that would simplify it? How to scale such test if I have four members in a structure and don't want for test case code to explode?

How to correctly import and test a class into a pytest python file?

I am trying to learn about python testing with pytest.
i have built a class named YBlizer but when I try to import it to my test file and test its function pytest tells me its value is None. here is what I mean:

class:

class YBlizer():

    @staticmethod
    def display_menu():
        print("""Welcome to YOUTUBELIZER
=======================""")

test:

import pytest
from Yout.Youtubeilizer import YBlizer


def test_two(youb):
    test = youb.display_menu()
    assert test is not None


@pytest.fixture
def youb():
    return YBlizer()

after that i run: pytest tests\test_Youtubeilizer.py

and i get the following message:

FAILED tests/test_Youtubeilizer.py::test_two - assert None is not None

can someone please explain to me why the display_menu method is considered None in my test file and how can i fix this?

thanks!

Read and Print Excel Data on console and Open all excel links present in sheet

public class UrlTesting {

    public static void main(String[] args) throws IOException, BiffException {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Jatin\\Downloads\\chromedriver_v83\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();

        File excel = new File("C:\\Users\\Jatin\\Desktop\\Worksheet.xls");

        FileInputStream fi = new FileInputStream(excel);

        Workbook wb = null;

            wb = Workbook.getWorkbook(fi);


            Sheet s = wb.getSheet(0);

            System.out.println(s.getRows());


            // driver.get(https://www.google.com/);



            for(int row=0; row <=s.getRows();row++)

            {

                String Urllist = s.getCell(0, row).getContents();

                System.out.println("Url list - " + Urllist);

                List<WebElement> linkElements = driver.findElements(By.tagName("a"));



                String[] linkTexts = new String[linkElements.size()];

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



                int j = 0;

                for (WebElement e : linkElements)

                {

                    linkTexts[j] = e.getText();

                    j++;

                }

                //test each link

                for (String t : linkTexts)

                {

                    if (t != null && !t.isEmpty())

                    {

                        driver.findElement(By.linkText(t)).click();

                        String title;

                        title=driver.getTitle();

                        if(title.contains("404"))


                            System.out.println(t + " the link is not working");

                        else 

                            System.out.println(t + "is working");

                    }

                }
            }
        }
}

/* console o/p: ChromeDriver was started successfully. May 30, 2020 8:45:18 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: W3C 5 Url list - https://www.example.com/ Url list - https://www.example.com/ Url list - https://www.example.com/ Url list - https://www.example.com/ Url list - https://www.example.com/ Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at jxl.read.biff.SheetImpl.getCell(SheetImpl.java:356) at UrlTesting.main(UrlTesting.java:47) */

Test full render DOM Leaflet map

I have a component responsible for manage everything I need to render a map using Leaflet plugin, and it works great. Now I'm trying to write some tests using Enzyme and Jest but I'm facing some problems.

Here is one of my failing tests:

it('should trigger the marker click event', (done) => {
  const onMarkerClickMock = jest.fn(),
    myMarkers = [{
                  id: '10000001',
                  geolocation: { coordinates: [38.734577, -9.21739], type: 'Point' },
                  onClick: onMarkerClickMock
                }],
    markerSelector = '#path__0';


  $.ajax.mockImplementationOnce((request) => {
    expect(request.url).toContain(`https://maps.google.com/maps/api/js?v=3.&key=${myKey}`);
    return new Promise((resolve) => {
      fs.readFile(`${__dirname}test-data/google.js`, 'utf8', (err, data) => {
        request.success(resolve(data));
      });
    });
  });

  const map = mount(<Map markers={myMarkers} />);

  setTimeout(() => {
    const markers = map.state('markers');
    expect(markers).toHaveLength(1);
    expect(typeof markers[0].onClick).toBe('function');
    expect(markers[0].onClick).toEqual(onMarkerClickMock);
    map.find(markerSelector).simulate('click');         // <- failing here
    expect(onMarkerClickMock).toHaveBeenCalledTimes(1);
    done();
  }, 500);
});

First I had problems with setTimeOut and then figured out I needed to call done() inside it. Now when map.find(markerSelector) is called it is failing with this error message:

Method “simulate” is meant to be run on 1 node. 0 found instead.

I did map.html() and it returned only this:

<div class="my-component map-container" role="button" tabindex="0">
    <div id="map-61bb504b-8c6d-fb91-e743-e67f4b6b3f8a" class="map"></div>
</div>

But I expected it returned something like this with leaflet map rendered:

<div class="my-component map-container" role="button" tabindex="0">
   <div id="map-61bb504b-8c6d-fb91-e743-e67f4b6b3f8a" class="map leaflet-container leaflet-fade-anim leaflet-grab leaflet-touch-drag" tabindex="0" style="position: relative; outline: none;">
      <div class="leaflet-pane leaflet-map-pane" style="transform: translate3d(-319px, 0px, 0px);">
         <div class="leaflet-pane leaflet-tile-pane">
            <div class="leaflet-layer " style="z-index: 1; opacity: 1;">
               <div class="leaflet-tile-container leaflet-zoom-animated" style="z-index: 18; transform: translate3d(0px, 0px, 0px) scale(1);">
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(268px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124766!3i98632!4i256!2m3!1e0!2sm!3i515229400!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=99746" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(524px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124767!3i98632!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=94189" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(268px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124766!3i98633!4i256!2m3!1e0!2sm!3i515227686!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=14690" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(524px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124767!3i98633!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=98859" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(12px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124765!3i98632!4i256!2m3!1e0!2sm!3i515229400!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=40319" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(780px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124768!3i98632!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=22545" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(12px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124765!3i98633!4i256!2m3!1e0!2sm!3i515227686!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=86334" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(780px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124768!3i98633!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=27215" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(-244px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124764!3i98632!4i256!2m3!1e0!2sm!3i515218768!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=61271" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(1036px, -73px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124769!3i98632!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=81972" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(-244px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124764!3i98633!4i256!2m3!1e0!2sm!3i515216758!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=41588" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
                  <div class="leaflet-tile leaflet-tile-loaded" data-pending="0" style="width: 256px; height: 256px; transform: translate3d(1036px, 183px, 0px); opacity: 1;"><img draggable="false" alt="" role="presentation" src="https://maps.google.com/maps/vt?pb=!1m5!1m4!1i18!2i124769!3i98633!4i256!2m3!1e0!2sm!3i515229832!3m12!2spt!3sUS!5e18!12m4!1e68!2m2!1sset!2sRoadmap!12m3!1e37!2m1!1ssmartmaps!4e0&amp;key=AIzaSyCwHM3UZdSmdNOW2WvFH8UuG4YtgKCv000&amp;token=86642" style="width: 256px; height: 256px; user-select: none; border: 0px; padding: 0px; margin: 0px; max-width: none; position: absolute; visibility: visible;"></div>
               </div>
            </div>
         </div>
         <div class="leaflet-pane leaflet-shadow-pane"></div>
         <div class="leaflet-pane leaflet-overlay-pane">
            <svg pointer-events="none" class="leaflet-zoom-animated" width="704" height="480" viewBox="260 -40 704 480" style="transform: translate3d(260px, -40px, 0px);">
               <g>
                  <path class="leaflet-interactive" stroke="#e8008b" stroke-opacity="1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="#e8008b" fill-opacity="1" fill-rule="evenodd" d="M613,200L600.3538070924236,134.9409774905928A 66.27671238780022,66,0,0,1,654.709286557388,148.49332062917586 z" id="path__0" type="" networkelement="0"></path>
               </g>
            </svg>
         </div>
         <div class="leaflet-pane leaflet-marker-pane"></div>
         <div class="leaflet-pane leaflet-tooltip-pane"></div>
         <div class="leaflet-pane leaflet-popup-pane"></div>
         <div class="leaflet-proxy leaflet-zoom-animated" style="transform: translate3d(3.19404e+07px, 2.52501e+07px, 0px) scale(131072);"></div>
      </div>
      <div class="leaflet-control-container">
         <div class="leaflet-top leaflet-left"></div>
         <div class="leaflet-top leaflet-right"></div>
         <div class="leaflet-bottom leaflet-left" style="margin-bottom: 20px;"></div>
         <div class="leaflet-bottom leaflet-right" style="margin-bottom: 20px;">
            <div class="leaflet-control-zoom leaflet-bar leaflet-control"><a class="leaflet-control-zoom-in leaflet-disabled" href="#" title="Zoom in" role="button" aria-label="Zoom in">+</a><a class="leaflet-control-zoom-out" href="#" title="Zoom out" role="button" aria-label="Zoom out">−</a></div>
            <div class="leaflet-control-attribution leaflet-control"><a href="https://leafletjs.com" title="A JS library for interactive maps">Leaflet</a> | Map © 2020 <a target="_blank" href="https://developers.google.com/maps/">Google</a></div>
         </div>
      </div>
   </div>
</div>

Why mount() don't fully render my component? What I'm missing here? Can anyone help me, please?

how to calculate quizs

I want to make a test system. For this, there are "id", "question", "correct", "A", "B", "C", "D", "E" columns in the database. And in the "correct" column, I enter one of the values "A", "B", "C", "D" or "E". However, after entering the user response, I cannot automatically find the correct and wrong number on the result.php page. And I can't calculate the user score.

this is form :

<form action="result.php" method="post">
    <?php 
    /*n */
    include 'ayar.php';
    $v=$db->prepare("select * from riyaziyyat where id IN(1,2,3)");
    $v->execute(array());
    $x=$v->fetchALL(PDO::FETCH_ASSOC);
    foreach ($x as $key => $b) {  
    ?> 
    <div class="cavablardivi">
    <input type="radio" name="<?php echo $b["id"];?>" value="A"><span class="radioherf">A</span><br>
    <input type="radio" name="<?php echo $b["id"];?>" value="B"><span class="radioherf">B</span><br>
    <input type="radio" name="<?php echo $b["id"];?>" value="C"><span class="radioherf">C</span><br>
    <input type="radio" name="<?php echo $b["id"];?>" value="D"><span class="radioherf">D</span><br>
    <input type="radio" name="<?php echo $b["id"];?>" value="E"><span class="radioherf">E</span><br>
    </div>
    <?php } ?>
    <input type="submit" name="send" value="finnish">
</form>

and this is resul.php :

<?php 

$corrects=0;
$wrongs=0;
include 'ayar.php';
$v=$db->prepare("select * from riyaziyyat where id IN(1,2,3) limit 100");
$v->execute(array());
$x=$v->fetchALL(PDO::FETCH_ASSOC);
foreach ($x as $key => $b) {
if ($_POST['$b["id"]'] and $_POST['$b["id"]']==$b["correct"]) {
        $corrects++;} 
 else { $wrongs++;}
} 

echo "your corrects ---> ".$corrects; 
echo "<br>"; 
echo "your wrongs ---> ".$wrongs;
         
?>

enter image description here

Test IF file exist, ELSE xcopy these two files

Morning all.

So I've been up hours trying to cobble together -a variety of replies to other posts- into my own code in order to see if I could get something usable. No-go. I'm sufficiently lost in the sauce that I've now got to ask for some help from you.

Background: OS: Windows 10 I use the program text2folders.exe to create 20-30 new folders on a secondary drive every night. Primarily, I have a base file "aGallery-dl.bat" that I populate each folder with using an xcopy batch file. Secondarily, from time to time I update the source file "aGallery-dl.bat" using the same xcopy and this overwrites the older target file, populating all folders with the newest "aGallery-dl.bat" (whether they need it or not). All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

I've recently decided I want to add two new files to each folder and have expanded my xcopy to include these. All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"

Folder.jpg a big red X

Folder2.jpg a big yellow ! mark

When I choose to run a "aGallery-dl.bat" in a given folder (again, one of 100's), it first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. All is well.

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg

If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible.

Problem: When I have to re-run my original xcopy command to update "aGallery-dl.bat" in ALL FOLDERS, the Folder.jpg and Folder2.jpg will be re-copied to all folders, defeating the purpose of deleting them once via "aGallery-dl.bat." I don't want to have to go back and re-run "aGallery-dl.bat" 100's of times intermittently across a number of folders, just to get rid of them again. I need some type of test, that if "aGallery-dl.bat" is already present in the target folder, DO NOT xcopy Folder.jpg and Folder2.jpg aka vague example, below.

*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /s /y /d ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /s /y /d ".\Folder2.jpg" "%%a\"
GOTO eof

:eof

I had found a hopeful candidate test statement in the below (copied in its original form from what/where I read in other post), but am looking for ideas/replacements as I HAVE NO IDEA how to modify/inject/implement the below to work in the above.

If exist \\%DIR%\%Folder%\123456789.wav xcopy \\%DIR%\%Folder%\123456789.wav D:\%New Folder%\ /y

Having XCopy copy a file and not overwrite the previous one if it exists (without prompting)

Moving this to the end of the xcopy command (after the above, rather than before) allows "aGallery-dl.bat" to be updated in all folders without mucking up the above command.

for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

vendredi 29 mai 2020

Android Espresso - How to check if a view is ready to be clicked

I have an app with a splashscreen, which stays for about 2 seconds.

After that, it switches to another activity A. In A, I set a value in a SeekBar and after that, click a Button to confirm.

When I simply start a recorded Espresso test doing this, it tries to play while on the splashscreen. So when it tried to set the SeekBar value or click the Button, I get a NoMatchingViewException. So my first attempt at fixing this was to simply add a sleep(5000). This worked.

However, I dont want to put a manual sleep in after every Activity switch.

  1. Because it seems like unnecessary code
  2. Because it would mean unnecessary waiting time for running the test
  3. The timing might be arbitrary and could be different for different devices

So I tried to check whether or not Im in the right Activity/can see the right views. I did this using some SO links: Wait for Activity and Wait for View.

However, even that does not work 100%.

I have these two functions:

fun <T: AppCompatActivity> waitForActivity(activity: Class<T>, timeout: Int = 5000, waitTime: Int = 100) {
    val maxTries = timeout / waitTime
    var tries = 0

    for(i in 0..maxTries) {
        var currentActivity: Activity? = null
        getInstrumentation().runOnMainSync { run { currentActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(
            Stage.RESUMED).elementAtOrNull(0) } }
        if(activity.isInstance(currentActivity)) {
            break
        } else {
            tries++
            sleep(waitTime.toLong())
        }
    }
}
fun waitForView(
    @IntegerRes id: Int,
    waitMillis: Int = 5000,
    waitMillisPerTry: Long = 100
): ViewInteraction {

    // Derive the max tries
    val viewMatcher = allOf(
        withId(id),
        isDisplayed()
    )
    val maxTries = waitMillis / waitMillisPerTry.toInt()
    var tries = 0
    for (i in 0..maxTries)
        try {
            tries++
            val element = onView(viewMatcher)
            element.check { view, noViewFoundException ->
                if(view == null) {
                    throw noViewFoundException ?: Exception("TEST")
                }
                if(view.hasWindowFocus()) {
                    throw noViewFoundException ?: Exception("TEST2")
                }
            }
            return element
        } catch (e: Exception) {
            if (tries == maxTries) {
                throw e
            }
            sleep(waitMillisPerTry)
        }
    throw Exception("Error finding a view matching $viewMatcher")
}

Neither of those work 100%. Both of them seem to return within the timeout restrictions, and have "found" the activity/view. However, the expected view, e.g. a Button is not yet ready to perform, for example, element.perform(click()). It does not lead to a NoMatchingViewException, but it does not perform the click I did either. For the SeekBar, I use this:

private fun setSeekValue(seekBar: ViewInteraction, age: Int) {
        val fullPercentage = .9f
        val step = 1/99f

        seekBar.perform(
            GeneralClickAction(
                Tap.SINGLE,
                CoordinatesProvider { view ->
                    val pos = IntArray(2)
                    view?.getLocationOnScreen(pos)
                    FloatArray(2).apply {
                        this[0] = pos[0] + view!!.width * (.05f + fullPercentage*step*age)
                        this[1] = pos[1] + view.height * .5f
                    }
                },
                PrecisionDescriber {
                    FloatArray(2).apply {
                        this[0] = .1f
                        this[1] = 1f
                    }
                },
                InputDevice.SOURCE_MOUSE,
                MotionEvent.ACTION_BUTTON_PRESS
            )
        )
    }

However, when I use these functions and just put a very short sleep, e.g. sleep(100) after it, it works. This again however, would go against the three reasons listed above, which im trying to avoid here.

As you can see in the function waitForView, I tried to check if the View is "usable", using hasWindowFocus(). But this still does not perform the click, except for when I again put a sleep(80) or something after it. So it waits for the splashscreen to switch to A, finds the view it's looking for and then cant perform the click, except for when I wait a little bit.

I have also tried these functions of View:

  • isEnabled
  • isShown
  • visibility
  • getDrawingRect
  • isFocusable
  • isFocused
  • isLayoutDirectionResolved

Neither of them worked as I expected. With all of them, after the needed value was returned on the element.check part of waitForView, they would still not be accessible without putting a short sleep after.

Is there a way to reliably check if I can perform a click on a view/safely can perform ViewInteraction.perform()

Either by checking, if an activity is fully loaded to a point where its views are usable. Or by directly checking if a view is usable.

How to pass value returned by a method of a class as a parameter for test case in PyTest?

I am trying to pass a value returned by a class method into a test method in the same class.

def SampleTest:

    # my dynamic value generation function
    def dynamicValue(self):
        result = 10
        return result

    # how to pass a value returned by dynamicValue method?
    @pytest.mark.parametrize('value', [1, 2, dynamicValue])
    def test_case(self, value):
        print(f'Testing for input value {value}')
        # testing functionality...

By dynamic value I mean some numeric value fetched from operating system during collect phase of tests execution. How to do this correctly? Above example doesn't work.

How I can assert that an Attachment on a Mailable class equals to a file?

In a laravel project I have the following Mailable:

class MyMail extends Mailable
{
  public function build()
  {
     return $this            
                ->from('hentaiouji@neko.com', 'Hentai Prince witouh Story cat')
                ->subject("Stony Cat Lists")
                ->attach('myFile.xlsx', [
                    'as'   => 'myFile.xlsx',
                    'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                ])
                ->bcc('konekochan@example.com');
  }
}

And I want to assert that the correct file is attached so I need to locate the path and compare the md5's that are generated by reading the files.

The question is how from a mailable can retrieve the attachments so I can manually read them in php. The approach I want to follow is the:

public function testAtachmentIsTheSame()
{
   $expectedAttatchmentMd5=md5(file_get_contents('myFile.xlsx'));
   $mailable=(new MyMail())->build();
   $attatchmentMd5; //Contains the md5 read from the mailable Atachment

   $this->assertEquals($expectedAttatchmentMd5,$attatchmentMd5);
}

So in my test how I can get the attatchment from a Mailable without sending the actual email?

Spring test mock and object references an unsaved transient instance

In short I have an entity that have references to other entity and this entity have reference... so when I want to test the first entity I have to create many more, related entities, but I don't want to ;). Other thing I don't really want to do is to change entities/cascades just for test case. I was trying to mock "main" object by Podam (uk.co.jemos.podam.api.PodamFactory) but then I have object references an unsaved transient instance error, because related entities are not saved.

Is there any workaround for this or some other way to mock entity w/o creating referenced objects?

Using Spring with groovy tests.

django rest frame work API Test case (Authentication needed)

I am using (simple JWT rest framework) as a default AUTHENTICATION CLASSES Now I want to write an API test case for one of my view which needed authentication I don't know how to add "access" token and how to use this in rest framework test cases

I will be thankful if you answer to my question

How to mock websocket messages in Cypress

In my team we are using websockets to push some notifications that then update the state of the app. I tried to test changes in UI, but real data is to random and I have to mock it. Unfortunately, as for now I was unsuccessful. I tried to use @lensesio/cypress-websocket-testing plugin, but all I can do with it is catch real data and check what it was.

Is there a way to mock websockets in Cypress? I want my mocked server to send the message, that UI will display in browser and Cypress will assert if it's true. Something like cy.route for websockets.

can't able to mock a variable while testing

I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested. for example

const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i<sample.length;i++)
**some process read and access doc
}

I am facing issue while unit testing the second function I have tried rewire npm that is also not working

Can't delete all browsing data using chromedriver

I have to delete all browsing data to achieve a log out from page.

I've tried:

getDriver().manage().deleteAllCookies();

no result.

What worked (but i don't want to use it, cause i don't like this way) is:

getDriver().get("chrome://settings/clearBrowserData");
getDriver().findElement(By.xpath("//settings-ui")).sendKeys(Keys.ENTER);

Is there a way to achieve same behavior but by managing chromedriver?

chrome version: 83.0.4103.61

How to distribute a macOS app for testing [closed]

I'm an iOS developer with a very little experience with MacOS development. I've built a new MacOS app that I'd like to distribute to some testers but I can't find any Apple doc specific to MacOS apps distribution. All I can find is about iOS which uses Testflight, but it seems MacOS does not have the equivalent.

For now I send directly the .app to my testers, but it makes the versioning management very unclean and bug reporting very hard to track.

Do you know any 3rd party tool I could use? Thanks

Automation of processing test steps in ALM

I will have the same Test sets and Test cases but placed in Test Lab in a different folder with each testing cycle. I could have all the test cases and steps downloaded to Excel and have a column with Pass/Fail indication. I would like to have the execution of steps automated based on the results of that Excel file. How could a script find the right path in Test Lab and the right test set and so on?

The problem is that even if I copy all the test sets the copies will have different names in the element structure, for instance once test set's name is 'Test Set 101' and its copy 'Test Set 1105'.

Angular 9 Component Test: Export of name 'ngbNav' not found

I have a modal component which I would like to test. But it is always complaining about "Export of name 'ngbNav' not found". Any ideas would be great on how to solve this.

Error: Export of name 'ngbNav' not found!
        at cacheMatchingLocalNames (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:13112:1)
        at resolveDirectives (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12871:1)
        at elementStartFirstCreatePass (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:21229:1)
        at ɵɵelementStart (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:21271:1)
        at TemplateModalComponent_Template (ng:///TemplateModalComponent.js:381:9)
        at executeTemplate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:12129:1)
        at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11899:1)
        at renderComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:13509:1)
        at renderChildComponents (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11700:1)
        at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11925:1)

template-modal.component.html

    <div class="modal-header">
  <h4 class="modal-title" ngbTooltip="" triggers="click:blur">template_edit</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <form class="form" [formGroup]="this.templateFormGroup">
    <div formGroupName="template">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Name</label>
            <div class="col-sm-9">
              <input type="text" class="form-control" name="name" formControlName="name" required/>
            </div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Instrument Type</label>
            <div class="col-sm-9">
              <input type="text" class="form-control" name="instrumentType" formControlName="instrumentType" value="DERIVATIVE" readonly />
            </div>
          </div>
        </div>
      </div>
      <div class="row" *ngIf="isStandardTemplate">
        <div class="col-md-6">
          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Publisher</label>
            <div class="col-sm-9">
              <select class="form-control" formControlName="publisherId" (change)="resetAdvertiser()">
                <option [value]="null">select-choose</option>
                <option [value]="p.id" *ngFor="let p of publisher | orderBy:'name'"></option>
              </select>
            </div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Advertiser</label>
            <div class="col-sm-9">
              <select class="form-control" formControlName="advertiserId" (change)="resetPublisher()">
                <option [value]="null">select-choose</option>
                <option [value]="a.id" *ngFor="let a of advertiser | orderBy:'name'"></option>
              </select>
            </div>
          </div>
        </div>
      </div>
      <div class="row justify-content-end mb-3" *ngIf="!isStandardTemplate">
        <div class="col-3">
          <button class="btn btn-secondary form-control" (click)="createStandardTemplateModal()">Standard Templates</button>
        </div>
      </div>
      <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs justify-content-center">
        <li [ngbNavItem]="1">
          <a ngbNavLink>Filter</a>
          <ng-template ngbNavContent>
            <ngb-alert type="secondary" *ngIf="!filter || filter.length == 0">Keine Filter vorhanden. Bitte anlegen!
            </ngb-alert>
            <div class="table-responsive" *ngIf="filter.length > 0">
              <table class="table">
                <thead>
                <tr>
                  <th>Name</th>
                  <th>Variable</th>
                  <th>criteria</th>
                  <th>comment</th>
                  <th></th>
                </tr>
                </thead>
                <tbody>
                <tr *ngFor="let f of filter | orderBy:'name'">
                  <td></td>
                  <td></td>
                  <td><span class="badge badge-pill badge-secondary mr-1" *ngFor="let i of f.filterCriteria">
                      
                      </span></td>
                  <td></td>
                  <td>
                    <span class="prodo-icon prodo-delete-icon cursor-pointer float-right" (click)="deleteFilter(f.id)" ngbTooltip="delete"></span>
                    <span class="prodo-icon prodo-edit-icon cursor-pointer float-right" *ngIf="f.id" ngbTooltip="edit" (click)="chooseFilter(f.id)"></span>

                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div class="row">
              <div class="col">
                <button type="button" class="btn btn-secondary"
                        (click)="newFilter()">filter_new</button>
              </div>
            </div>
          </ng-template>
        </li>
        <li [ngbNavItem]="2">
          <a ngbNavLink>HTML-Template</a>
          <ng-template ngbNavContent>
            <div class="row">
              <div class="col-md-12">
                <editor formControlName="html" required name="html" [init]="tinyMceConfig"></editor>
              </div>
            </div>
          </ng-template>
        </li>
        <li [ngbNavItem]="3">
          <a ngbNavLink>disclaimer_page_end</a>
          <ng-template ngbNavContent>
            <div class="row">
              <div class="col-md-12">
                <editor formControlName="disclaimer" name="disclaimer" [init]="tinyMceConfig">
                </editor>
              </div>
            </div>
          </ng-template>
        </li>
        <li [ngbNavItem]="4">
          <a ngbNavLink>disclaimer_at_ad</a>
          <ng-template ngbNavContent>
            <div class="row">
              <div class="col-md-12">
                <editor formControlName="disclaimerJson" name="disclaimerJson" [init]="tinyMceConfig">
                </editor>
              </div>
            </div>
          </ng-template>
        </li>
      </ul>
    </div>
  </form>
  <div [ngbNavOutlet]="nav" class="mt-2"></div>

</div>
<div class="modal-footer">
  <button type="button" class="btn btn-light" (click)="activeModal.dismiss()">Close</button>
  <button type="button" class="btn btn-success" (click)="passBack()" [disabled]="!templateFormGroup.valid">Speichern
  </button>
</div>

template-modal.component.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {NgbActiveModal, NgbModal} from '@ng-bootstrap/ng-bootstrap';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {StandardTemplateModalComponent} from "./standard-template-modal/standard-template-modal.component";
import {FilterModalComponent} from "./filter-modal/filter-modal.component";
import {Filter} from "../../../model/filter.model";
import {Publisher} from "../../../model/publisher.model";
import {Advertiser} from "../../../model/advertiser.model";
import {Template} from "../../../model/template.model";
import {PublisherService} from "../../../services/publisher.service";
import {AdvertiserService} from "../../../services/advertiser.service";
import {FilterService} from "../../../services/filter.service";
import {TemplateService} from "../../../services/template.service";
import {InstrumentAttributeService} from "../../../services/instrument-attribute.service";
import {StandardTemplate} from "../../../model/standard-template.model";

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

  @Input()
  public template;
  @Input()
  advertisementId: string;
  @Input()
  isStandardTemplate: boolean;

  filter: Filter[] = [];
  publisher: Publisher[];
  advertiser: Advertiser[];
  standardTemplates: Template[];
  templateFormGroup: FormGroup;
  usedInstrumentTypesInFilter: string[];
  fieldsOfInstrumentType: any[] = new Array<string>();
  tinyMceConfig: any;

  @Output() passEntry: EventEmitter<any> = new EventEmitter();
  active = 1;


  constructor(
    public activeModal: NgbActiveModal,
    public publisherService: PublisherService,
    public advertiserService: AdvertiserService,
    private filterService: FilterService,
    private templateService: TemplateService,
    private instrumentAttributeService: InstrumentAttributeService,
    private fb: FormBuilder,
    private modalService: NgbModal) {
  }

  ngOnInit() {
    this.loadData();
    this.configureTinyMce();
  }

  createFormGroup() {
    return this.fb.group({
        template: this.fb.group(this.template),
        standardTemplate: new FormControl('')
      }
    );
  }

  loadData() {
    this.publisherService.get().subscribe((data: Publisher[]) => { this.publisher = data; });
    this.advertiserService.get().subscribe((data: Advertiser[]) => { this.advertiser = data; });
    if (!this.isStandardTemplate) {
      this.templateService.getSuitableStandardTemplates(this.advertisementId)
        .subscribe( data => {
          this.standardTemplates = data;
        });
    }
    this.templateFormGroup = this.createFormGroup();
    this.filterService.get(this.template.id)
      .subscribe( data => {

        this.filter = data;
        this.usedInstrumentTypesInFilter = this.filter.map( f => f.zertartId).filter((el, i, a) => i === a.indexOf(el));

        for ( const instrumentType of this.usedInstrumentTypesInFilter) {
          this.filterService.getFilterCriteria(instrumentType).subscribe( fields => {
            this.fieldsOfInstrumentType[instrumentType] = fields;
          });
        }
      });
  }

  createStandardTemplateModal() {
    const modalRef = this.modalService.open(StandardTemplateModalComponent, { centered: true, size: 'lg' });
    modalRef.componentInstance.advertisementId = this.advertisementId;
    modalRef.result.then((result: StandardTemplate) => {
      if (result) {
        // Updating form with values from Standard Template
        this.templateFormGroup.get("template").patchValue(result);
        // Result Object for saving
        const template = this.createTemplateResult();
        this.templateService.putTemplate(this.advertisementId, template).subscribe( t => {
          // Template is saved, now fetch all filter and add them to the template
          this.filterService.get(result.id).subscribe( data => {
            for (const f of data) {
              // setting the new template id of the filter and remove its id, as it will receive a new one
              f.abstractTemplateId = t.id;
              f.id = null;
              this.filterService.post(f).subscribe( _ => this.activeModal.close() );
            }
          });
        });
      }
    });
  }

  newFilter() {
    const modalRef = this.modalService.open(FilterModalComponent, { centered: true, size: 'xl' });
    modalRef.componentInstance._templateId = this.template.id;
    modalRef.result.then((result: Filter) => {
      if (result) {
        this.filterService.post(result).subscribe(_ => {
          this.loadData();
        });
      }
    });
  }

  deleteFilter(filterId: string) {
    this.filterService.delete(filterId).subscribe( _ => {
      this.loadData();
    });
  }

  chooseFilter(filterId: string) {
    const modalRef = this.modalService.open(FilterModalComponent, { centered: true, size: 'xl' });
    modalRef.componentInstance.filterId = filterId;
    modalRef.result.then((result: Filter) => {
      if (result) {
        this.filterService.put(filterId, result).subscribe(_ => {
          this.loadData();
        });
      }
    });
  }

  configureTinyMce() {
    const that = this;

    this.tinyMceConfig = {
      menubar: false,
      branding: false,
      height: 300,
      base_url: '/tinymce',
      suffix: '.min',
      inline: false,
      valid_elements: '*[*]',
      plugins: [
        'advlist lists link image directionality',
        'searchreplace visualblocks visualchars media table paste pagebreak code'
      ],
      toolbar: 'filterbutton filterIterationButton | undo redo formatselect table | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat hr pagebreak code',
      table_resize_bars: false,
      setup: function (editor) {
        const test = that.filter.map(f => {
          if ( f.maximumNumberOfResults <= 1) {
            return {
              type: 'nestedmenuitem',
              text: f.templateVariableName,
              icon: 'template',
              getSubmenuItems: function () {
                return f.allowedFields.map(field => {
                  return {
                    type: 'menuitem',
                    text: field,
                    icon: 'paste-text',
                    onAction: function () {
                      editor.insertContent(
                        '<span th:text="${' + f.templateVariableName + '.' + field + '}">' + f.templateVariableName + '.' + field + '</span>'
                      );
                    }
                  };
                });
              }
            };
          } else {
            return [];
          }
        });
        const filterIteration = that.filter.map(f => {
          if (f.maximumNumberOfResults > 1) {
            return {
              type: 'nestedmenuitem',
              text: f.templateVariableName,
              icon: 'template',
              getSubmenuItems: function() {
                const filterWithMultipleResults = (element: Filter) => element.maximumNumberOfResults > 1;
                if ( that.filter.some(filterWithMultipleResults) ) {
                  return f.allowedFields.map( field => { return {
                    type: 'menuitem',
                    text: field,
                    icon: 'paste-text',
                    onAction: function () {
                      const iteration =
                        '<table>' +
                        '<tr th:each="item: ${' + f.templateVariableName + '}">' +
                        '<td th:text="${item.' + field + '}" />' +
                        '</tr>' +
                        '</table>';
                      console.log("inserting:");
                      console.log(iteration);
                      editor.insertContent(iteration);

                    }
                  }; });
                } else {
                  return [];
                }

              }
            };
          } else {
            return [];
          }

        });
        /* example, adding a toolbar menu button */
        editor.ui.registry.addMenuButton('filterbutton', {
          text: 'Filter',
          fetch: function (callback) {
            callback(test);
          }
        });
        editor.ui.registry.addMenuButton('filterIterationButton', {
          text: 'Filter Iteration',
          fetch: function (callback) {
            callback(filterIteration);
          }
        });
      },
      image_advtab: true,
      imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
      paste_data_images: !0,
      importcss_append: !0,
      images_upload_handler: function (e, t, a) {
        t('data:' + e.blob().type + ';base64,' + e.base64());
      },
    };
  }

  resetAdvertiser() {
    this.templateFormGroup.get("template").get("advertiserId").reset();
  }

  resetPublisher() {
    this.templateFormGroup.get("template").get("publisherId").reset();
  }

  createTemplateResult() {
    let result;
    if (this.isStandardTemplate) {
      result =  Object.assign({}, this.templateFormGroup.get('template').value) as StandardTemplate;
    } else {
      result =  Object.assign({}, this.templateFormGroup.get('template').value) as Template;
    }
    result = Object.assign({}, result);
    return result;
  }

  passBack() {
    const result = this.createTemplateResult();
    this.activeModal.close(result);
  }

}

In my test file I am going this way:

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

import {TemplateModalComponent} from './template-modal.component';
import {HttpClient} from "@angular/common/http";
import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing";
import {RouterTestingModule} from "@angular/router/testing";
import {TranslateLoader, TranslateModule} from "@ngx-translate/core";
import {HttpLoaderFactory} from "../../../app.module";
import {FormBuilder, FormsModule, NgForm} from "@angular/forms";
import {NgbActiveModal, NgbModal, NgbNav, NgbNavConfig} from "@ng-bootstrap/ng-bootstrap";
import {AdslotService} from "../../../services/adslot.service";
import {ErrorHandlingService} from "../../../services/error-handling.service";
import {ToastService} from "../../../services/toast.service";

describe('TemplateModalComponent', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
          }
        }),
      ],
      declarations: [ TemplateModalComponent ],
      providers: [
        FormsModule,
        NgbActiveModal,
        AdslotService,
        ErrorHandlingService,
        ToastService,
        FormBuilder,
      ]
    }).compileComponents();
    // Inject the http service and test controller for each test
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);

  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(TemplateModalComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
});

I really appreciate any hints or helping steps to debug this. Cheers Maik

How to simple test the file download and upload?

I have two api for file download and upload. (/static/{filename} api for downloading, /upload api for uploading) For consistency, it need a test file to ensure the functionality of them two. I check the official fs_test.go, but it is too massive to use, is there a trick way to do it?

Using @InjectMock for panache repository fails when using rest-assured

We have a simple Quarkus project implementing an n-tier architecture. We would like to test the API using Rest Assured, by mocking the Repository layer.

@QuarkusTest
class ContactResourceTest {
    @InjectMock
    private ThirdPartyPanacheRepository thirdPartyRepository;

    @Test
    void doTest() throws BusinessException {
        given()
                .contentType(MediaType.APPLICATION_JSON)
                .body(new MyDTO())
                .when()
                    .post("/my/route")
                .then()
                    .statusCode(200);
    }
}

The exception I get is:

org.junit.jupiter.api.extension.TestInstantiationException: Failed to create test instance

    at io.quarkus.test.junit.QuarkusTestExtension.initTestState(QuarkusTestExtension.java:397)
    at io.quarkus.test.junit.QuarkusTestExtension.interceptTestClassConstructor(QuarkusTestExtension.java:378)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestClassConstructor(InvocationInterceptor.java:72)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:77)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:333)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:280)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:77)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:262)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:256)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:255)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:108)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:107)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    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.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at io.quarkus.test.junit.QuarkusTestExtension.initTestState(QuarkusTestExtension.java:394)
    ... 59 more
Caused by: org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.company.repository.ThirdPartyPanacheRepository_ClientProxy.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 11
JVM vendor name    : Oracle Corporation
JVM vendor version : 11.0.3+12-LTS
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 11.0.3+12-LTS
JVM info           : mixed mode
OS name            : Windows 10
OS version         : 10.0


Underlying exception : java.lang.IllegalArgumentException: Unknown type: null
    at io.quarkus.test.junit.mockito.internal.CreateMockitoMocksCallback.createMockAndSetTestField(CreateMockitoMocksCallback.java:36)
    at io.quarkus.test.junit.mockito.internal.CreateMockitoMocksCallback.beforeAll(CreateMockitoMocksCallback.java:27)
    ... 64 more
Caused by: java.lang.IllegalArgumentException: Unknown type: null
    at net.bytebuddy.description.type.TypeDefinition$Sort.describe(TypeDefinition.java:228)
    at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection$OfMethodParameter.resolve(TypeDescription.java:6623)
    at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection.accept(TypeDescription.java:6106)
    at net.bytebuddy.description.method.ParameterDescription$TypeSubstituting.getType(ParameterDescription.java:1057)
    at net.bytebuddy.description.method.ParameterList$AbstractBase.asTypeList(ParameterList.java:109)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asTypeToken(MethodDescription.java:845)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Harmonized.of(MethodGraph.java:922)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Store.registerTopLevel(MethodGraph.java:1107)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyzeNullable(MethodGraph.java:615)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:629)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyzeNullable(MethodGraph.java:615)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:629)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:471)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:207)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3404)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:173)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
    at org.mockito.Mockito.mock(Mockito.java:1908)
    at org.mockito.Mockito.mock(Mockito.java:1817)
    ... 66 more

I also tried without using @InjectMock, instead using QuarkusMock.installMockForType in a @BeforeAll method, as documented here. This fails at the moment when the business code attempts to call a method on the repository, with the following error:

org.jboss.resteasy.spi.UnhandledException: java.lang.ClassCastException: class org.mockito.codegen.ThirdPartyRepository$MockitoMock$1469313994 cannot be cast to class com.company.repository.ThirdPartyPanacheRepository (org.mockito.codegen.ThirdPartyRepository$MockitoMock$1469313994 is in unnamed module of loader net.bytebuddy.dynamic.loading.MultipleParentClassLoader @7836c79; com.company.repository.ThirdPartyPanacheRepository is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @7072bc39)

How can I install a mock for my test?

jeudi 28 mai 2020

How to test FileReader wrapped inside promise?

Current code:

export const readFilePromise = file => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = error => {
      reject(error);
    };
  });
};

I am able to test the onload method

it('readFilePromise method', async () => {
    const fileContentsEncodedInHex = [
      '\x45\x6e\x63\x6f\x64\x65\x49\x6e\x48\x65\x78\x42\x65\x63\x61\x75\x73\x65\x42\x69\x6e\x61\x72\x79\x46\x69\x6c\x65\x73\x43\x6f\x6e\x74\x61\x69\x6e\x55\x6e\x70\x72\x69\x6e\x74\x61\x62\x6c\x65\x43\x68\x61\x72\x61\x63\x74\x65\x72\x73'
    ];
    const blob = new Blob(fileContentsEncodedInHex);
    const result = readFilePromise(blob);
    const output = await result;
    const expectedOutput =
      'data:;base64,RW5jb2RlSW5IZXhCZWNhdXNlQmluYXJ5RmlsZXNDb250YWluVW5wcmludGFibGVDaGFyYWN0ZXJz';
    expect(output).toEqual(expectedOutput);
  });

I wonder how do I test the onerror?

How to test/mock API calls using JEST in Create react app

Hello I'm trying to test my async action creators in create react app but I don't have enough information to fix the issue. This is my first time to test async actions in react. I'm using axios for fetching API and jest mock to create a mock functions.

Here's fetch function:

export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}

here's my test:

import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockResolvedValue({ data: {} });

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});

Here's the error that I'm getting but dont understand because I am mocking it as a Resolved value but it goes to my catch block in my actual API call. Weird.

enter image description here

How to test a Redux-Saga API GET request which sends data to the API

Saga Code, works fine, it shows a list of restaurants based on the city you input.

export function* fetchRestaurantsAsync({ cityName }) {
  try {
    const data = yield call(fetchRestaurants,cityName);
    yield put(receiveRestaurants(data));
  } catch (e) {
    yield put(requestFailed(e));
  }
}

export default function* watchFetchRestaurant() {
  yield takeLatest(RESTAURANTS_REQUEST, fetchRestaurantsAsync);
}

Redux-Saga Test File

import fetchRestaurants from "api";
import { runSaga } from 'redux-saga';
import {fetchRestaurantsAsync} from 'sagas'

test("should load restaurants in case of success", async () => {

 const dispatchedActions = [];

  const fakeStore = {
    getState: () => ({cityName:'Toronto'}),
    dispatch: (action) => dispatchedActions.push(action),
  };

  await runSaga(fakeStore, fetchRestaurantsAsync).done;
  console.log(dispatchedActions)
});

This is my test error


    TypeError: Cannot destructure property 'cityName' of 'undefined' as it is undefined.

      4 | import fetchRestaurants from "api";
      5 | 
    > 6 | export function* fetchRestaurantsAsync({ cityName }) {
        |                                          ^
      7 |   try {
      8 |     const data = yield call(fetchRestaurants,cityName);
      9 |     yield put(receiveRestaurants(data));

      at fetchRestaurantsAsync (src/sagas/index.js:6:42)

all the examples I have found don't show how to pass in the data, in this case the name of the city. They are just fetch requests that don't manipulate the URL. I am passing in the city name at the end of the url.