lundi 19 avril 2021

How to test react hooks using jest and mock? My unit test isn't working

I'm trying to write a test for my LED hook, but it's not working. I need to test if the code is calling the Set Behavior. I'm using toHaveBeenCalled, but I'm missing something.

When I run the test shows this message:

useLED › should call setBehavior()

    expect(jest.fn()).toHaveBeenCalled()

What I need to do? Please someone help me!!! Thank you.

My hook:

const useLED = (page: ICMSDataErrorPage | ICMSSuccessPage | undefined) => {
  const ledService = useService<ILEDService>(LEDServiceConstants.ServiceName);

  const startLEDAnimation = async () => {
    await ledService.startAnimation();
  };
  const stopLEDAnimation = async () => {
    await ledService.stopAnimation();
  };

  useEffect(() => {
    if (page) {
      const { red, green, blue, white, behavior } = page;

      ledService.setColor({
        red,
        green,
        blue,
        white,
      });
      ledService.setBehavior(behavior);
      startLEDAnimation();
    }
    return () => {
      stopLEDAnimation();
    };
  }, []);
};

export default useLED;

MY TEST:

describe("useLED", () => {
  let ledService : ILEDService;
  let page: ICMSDataErrorPage | ICMSSuccessPage | undefined;
  beforeEach(() => {
    ledService = mock<ILEDService>();
    page = mock<ICMSDataErrorPage | ICMSSuccessPage | undefined>();
    when(useService as jest.Mock)
      .calledWith(LEDServiceConstants.ServiceName)
      .mockReturnValue(ledService)
  });
  it("should call setBehavior()", () => {
    renderHook(() => useLED(page));
    expect(ledService.setBehavior).toHaveBeenCalled();
})});

junit does not appear even after adding the dependency in pow.xml

i'm learning java with springboot and i can't use junit annotations in my classes.

when I put @RunWith (SpringRunner.class) or @ExtendWith (SpringExtension.class) it doesn't even appear Cannot solve symbol as if I hadn't added the dependency in pow.xml, follow the full pow.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.fquadros</groupId>
    <artifactId>minhasfinancas</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>minhasfinancas</name>
    <description>Projeto para gerenciamento de finanças pessoais</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
        <!-- Dependencia para poder rodar testes feitos em Junit 4 -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

I'm using the IDE: Intelij 2018.2.8

what I've tried to do:

after I added the dependencies I went to build / rebuild Project

in the intelij terminal i already did the mvn clean commands and then the mvnInstall

at the time of installation I get several errors:

https://codepen.io/flavionfg/full/KKaQVbG

to use junit do i need to do anything other than that?

thanks in advance!

How to read a JSON for just one time and use it many time in the same robot file in Robot Framework

I am implementing a test automation framework with using robot framework. But i couldn't manage some JSON things.. I have a robot file full of keywords (no tests), i tried to read the json file (with full of xpaths) in test setup section, but it failed.

Is it possible to read the file at the beginning of a robot file and use that object for every keyword in that list?

Current structure:

keyword 1
  read json
  do sth

keyword 2
  read json
  do sth

keyword 3
  read json
  do sth

What i want?

read json

keyword 1
  do sth
keyword 2
  do sth
keyword 3
  do sth

How to raise timeout error in unittesting

This is first time i am touching ruby, so no sure about correct terminology. I have tried searching for mulitple things, but couldn't find a solution.

I have this code block

domain_response = MyDomain::Api::MyApi::Api.new(parameters: message.to_domain_object, timeout: 1000)
# :nocov:
case (response = domain_response.response)
when MyDomain::Api::MyApi::SuccessResponse
  ## do something
when Domain::ErrorResponses::TimeoutResponse
  ## do something.

now i am trying to testing TimeoutResponse, I have written(tried) this

      it "when api call timesout" do
        expect(MyDomain::Api::MyApi::Api).to{
          receive(:new)
        } raise_error(MyDomain::ErrorResponses::TimeoutResponse)
      end

this gave me error that unexpected identifier.

I have also tried by not providing receive, and it gave me error that block is expected.

Whats the proper way to raise an error that i can test?

How to add query param to send request url using a pre request script postman?

I would like to be able to add a query param to the pre request script sendRequest url shown below, but havent been able to figure out how to do that.... I have tried to use different options to no avail. Thanks for the help!

pm.sendRequest({
        url: pm.globals.get("base_url") + bankNum + "/loans/" + loan14,
        method: 'GET',
        header: {
        'Authorization': '********',
        },
    }, function (err, response) {
        console.log(response.json());
    });

What is the best way to await functions in UI testing in Android Studio without Thread.Sleep()?

I'm using Espresso to write some automated tests for an Android app that I've developed. All the tests are automated and are passing/failing according to what happens with the UI. I've ran the code through SonarQube to detect bad coding practices and it's informed me that Thread.Sleep() should not be used.

I'm mainly using Thread.sleep() in instances where I'm typing out a form and need to hide the keyboard to scroll down to tap the next form field etc. From my understanding, using something like awaitility is for big async functions like fetching data etc. but what should I use in my case where something is not being fetched but more so for just interacting with the UI?

Here is an example of a log in test that I have created that uses Thread.Sleep():

        onView(withId(R.id.fieldEmail)).perform(typeText("shelley@gmail.com"));
        Thread.sleep(SHORT_WAIT);
        onView(withId(R.id.fieldPassword)).perform(click());
        onView(withId(R.id.fieldPassword)).perform(typeText("password"));
        Thread.sleep(SHORT_WAIT);
        onView(isRoot()).perform(pressBack());
        Thread.sleep(SHORT_WAIT);
        onView(withId(R.id.signIn)).perform(click());
        Thread.sleep(LONG_WAIT);

jest/enzym expect.any(ReactComponent)

may be some of you faced with testing features when need to check specification. I am faced with want to test files of themes which look like some thing like this.

export { ReactComponent as SVG1 } from './svg1.svg';
export { ReactComponent as SVG2 } from './svg2.svg';
// ... etc

I was find the way how to check... But it doesn't provide 100% sure it's will be React Component.

const ReactComponent = expect.any(Function);

const svgSchema = expect.objectContaining({
  SVG1: ReactComponent,
  SVG2: ReactComponent,
});

May be some who knows how to define more smart/elegant solution ?

P.S. I do not want to test @svgr/webpack functionality. Within project will be a lot of different themes and i want to make sure they contain required SVG for each theme

How to create complex Integration Test with 2 Web API using C# (NUnit)?

I have an application that works as shown on the figure:

My app scheme

The idea behind is:

Both Web API (Web API #1, Web API #2) are part of my application (2 projects in 1 solution).

step 1: Requesting the endpoint of Web API #1. Web API #1 stores a record to database with status NEW.

step 2: Web API #1 returns a response to a caller (For example: Your request has been accepted).

step 3: Web API #1 has a demon inside. The demon sees a new record in the database with status NEW and make a request to Web API #2.

step 4: Web API #2 do some work (For example: 10 seconds) and returns a response to Web API #1. Web API #1 updated the record in database with status PROCESSED.

I know how to test the endpoint of Web API #1 (WebApplicationFactory etc...), but I want to test full cycle: request to Web API #1 -> record with status NEW -> request to Web API #2 -> response -> record with status Processed -> We have record with status PROCESSED? => Test is done.

iPad / iPhone: Slow down application start time for testing purpose

Could someone advice any tools / techniques in order to slowdown application start time on iOS device. Most articles are focused around performance improvement, however I am interested in opposite scenario.

How to interact with Angular ColorPicker components using Selenium WebDriver?

How to interact with Angular ColorPicker components using Selenium WebDriver? There's no text field input for hex codes, and it's operated purely by mouse clicks. An example of it can be seen here: https://www.primefaces.org/primeng/showcase/#/colorpicker

pytest fails due to ModuleNotFoundError, but works when using "python -m pytest"

Similarly to this OP's issue, but the other way around, pytest works for me within my virtual environment ("venv") only when running python -m pytest, but not with just running pytest in my console.

I'm working with VS Code on Windows 10 within the built-in console.

The command pytest does not work in neither scenario: neither in the global scope, nor in the target venv. By contrast, python -m pytest works within said venv.

I'm working with CLI from the root directory of the project whose full directory tree is:

(Testing) PS C:\Users\user\Documents\Programming\Testing> tree /F
Folder PATH listing for volume Windows
Volume serial number is 50BE-501E
C:.
│   default_python_script.py
│
├───.benchmarks
├───.pytest_cache
│   │   .gitignore
│   │   CACHEDIR.TAG
│   │   README.md
│   │
│   └───v
│       └───cache
│               lastfailed
│               nodeids
│               stepwise
│
├───.vscode
│       launch.json
│       settings.json
│
├───cli_testapp
│   │   cli_testapp.py
│   │   __init__.py
│   │
│   └───__pycache__
│           cli_testapp.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───my_sum
│   │   my_sum.py
│   │   __init__.py
│   │
│   └───__pycache__
│           my_sum.cpython-39.pyc
│           __init__.cpython-39.pyc
│
├───tests
│   │   errors_pytest.log
│   │   test.py
│   │   testing.py
│   │   test_with_pytest.py
│   │
│   ├───.benchmarks
│   ├───.pytest_cache
│   │   │   .gitignore
│   │   │   CACHEDIR.TAG
│   │   │   README.md
│   │   │
│   │   └───v
│   │       └───cache
│   │               lastfailed
│   │               nodeids
│   │               stepwise
│   │
│   └───__pycache__
│           test.cpython-39.pyc
│           testing.cpython-39.pyc
│           test_with_pytest.cpython-39-pytest-6.2.3.pyc
│           test_with_pytest.cpython-39.pyc
│
└───__pycache__
        test.cpython-39.pyc
        testing.cpython-39.pyc

What's annoying about it is that I'd like to use the helpful VS Code testing kit, which facilitates employing any testing framework, also pytest. The problem is that VS Code uses the following command by default to run the testing:

python c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py discover pytest -- --rootdir c:\Users\user\Documents\Programming\Testing -s tests

As one can inspect, it uses pytest instead of python -m pytest. Apparently, the default way of implementation via VS Code doesn't load correctly the environmental variables, since it always produces the following error:

Test Discovery failed:
Error: ============================= test session starts =============================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: c:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 0 items / 1 error

=================================== ERRORS ====================================
_________________ ERROR collecting tests/test_with_pytest.py __________________
ImportError while importing test module 'c:\Users\user\Documents\Programming\Testing\tests\test_with_pytest.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\.pyenv\pyenv-win\versions\3.9.0a4\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_with_pytest.py:22: in <module>
    from cli_testapp import cli_testapp
E   ModuleNotFoundError: No module named 'cli_testapp'
=========================== short test summary info ===========================
ERROR tests/test_with_pytest.py
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
==================== no tests collected, 1 error in 0.23s =====================

Traceback (most recent call last):
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "c:\Users\user\.vscode\extensions\ms-python.python-2021.3.680753044\pythonFiles\testing_tools\adapter\pytest\_discovery.py", line 44, in discover
    raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 2)

For the sake of completeness, I'm going to post how it looks like with python -m pytest within the venv correctly loaded (CLI utilized here):

(Testing) PS C:\Users\user\Documents\Programming\Testing> python -m pytest
=================================================================== test session starts ===================================================================
platform win32 -- Python 3.9.0a4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: C:\Users\user\Documents\Programming\Testing
plugins: benchmark-3.4.1
collected 7 items

tests\test_with_pytest.py .F....F                                                                                                                    [100%]

======================================================================== FAILURES =========================================================================
____________________________________________________________________ test_always_fails ____________________________________________________________________

    def test_always_fails():
        """Function docs:\n
        See above with function docs of "test_always_passes()".
        """
>       assert False
E       assert False

tests\test_with_pytest.py:46: AssertionError
______________________________________________________________ test_initial_transform[dict] _______________________________________________________________

generate_initial_transform_parameters = ({'city': 'Anytown', 'name': ...})

    def test_initial_transform(generate_initial_transform_parameters):
        test_input = generate_initial_transform_parameters[0]
        expected_output = generate_initial_transform_parameters[1]
>       assert cli_testapp.initial_transform(test_input) == expected_output
E       AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
E         Omitting 5 identical items, use -vv to show
...

tests\test_with_pytest.py:118: AssertionError
================================================================= short test summary info =================================================================
FAILED tests/test_with_pytest.py::test_always_fails - assert False
FAILED tests/test_with_pytest.py::test_initial_transform[dict] - AssertionError: assert {'city': 'Any...e': 'FL', ...} == {'city': 'Any...Public'], ...}
=============================================================== 2 failed, 5 passed in 0.31s ===============================================================

How can I resolve this issue that it'll always work, also with just pytest? This is particularly important, because I'd love to leverage the amenities provided by VS Code, which employs a default command based on just pytest.

How to combine different testInstrumentationRunner

Is there any way to have different testInstrumentationRunner for each test? Do I have to create a Task for it? I have my runner as follows :

class MyTestRunner : AndroidJUnitRunner() {
    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, MyTestApp::class.java.name, context)
    }
}

But what if I want to run some using the real app? how can I choose it?

I've been reading that is possible doing it with @RunWith(AndroidJUnit4ClassRunner::class)on my tests I'm using it but I understand if I do this it takes the one of the defaultConfig

defaultConfig {
        testInstrumentationRunner("mypackage.MyTestRunner")
}

But I can not use something like

@RunWith(MyTestRunner::class)

In case I could do this I'd understand how can I use different runners.

Unable to interact with dropdown using CCS selector

I'm Currently trying to work with a dropdown on Testcafe. I have been struggling to interact with this please see error message provided: 1) The specified selector does not match any element in the DOM tree. > | Selector('.rtv-specialties.btn')

What I'm trying to select ^ arrow

Style sheet

<div class="col-md-6  rtv-specialties"><!--!-->
    <div class="form-group"><!--!-->
                <label class="col-form-label col-form-label-sm  dxbs-fl-cpt" for="Specialties"><!--!-->
                    Specialty<!--!-->
                </label><!--!-->
                <!--!--><!--!-->
                    <div class="dxbs-fl-ctrl"><!--!--><!--!--><!--!--><!--!-->

<div id="ide2d65ebf-ef95-4339-99b5-5f45b4d24c06" class="dxbs-dropdown-edit dxbs-combobox  valid" _bl_401af617-1215-41ca-8a5e-05f4d6d1c311="" data-dispose-id="63754436394711968"><!--!-->
    <!--!--><!--!--><!--!--><div class="input-group input-group-sm dx-listbox"><!--!-->
    <!--!--><!--!-->
        <!--!-->
    <!--!-->
    <div><!--!-->
        <!--!-->
            <!--!--><!--!-->
        <!--!-->
        <input id="Specialties" name="idc97c1635-39d6-4393-ad3c-173d858afa80" type="text" class="form-control form-control-sm dxbs-form-control text-truncate dx-reset-readonly-style" autocomplete="off" readonly="" placeholder="Choose..." data-blured-class="form-control form-control-sm dxbs-form-control dx-reset-readonly-style text-truncate" data-focused-class="form-control form-control-sm dxbs-form-control dx-reset-readonly-style text-truncate" _bl_f4380398-d403-43bb-b216-7f347c17e16d="" style="padding-right: 46.6px;"><!--!-->
        <!--!-->
        <!--!-->
    </div><!--!-->
        <div class="form-control form-control-sm input-group-append dxbs-input-group-append dxbs-focus-hidden" _bl_c0f56011-62d0-48f0-8006-939ec5ba268d=""><!--!-->
            <!--!--><span class="dxbs-feedback "><!--!-->
    <!--!--><!--!--><!--!-->        <button class="btn btn-sm dx-btn dxbs-edit-btn dxbs-clear-btn" id="id09de5a6a-83af-440b-845d-dd975b127628" aria-label="Clear value" tabindex="-1" type="button"><!--!-->
            <!--!-->
        <!--!--><svg class="dx-blazor-clear-button-icon" role="img">
            <use href="#dxsc-clear-button-icon"></use>
        </svg>
    <!--!-->
        </button><!--!-->
<!--!-->
</span><!--!-->
            <!--!-->
            <!--!--><!--!--><!--!-->        <button class="btn btn-sm dx-btn  btn-secondary dxbs-edit-btn dropdown-toggle dxbs-dropdown-toggle" id="id2886515b-19cf-4d4f-b553-534352486075" data-toggle="dropdown-show" aria-haspopup="true" aria-expanded="false" aria-label="Open or close the drop-down window" tabindex="-1" type="button"><!--!-->
            <!--!-->
<!--!-->
                    <span></span><!--!-->
        <!--!-->
        </button><!--!-->
<!--!-->

How to run load test for 3000 users with 50 loops in jmeter?

I tried to run a load test in jmeter with 3000 users and 50 loops.But it shows this error.

[9.746s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 4k, detached.
Uncaught Exception java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached in thread Thread[StandardJMeterEngine,5,main]. See log file for details.

I also tried to increase the Heap size using- HEAP:="-Xms2g -Xmx2g -XX:MaxMetaspaceSize=2g"

But the same issue of OutOfMemory persits. Thanks for the help

ReactJS :: Jest Testing :: "TypeError: Cannot read property 'then' of undefined"

I am currently having some trouble compiling a test for an online study task to see whether the fetch() function of my weather application is working correctly.

I have made use of the useEffect() hook to fetch the data from the OpenWeather API to store and render once the API's URL changes.

I am new to Jest testing and have tried a couple of things, following tutorials and other sources, but am unfortunately not having any success. My current solution is returning the following error: "TypeError: Cannot read property 'then' of undefined"

Please see below my code:

App.js

// Imported hooks and react libraries.
import React, { useState, useEffect } from 'react';
// Imported stylesheet.
import './App.css';
// Imported components.
import Header from './components/Header';
import Footer from './components/Footer';
// Imported countries from i18n-iso-countries to get the iso code and return the country name in English.
import countries from 'i18n-iso-countries';
// Imported icons from Font Awesome.
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCloudSunRain,
  faHandHoldingWater,
  faHandSparkles,
  faMapMarkerAlt,
  faSearchLocation,
  faTemperatureHigh,
  faTemperatureLow,
  faWind
} from '@fortawesome/free-solid-svg-icons';

countries.registerLocale(require('i18n-iso-countries/langs/en.json'));

function App() {
  // Setting the initial states of the app to store the response and the locations. Using the useState hook to set the data. Showing Durban as 
  // an example.
  const [apiData, setApiData] = useState({});
  const [getState, setGetState] = useState('Durban');
  const [state, setState] = useState('Durban');

  // Constructing the API URL and accessing the key via the process.env variable.
  const apiKey = process.env.REACT_APP_API_KEY;
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${state}&APPID=${apiKey}`;
  console.log (process.env.REACT_APP_API_KEY);

  // Using the useEffect hook to fetch the data from the API to store and render once the API's URL changes.
  useEffect(() => {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((data) => setApiData(data));
  }, [apiUrl]);

  // Constructed an input handler to get the data once requested and to store in the getState.
  const inputHandler = (event) => {
    setGetState(event.target.value);
  };

  // Constructed a submit handler to handle the request once the search button is clicked.
  const submitHandler = () => {
    setState(getState);
  };

  // Constructed a kelvin to celsius converter to output the temperature in celsius.
  const kelvinToCelsius = (k) => {
    return (k - 273.15).toFixed(2);
  };

  // Constructed a miles to kilometers converter to output the temperature in kilometers.
  const milesToKilometers = (k) => {
    return (k * 3.6).toFixed(2);
  };

  // Created a function to capitalize the first letters of each part of the countries' names.
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  };

  // Returning the data. Included the React Bootstrap stylesheet's link and called the "Header" and "Footer" components below. I also called the
  // following from the API:

  // {apiData.weather[0].icon} - The icon displaying the current conditions.
  // {apiData.name} - The city's name.
  // {countries.getName(apiData.sys.country, 'en', { select: 'official', })} - The country's name with the first letters capitalized.
  // {kelvinToCelsius(apiData.main.temp_min)} - The minimum temperature.
  // {kelvinToCelsius(apiData.main.temp_max)} - The maximum temperature.
  // {kelvinToCelsius(apiData.main.feels_like)} - The "feels like" temperature, taking into account the temperatures and conditions.
  // {apiData.weather[0].main} - The summarized condition.
  // {capitalizeFirstLetter(apiData.weather[0].description)} - The full condition's description.
  // {apiData.main.humidity} - The humidity percentage.
  // {milesToKilometers(apiData.wind.speed)} - The wind speed.

  // Called the inputHandler (input section) and submitHandler (button) to get the current state's values and added Font Awesome icons. Also 
  // added a loading message for if the page load takes a while. Currently only shows if there is no input or upon refresh.
  return (
    <div className="App">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"></link>
      <Header />

      <div className="container">
        <div className="searchsection">
          <label htmlFor="location-name">Enter Location:</label>
          <input
            type="text"
            id="location-name"
            onChange={inputHandler}
            value={getState}
          />
          <button onClick={submitHandler}><FontAwesomeIcon icon={faSearchLocation} /></button>
        </div>

        <div className="mt-3 mx-auto" style=>
          {apiData.main ? (
            <div id="weathercontainer">
              <div id="mainweather">
                <img
                  src={`http://openweathermap.org/img/wn/${apiData.weather[0].icon}@2x.png`}
                  alt="weather status icon"
                  className="weather-icon"
                />
                <p className="h2">{kelvinToCelsius(apiData.main.temp)}&deg;C</p>
                <h3><FontAwesomeIcon icon={faMapMarkerAlt} /> {apiData.name}</h3>
                <h3>{countries.getName(apiData.sys.country, 'en', { select: 'official', })}</h3>
              </div>

              <div className="temperatureconditions">
                <div id="temperature">
                  <h5>Temperature:</h5>
                  <p><FontAwesomeIcon icon={faTemperatureLow} /> {kelvinToCelsius(apiData.main.temp_min)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faTemperatureHigh} /> {kelvinToCelsius(apiData.main.temp_max)}&deg;C</p>
                  <p><FontAwesomeIcon icon={faHandSparkles} /> Feels like: {kelvinToCelsius(apiData.main.feels_like)}&deg;C</p>
                </div>
                <div id="conditions">
                  <h5>Conditions:</h5>
                  <p><FontAwesomeIcon icon={faCloudSunRain} /> {apiData.weather[0].main}: {capitalizeFirstLetter(apiData.weather[0].description)}</p>
                  <p><FontAwesomeIcon icon={faHandHoldingWater} /> Humidity: {apiData.main.humidity}%</p>
                  <p><FontAwesomeIcon icon={faWind} /> Wind Speed: {milesToKilometers(apiData.wind.speed)} km/h</p>
                </div>
              </div>
            </div>
          ) : (
            <h1 id="loading">Weather Bot is Loading...</h1>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
}

// Exported App to Index.js.
export default App;

App.Fetch.React.test.js

import React from 'react';
import App from '../App';
import { render, screen, act } from '@testing-library/react';

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () =>
            Promise.resolve({
                value: "Durban"
            }),
    })
);

describe("App", () => {
    it("loads Durban city name", async () => {
        await act(async () => render(<App />));
        expect(screen.getByText("Durban")).toBeInTheDocument();
    });
});

Does anyone mind helping?

Can mechanical engineering experience count in IT field as Software developer?

I'm mechanical engineer and I want to work at IT company as a 'Software developer'. I've 2Years experience in mechanical industry, So can this experience should be counted in IT Company?

How to Upload txt file with Cypress for API Testing - XMLHTTPRequest?

I'm trying to test an endpoint which will upload a file and give 200 response status code in cypress. As per some research cy.request cannot be used to upload a file for multipart/form-data so we need to use XMLHttp to upload such files. I have created below file to test the api but it doesn't work. Can someone please help what's wrong with my code ? Thank you.

Added below code under support/commands.ts(I will require a header to pass token from auth endpoint)

// Performs an XMLHttpRequest instead of a cy.request (able to send data as FormData - multipart/form-data)
Cypress.Commands.add('form_request', (method,URL, formData,headers, done) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, URL);
        xhr.setRequestHeader("accept", "application/json");
        xhr.setRequestHeader("Content-Type", "multipart/form-data");
    if (headers) {
        headers.forEach(function(header) {
            xhr.setRequestHeader(header.name, header.value);
        });
    }
        xhr.onload = function (){
            done(xhr);
        };
        xhr.onerror = function (){
            done(xhr);
        };
        xhr.send(formData);
})

Test file to call multipartFormRequest:

const fileName = 'test_file.txt';
                    const method = 'POST';
                    const URL = "https://fakeurl.com/upload-file";
                    const headers = api.headersWithAuth(`${authToken}`);
                    const fileType = "application/text";

                    cy.fixture(fileName, 'binary').then((res) => {
                        Cypress.Blob.binaryStringToBlob(res, fileType).then((blob) => {
                            const formData = new FormData();
                            formData.append('file', blob, fileName);

                            cy.multipartFormRequest(method, URL, headers, formData, function (response) {
                                expect(response.status).to.equal(200);
                            })
                        })

I'm getting this error message:- Cypress.Blob.binaryStringToBlob(...).then is not a function.

Mock Typeorm QueryBuilder

I need to test a call like this:

    const connection = await getConnection('default');
    const queryBuilder = connection
        .createQueryBuilder(Reading, 'r')
        .where("r.code = :code AND um = 'KWH'", { code: meter.code })
        .andWhere(" measure_date BETWEEN to_date(:startDate,'YYYY-MM-DD') AND to_date(:endDate,'YYYY-MM-DD')", {
            startDate,
            endDate,
        })
        .andWhere('r.deleted_at IS NULL')
        .orderBy('r.measure_date', 'DESC')
        .addOrderBy('r.reading_type')
        .addOrderBy('r.band', 'ASC');

    const readings = await queryBuilder.getMany();

i tried many solutions, but none worked. any suggestions?

thx to all

Testing service with http still gives provider not found while importing HttpClientTestingModule

I'm starting making tests for my Angular project but get stuck with some problems while testing my service which is using HTTP.

Bases on other discussion I've already imported the HttpClientTestingModule but I still get a error that the provider is not found..

My code currently looks like:

import { TestBed } from '@angular/core/testing';
import {
  HttpClientTestingModule,
} from '@angular/common/http/testing';

import { AuthenticationService } from './authentication.service';

describe('AuthenticationService', () => {
  let service: AuthenticationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
    });
    service = TestBed.inject(AuthenticationService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

And the given error while running the code is:

NullInjectorError: R3InjectorError(DynamicTestModule)[ErrorInterceptor -> AuthenticationService -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11049:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11216:1)
...

I hope someone knows what to do.

Specflow step file doesn't appear to be recognised by feature file

I created a Specflow project which has one feature file, EBIntegrationTest.feature :

Feature: EBIntegrationTest for MF
    Initial test feature

@mytag
Scenario: Subscribe to Market Data EU Topic and write to SQL DB
    Given MD messages are streaming to MF application
    When MF enriches template 304
    Then the enriched messages are then written to an SQL DB server

I then added a step file to my Steps folder:

using System;
using System.Collections.Generic;
using System.Text;

namespace eb_test_tool.Steps
{
    class EBIntegrationTest
    {
        [Given(@"MD messages are streaming to MF application")]
        public void GivenMDMessagesAreStreamingToMFApplication()
        {
            var processInfo = new ProcessStartInfo("C:\\ProgramData\\CME\\Java_SymLinks\\JDK8_x64\\jre\\bin\\java.exe",
                                                   "java -jar .\\Jar\\Injector\\MD-Injector-1.0.jar My.TOPIC")
            {
                CreateNoWindow = true,
                UseShellExecute = false
            };
            Process proc;

            if ((proc = Process.Start(processInfo)) == null)
            {
                throw new InvalidOperationException("Message injector failed to run");
            }

            proc.WaitForExit();
            int exitCode = proc.ExitCode;
            proc.Close();
        }
        
        [When(@"MF enriches template (.*)")]
        public void WhenMFEnrichesTemplate(int p0)
        {
            ScenarioContext.Current.Pending();
        }
        
        [Then(@"The enriched messages are then written to an SQL DB server")]
        public void ThenTheEnrichedMessagesAreThenWrittenToAnSQLDBServer()
        {
            ScenarioContext.Current.Pending();
        }

    }
}

When I run dotnet test it is skipped with this alert:

enter image description here

Am I doing something wrong or should I reference my steps file from the feature file in some way?

Is it possible play a video and record the timestamp in UFT?

I'm new to automation testing and UFT. I'm trying to play a video and record its timestamp through automation in UFT one. Please let me know if its possible, if so, how? I'm testing on a Web application

Is TDD based on unit test?

I search a lot but couldn't find any right answer for this question. Some articles define TDD which you can do any sort of test in it. Some articles just said TDD is just about function test, and when it comes to acceptance test it will be BDD not TDD. So...

Is TDD really just unit test?

dimanche 18 avril 2021

How to parametrize different numbers or positions of arguments?

For example, say I have two functions:

def func3(a, b, c):
    for var in (a, b, c):
        if var < 0:
            raise ValueError
    pass


def func7(a, b, c, d, e, f, g):
    for var in (a, b, c, d, e, f, g):
        if var < 0:
            raise ValueError
    pass

And in my tests, I want to test a set of invalid values at each parameter. The only way I know of to do this is to write them all out:

@pytest.mark.parametrize('val', [-2, -3, -4.5])
def test_invalid_param(val):
    with pytest.raises(ValueError):
        func3(val, 0, 0)
    with pytest.raises(ValueError):
        func3(0, val, 0)
    with pytest.raises(ValueError):
        func3(0, 0, val)
    with pytest.raises(ValueError):
        func7(val, 0, 0, 0, 0, 0, 0)
    with pytest.raises(ValueError):
        func7(0, val, 0, 0, 0, 0, 0)
    with pytest.raises(ValueError):
        func7(0, 0, val, 0, 0, 0, 0)
    ...

How can I combine these all into one with pytest.raises case?

If both funcs had the same number of arguments, I could stack this:

@pytest.mark.parametrize('func', [func3, func7])

but they don't. If they just had different numbers of arguments and I was only testing the first, then I could stack this:

@pytest.mark.parametrize('func, args', [(func3, (0, 0)), 
                                        (func7, (0, 0, 0, 0, 0, 0))])

But that won't work for testing the parametrized value in multiple positions.

Is clojure.spec check generating bad input?

Using clojure.spec (org.clojure/clojurescript {:mvn/version "1.10.520"}), I have a function spec that specifies a map for its input.

gen/generate and gen/sample work fine. But calling cljs.spec.test.alpha/check errors with input that should be a map, but is passed a collection (Error: More than one element found in structure). Ie, it looks like the spec system is generating bad input.

Is this a bug with spec?

bar spec

(s/def ::check-run
  (s/keys
    :req-un
    [::action
     ::check_run
     ::installation
     ::organization
     ::repository
     ::sender]))

foo.cljs

(s/def ::payload :bar/check-run)
(s/def ::check-run-started (s/keys :req-un [::payload]))

(s/fdef check-run->cijob-created
  :args (s/cat :arg ::check-run-started))

(defn check-run->cijob-created [arg])

While the function spec only declares A, the spec system is generating B.

;; A
{:payload {:action "", :check_run {:html_url "", }}, ...}

;; B
[({:payload {:action "", :check_run {:html_url "", }}, ...}})]

workbench

(cljs.spec.test.alpha/check
  `foo/check-run->cijob-created
  {:clojure.spec.test.check/opts {:num-tests 10}})


[{:spec #object[cljs.spec.alpha.t_cljs$spec$alpha50916],

  :clojure.spec.test.check/ret
  {:shrunk
   {:total-nodes-visited 313, :depth 148, :pass? false, :result #object[Error Error: More than one element found in structure: 0], :result-data #:clojure.test.check.properties{:error #object[Error Error: More than one element found in structure: 0]}, :time-shrinking-ms 11299,
    :smallest
    [({:payload {:action "", :check_run {:html_url "", }}, ...}})]},

  :sym foo/check-run->cijob-created,
  :failure #object[Error Error: More than one element found in structure: 0]}]


  [1]: https://clojure.org/about/spec

Mocha cannot find module

I am trying to write simple Unit Test with Mocha & Chai in my React Client ( I am using typescript in my react client).

Unfortunately I am not able to start the test, because my module can not be found (App.tsx). My path is correct, 100%. I am using Typescript, so that it is an App.tsx file instead of App.js . My assumption is that typescript is blocking something. But I do not know what.

SyntaxError: Cannot use import statement outside a module

babel.config.js

module.exports = (api) => {
  const presets = ['react-app']
  const plugins = [
    '@babel/plugin-transform-modules-commonjs',
    'inline-react-svg',
  ]

  api.cache(false)

  return {
    presets,
    plugins,
  }
}

package.json

 "test": "NODE_ENV=test mocha  --require @babel/register --require       ignore-styles src/test/*.test.js",

App.test.js

import React from 'react'
import { configure, shallow } from 'enzyme'
import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import Adapter from 'enzyme-adapter-react-16'
import App from '../App.tsx'
configure({
  adapter: new Adapter(),
})
describe('Testin <App/> Component', () => {
  it('App renders a message', () => {
    const wrapper = shallow(<App />)
    const message = (
      <p>
        Edit <code>src/App.tsx</code> and save to reload.
      </p>
    )
    expect(wrapper).to.contain(message)
  })
  chai.use(chaiEnzyme())
})

How can I test a react-native library locally?

I currently created the package and created the "Example" folder inside it. The goal is to be able to test the react-native package itself from the "Example" folder.

I tried with npm link but it seems that it is not supported. So I tried "yarn add ../" but it is a tedious process that often requires continuous deletion of node_modules. I tried "npm pack" with which I create the .tgz and then import the tgz into Example with yarn. Is it really that complicated to test a react-native library locally or is there an easier way that doesn't require continuous deletion of node_modules?

Mocking axios requests on specific urls with jest

I'd like to know if it's possible to mock axios requests with different values depending on url. I use jest and typescript. Now I have this working example:

import axios from 'axios';
import { mocked } from 'ts-jest';
jest.mock('axios');
    
const mAxios = mocked(axios, true);
mAxios.get.mockResolvedValue({
  data: [
    {
      id: 1,
      title: 'john doe',
    },
    {
      id: 2,
      title: 'keyboard cat',
    },
  ],
});

It works but as you can see it always returns the same value no matter to where request was send. I'm wondering how can I achieve my goal.

Accordion is failing accessibility check

I have an accordion that is rendered using van11y-accessible-accordion-aria

The markup outputs as:

        <div className="c-accordion__items js-accordion accordion" data-accordion-cool-selectors="1" aria-multiselectable="true" role="tablist" id="z3j2diubs8r" data-hashaccordion-id="3o3nlqickh">
<!-- note role="tablist" above -->
          
          <div className="c-accordion__item">
        
            <h2 className="c-accordion__title accordion__title">
              <button className="js-accordion__header accordion__header" role="tab" id="accordionz3j2diubs8r_tab1" aria-controls="accordionz3j2diubs8r_panel1" aria-selected="false" type="button" data-hashaccordion-id="3o3nlqickh" aria-expanded="false">
<!-- note role="tab" above -->
              The Why
              </button>
            </h2>
        
    <div className="c-accordion__item-components js-accordion__panel accordion__panel" role="tabpanel"
                 aria-labelledby="accordionz3j2diubs8r_tab1" id="accordionz3j2diubs8r_panel1" data-hashaccordion-id="3o3nlqickh"
                 aria-hidden="true">
              <div className="c-accordion__item-content">
                <p>Duis vel nibh at velit scelerisque suscipit. Donec vitae sapien ut libero venenatis faucibus. Quisque ut
                  nisi. Ut non enim eleifend felis pretium feugiat. Nulla sit amet est.</p>
              </div>
            </div>
        
          </div>
        </div>

When I test this for accessibility using Lighthouse in Chrome, I am getting these messages

Elements with an ARIA [role] that require children to contain a specific [role] are missing some or all of those required children. Some ARIA parent roles must contain specific child roles to perform their intended accessibility functions. Learn more.

[role]s are not contained by their required parent element Some ARIA child roles must be contained by specific parent roles to properly perform their intended accessibility functions. Learn more.

The learn more links goes to https://web.dev/aria-required-children

enter image description here

... and there it implies that having role="tablist" as the parent and then role="tab" for the child.

In my code posted in this question, I seem to have the proper markup as compared to the example from https://web.dev/aria-required-childre

So I am at a loss as to why this is failing the accessibility check.

Flutter how to mock function response when it is called in tested function

I am trying to test some api call function:

  Future<SomeType> getType(int id) async {
    String token = await retrieveToken();
    String api = await getApiEndpoint();
    final response = await client.get("$api/something/$id", headers: { "Authorization": "Bearer $token"});
    if (response.statusCode == 200) {
      String body = utf8.decode(response.bodyBytes);
      return SomeType.fromJson(json.decode(body));
    } else {
      throw Exception('Failed to load some types from API');
    }
  }

The two functions:

retrieveToken();
getApiEndpoint();

that are called inside are not members of the same class as getType() function. They also contain inside them instances of FlutterSecureStorage().

I don't need to test this function, I just want to mock their responses in the test of getType function.

I've created following test example:

class MockedApiEndpoint extends Mock implements ApiEndpoint {}
void main() {
    WidgetsFlutterBinding.ensureInitialized();
    test('returns SomeType', () async {
      final typesRepository = TypesRepository();
      final mockedApiEndpoint = MockedApiEndpoint();

      when(mockedApiEndpoint.getApiEndpoint()).thenAnswer((_) async => Future.value("some_url.com"));
      when(mockedApiEndpoint.retrieveToken()).thenAnswer((_) async => Future.value("some_token"));

      typesRepository.client = MockClient( (request) async {
        final mapJson = {'id' : 123};
        return Response(json.encode(mapJson), 200);
      });

      final type =  await typesRepository.getType(123);
      expect(type.id, 123);
    });
}

I was able to succesfully Mock the client reposne, I am also trying to mock responses of those two functions, but I am constantly receiveing following error:

MissingPluginException(No implementation found for method read on channel plugins.it_nomads.com/flutter_secure_storage)

I would be very greatful for any hints how to approach this topic and what I am doing wrong with this one. I am new to unit testing in Flutter, I've tried to find any similar problem to mine on the web but unfortunatelly failed.

Chaos Testing Tool for Kubernetes environment - with Java client

I'm looking for a chaos testing tool to run in a Kubernetes environment.

I have a micro-services environment in which every service runs on a separate pod.

I'm looking to cause network connectivity issues, file system errors, services crash, and so on.

I want to do it - and this is the most important part - when the system and each service are in a particular state (pre-conditions).

I researched a few tools Like Litmus and Chaos Mesh.
If I understood correctly, the issue with them is that they are operating from outside of the Kubernetes cluster.
I define a custom resource for each chaos scenario, and whenever I invoke it, the chaos begins without consideration to the current state of the machine.

I'm looking for a tool that can do all this chaos while considering the existing state of the services.
I guess it means it should be done somehow from within the code itself, while having access to all the services and their state.

All my eco-system is written in Java.
So far, what I found is a tool called Toxiproxy, but I'm not sure it can shut down services and bring them up as part of the chaos.

Are you familiar with other tools that can be used for chaos from within the code and have a Java client?

Thanks

what is the real benefit of using software testing

I know that software testing (ex: unit, integration) makes sure that my functionality is working as expected, but I do not know what is its benefit since I can test the flow myself and make sure it is working as I'm expecting it to. so I need to know what is the bigger picture of software testing

palindron using Queue

I need to do a program that I have queue with double numbers and I have to to this a palindrome queue.

for example, head-> 1,1,2,2,3,3,4,4->end after the program: head-> 4,3,2,1,1,2,3,4->end

any ideas?

Testing a custom hook with jest

I have an input text field, where when a user types, I am setting a state and passing the setter as onChange function, something like this-

const [searchText, setSearchText] = React.useState('');

// Invoke input component 

<input type='input' onChange={setSearchText} />

// When input changes, debounce it and call another function

useDebounceFunction();

I want to write tests for this chunk of code- I have written when input changes, then the setter should be invoked and that's working fine, but how can I write a test in jest for debounce function? When my input text is changing, then after 1 sec, I am invoking a function inside debounce handler.

NEGATIVE TEST CASES [closed]

negative test cases for sharing a post on twitter?

samedi 17 avril 2021

How to configure Cookies with Cypress?

I'm trying to configure Cypress to have a Cookie in each request header. How do I achieve this? I'm trying this way:

it('successfully loads', () => {
    cy.visit('http://localhost:4200', { headers: { Cookie: 'JSESSIONID=064063D96094773DACBD93A2FD31736F' } });
});

Testing Apollo - one query with multiple results

I'm trying to test all possible values for a custom hook I did, based on the result of a query.

To do that, I'm using MockedProvider from Apollo client. The problem is because I can't find an easy way to mock different responses not copy-pasting multiple MockedProvider with different mocked data.

import React, { ReactElement, FunctionComponent } from 'react';
import { MockedProvider } from '@apollo/client/testing';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { renderHook } from '@testing-library/react-hooks';
import { QUERY_BANNER } from '../queries';
import { contentBanner } from '../types';
import { useBannerProfile, images } from '../use-banner-profile';
const mocks = [
  {
    request: {
      query: QUERY_BANNER,
    },
    result: {
      data: {
        stateBanner: {
          type: 'contacts',
          __typename: 'StateBanner',
        },
      },
    },
  },
];
const Stack = createStackNavigator();
const MockedNavigator: FunctionComponent = ({ children }) => {
  const MockedScreen = (): ReactElement => <>{children}</>;
  return (
    <MockedProvider mocks={mocks}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="MockedScreen" component={MockedScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </MockedProvider>
  );
};
test('title and image for contacts banner', async () => {
  const { result, wait } = renderHook(() => useBannerProfile(), {
    wrapper: MockedNavigator,
  });
  await wait(
    () =>
      result.current.title !== contentBanner.default.title &&
      result.current.backgroundImage !== contentBanner.default.backgroundImage,
  );
  expect(result.current.title).toBe(contentBanner.contacts.title);
  expect(result.current.backgroundImage).toBe(images.contacts);
});

Is there any way to change only the result, for instance:

stateBanner: {
  type: 'other-type',
  __typename: 'StateBanner',
},

I was looking documentation from Apollo and from React Hooks Testing Library, but I couldn't find an answer.

Thanks!

How to test Reac Lazy inside an object

At the project I'm working on, there's a few named exports like the object below:

export const object = {
    component: React.lazy(() => import('some-component'))
}

(They have more properties but I'll just show this one for brevity)

The issue

When I try to test it using Jest, I can't test inside React.lazy:

Screenshot of coverage report

I tried mocking React.lazy with no success:

jest.mock('react', () => ({
  lazy: () => {
    return 'lazy'
  },
}))

describe('Auth route object', () => {
  it('', () => {
    expect(auth).toBeDefined()
    expect(auth[0].component).toBe('lazy')
  })
})

This returns passed but it keeps complaining about coverage.

How can I mock/test that?

ps: I need at least 90% coverage on this file, that's why I can't just ignore it.

Extract the text of a disabled field

[enter image description here][1]

This is the HTML tag for the element. [1]: https://i.stack.imgur.com/8SjU8.jpg

I tried String A = Element.getText() to capture the value but it doesn't capture the text. I tried with

String A = element.getAttribute("value"); but still no text capture.

I tried with javascript executor also

String pageText = js.executeScript("return document.documentElement.innerText;",AdNum).toString();

This is also not capturing the text though it executes the script.

failed test with mock files

Im starting with mock in my unit tests. Wanted to upgrade method to using files. Mocks with some strings or numbers work, but now code has failed test. I have class with method:

public class FileService {
    public List<File> findFilesUsingSuffix(File root, String suffix) {
        List<File> list = new ArrayList<>();
        if (root.isDirectory()) {
            File[] files = root.listFiles();
            if (files != null) {
                for (File file : files) {
                    list.addAll(findFilesUsingSuffix(file, suffix));
                }
            }
        } else if (root.getName().endsWith(suffix)) {
            list.add(root);
        }
        return list;
    }
}

and test:

public class FileServiceTest {
    private FileService fileService;
    private TemporaryFolder temporaryFolder;
 
    @Before
    public void setUp() throws Exception {
        fileService = mock(FileService.class);
 
        temporaryFolder = mock(TemporaryFolder.class);
        File file1 = temporaryFolder.newFile("file.java");
        File file2 = temporaryFolder.newFile("file.swf");
        File file3 = temporaryFolder.newFile("file2.java");
        File file4 = temporaryFolder.newFile("picture.jpg");
        File file5 = temporaryFolder.newFile("photo.jpg");
        File file6 = temporaryFolder.newFile("movie.mp4");
        File file7 = temporaryFolder.newFile("music.mp3");
        File file8 = temporaryFolder.newFile("someFile.java");
        File file9 = temporaryFolder.newFile("someDoc.doc");
        File file10 = temporaryFolder.newFile("excelThing.xls");
        File file11 = temporaryFolder.newFolder("java");
    }
 
    @Test
    public void findFilesUsingSuffixIsTrue() throws IOException {
        //given
        List<File> expectedList = List.of(
                new File("file.java"), new File("file2.java"), new File("someFile.java")
        );
 
        when(fileService.findFilesUsingSuffix(ArgumentMatchers.any(File.class),any(String.class))).thenCallRealMethod();
 
        //when
        List<File> result = fileService.findFilesUsingSuffix(temporaryFolder.getRoot(), ".java");
 
        //then
        assertEquals(expectedList, result);
    }
}

I'm getting empty list in result, but idk what i did incorrectly

How to loop into test using pytest?

I would like to write a login test where the precondition is to make a few authentication requests that need to be done. Each time the JSON with the error msg "invalid" is returned. Then the user is blocked and the error msg is moving to "blocked".

I tried like that:

@pytest.fixture
def event_loop():
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()

def test_block(event_loop):
    r = login("login", variables.INVALID_PASSWORD)
    assert r.json()['error'] == event_loop.run_until_complete((f'User was blocked.'))
    event_loop.run_until_complete

How to run setUp function once per class in Laravel 8 tests?

I would like to run the setUP function just once in a class so all the tests can use the same information since it is read only.

Example: I have my API and in a class I want to test an enpoint that requires an authentication token.For obtaining the authentication token I need to create a user, make the login, and save the token so it can be used to test the endpoint. Right now with the setUp funciton the user is created for each test it would be enough to do it once and share the same token among all the tests. Additionally I am using the RefreshDatabase trait to keep the database clean but I want it as well to run only once per class.

Here I leave a sample code. createUser and loginUser are not implemented here.

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use Tests\TestUtils;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    const  TEST_ENDPOINT = '/myendpoint';

    private string $token;

    public function setUp(): void
    {
        createUser();
        $this->token = loginUser(); //runs for every test
    }

    public function test_endpoint_INVALID_AUTHORIZATION()
    {
        $response = $this->post(self::TEST_ENDPOINT);
        $response->assertStatus(400);
    }

    /*

    ... other tests

    */

    public function test_endpoint_SUCCESS()
    {
        $headers = TestUtils::createHeadersWithBearerToken($this->token);
        $response = $this->withHeaders($headers)
                        ->post(self::TEST_ENDPOINT);
        $response->assertStatus(200);
    }
}

Hspec - snapshot testing in Haskell?

Is there a build-in possibility to create snapshot tests in hspec testing framework? With snapshot, I mean, that the output of a function can be compared to an expected output stored in a file.

Or is there a hackage package to enable this feature?

Is there another package than (1) naniar - , (2) BaylorEdpsych - , (3) MissMech - package including "Littles mcar_test"?

I need to check the origin of my missing Data before I can start multiple imputation. Unfortunately the BaylorEdpsych and the MissMech package are not available on cran anymore and for anyreason the naniar package does not do the mcar_test.

Anyone got an alternative package to do Littles mcar_test? Maybe even a better solution how to check for that?

I know that testing if data is MNAR is almost not possible.. it is the first time I am doing this and theorydriven I would argue that they're missing at random - but as there are a few variables with almost 50% missing values I guess need any statistical proof to determine that they are unlikely to be "Mnar" to justify the multiple imputation procedure.

Cheers!

How to resolve a Bazel label to its jar in a custom test runner, so to be able to extract the packaged unit tests?

Using Bazel we have a macro that we call from our BUILD files to invoke our custom test runner. This macro makes a native call to java_test similar to:

native.java_test(
    name = name,
    srcs = srcs,
    resources = resources,
    use_testrunner = False,
    main_class = "com.example.CustomTestRunner",
    args = srcs,
    deps = deps,
    runtime_deps = runtime_deps + ["//bazel/tools/testng:testng_runner"],
    **kwargs
)

In our BUILD file the target to invoke the macro looks similar to:

java_custom_test(
    name = "test",
    srcs = glob(["src/test/java/**/*.java"]) + [
        ":sdk_gen_model_test",
        ":sdk_gen_controller_test",
    ],
    resources = glob(["src/test/resources/**/*"]),
    deps = [
        "@maven//:org_mockito_mockito_core",
        "@maven//:org_testng_testng",
    ],
)

Passing srcs to args in the macro, the hope is that in CustomTestRunner I can get access to all the unit test files, which is true for those identified by glob(["src/test/java/**/*.java"]).

However, in the case of ":sdk_gen_model_test" and ":sdk_gen_controller_test", these two refer to targets that generate unit tests which are packaged into a jar. Unfortunately, these two label strings are passed as are to the CustomTestRunner and I'm struggle to work out how to resolve the generated jars from them.

So the question is, how can I get Bazel to pass the list of files generated by those two targets to CustomTestRunner, or at least have some way to resolve those labels to the jars, so I can extract the files in CustomTestRunner?

Laravel Dusk - same element click issue

I'm having banner image upload and logo upload page in step progress bar like in https://codepen.io/jidelambo/pen/RaRygY

On banner image upload im taking to cropper page for image cropping (which has save button with id crop-button) similarly, On logo image upload im taking to same cropper page.

            ->assertSee('Banner Section')
            ->attach('image',public_path('images/banner-image.jpg'))
            ->waitFor('.cropper-container')    
            ->click('#crop-button')
            ->waitForReload()
            ->assertSee('Banner Uploaded!!!')
            ->press('Save Banner') 
            ->assertSee('Logo Section')
            ->attach('image',public_path('images/logo-image.jpg'))
            ->waitFor('.cropper-container')    
            ->click('#crop-button')
            ->waitForReload()//Error occurs in this line(Timeout: Waited 5 seconds for page reload. )
            ->assertSee('Logo Uploaded!!!')

For Banner image crop button works fine, but its not working for logo image crop, can you guide me please.Clicking same element causing issue ? How can i rectify this?

How to pass arguments to a test function in laravel throw console

Very newbie here. Apologize if i'm asking something stupid or obvious.

I'm playing around with test in Laravel, and I want to test the same function with different users I've created. Is there a way to pass the id as an argument throw laravel console? I mean, writing something like:

 /** @test */
public function my_test_function($id)
{
    $user = User::find($id);
   ..........................}

And then calling with:

php artisan test --filter my_test_function ....... plus something to pass the id.

Thanks a lot.

vendredi 16 avril 2021

How to test my Dockerfile for my python project using GitHub actions?

  • Sometimes we make errors in writing the docker file. If there is an error in the Dockerfile, the docker build will fail.

  • Sometimes we may forget to specify dependencies in our Dockerfile. Let's take an example.

Suppose, I have a python script that can take the screenshot of any web page (whose URL is supplied).

  • Now, in my code I am using pyppeeteer(Headless chrome/chromium automation library (unofficial port of puppeteer)
  • pyppeeteer uses chromium and chrome driver. These are already installed in my machine. So, running pytest will pass in my local dev environment.
  • I forget to specify the RUN commands in the dockerfile, that will install chromium and chrome driver. so running tests inside the container will fail. (although the docker build will succeed.)

I want to automate the task of building docker images and running tests in the container.

In the local machine, I can run docker build -t myproj . to build.

and for testing, I can run docker run -it myproj pytest (if i forget to add the RUN that installs chromium and chromedriver, then my pytest will fail inside container)

I hope I am able to explain my purpose.

Normally,in github actions,the python source code can be run on ubuntu, mac, windows etc. Besides the different os, I also want to build and test my dockerfile.

how can I do that? Please don't give tutorials to writing github actions. I am looking for an optimized way for achieving my task. My work can be done in many ways, but looking for specific instructions from an expert.

I would like to know how to pick an option from a dropdown in any given web application using Powershell in Selenium? If someone could give me an exp

I would love it if someone could give me a sample code on how to handle a static drop down and pick an option from it in any given website or web application using powershell in Selenium.This would be super helpful.

NullPointerException error while running test

I am new at testing in Java / Spring and when running test, I encounter the following error:

java.lang.NullPointerException at com.company.core.service.impl.StudentServiceImpl.findAllStudentServiceImpl.java:52) at com.company.core.service.impl.integration.StudentServiceImplTest.given_Nothing_When_FindAll(StudentServiceImplTest.java:226)
...

When clicking to link, it points the following method:

public List<StudentDTO> findAll(StudentCriteriaRequest request, Sort sort) {
    if(request.isGraduated()) {
        return getStudentDTOS((studentRepository.findAll(request, sort)).getContent());
    }
    return getStudentDTOS(studentRepository.findAllAndOthers());
}

And here is the test method:

public void given_Nothing_When_FindAll() {
  List<StudentDTO> studentDTOList = new ArrayList<>();

  for (int i = 0; i < 3; i++) { // --> line 52
      CommandDTO commandDTO = createStudent("Student name" + i);
      StudentDTO studentDTO = studentService.findByUuid(commandDTO.getUuid());
      studentDTOList.add(studentDTO);
  }
  List<StudentDTO> response = studentService.findAll(new StudentCriteriaRequest(), Sort.unsorted()); // line 226 --> it throws error at this line while debugging test class
  
  assertEquals(4, response.size());
  assertTrue(response.stream().anyMatch(studentDTO -> studentDTO.getUuid().equals(brandDTO.getStudentUuid())));
  assertTrue(response.stream().anyMatch(studentDTO -> studentDTO.getUuid().equals(studentDTOList.get(0).getUuid())));
  assertTrue(response.stream().anyMatch(studentDTO -> studentDTO.getUuid().equals(studentDTOList.get(1).getUuid())));
  assertTrue(response.stream().anyMatch(studentDTO -> studentDTO.getUuid().equals(studentDTOList.get(2).getUuid())));
}

I have tried to check request parameter if it is null in the first class, but it does not make any sense. So, what is the cause of the problem? And should I fix it on service file (on former method) or test file (on latter block)? As I have not previous experience, I have really no idea about the solution of this problem. Any help would be appreciated.

How to manage path to files for testing modules?

I have a small project with the following directory tree:

enter image description here

The paths to access to 'sets.txt' and 'copy3.png' are referenced to 'main.py'. However, I would like to run standalone the view to test placement issues or adjustments. Doing so will lead to FileNotFound exception. Should I have a variable to set when the view is in 'test mode'?

Which would be the best way to handle the paths?

How to use Cypress.io for E2E testing when back end and front end are in separate repos?

I have a project with a NextJS front end and a FeathersJS/Node back end. Both of these apps/codebases are separate repos. I would like to start using Cypress for E2E testing, but I'm not sure what the best approach is to do that with my set up. Ideally, the tests would run as part of CI for every back end AND front end change. I am currently using GitHub actions for my CI, I'm not sure if that would help or hurt me here.

I've seen some people mention putting Cypress in its own repo with its own docker-compose that would handle spinning up the front end and back end to run the tests. However, I don't understand how this would work as part of CI. How would new code, pre-merge, make its way into this repo to run as part of CI? I think there would be a lot of issues with this approach.

One approach I thought of is to just include Cypress as part of the front end NextJS app and have it run against a "staging" or "test" instance of the back end that gets seeded with every new back end deploy. One of the issues here is that the tests would not run when the back end changes, but that's not necessarily an issue, I suppose.

Any thoughts?

Testing pages with streamfields in Wagtail

I'm parsing HTML in a StreamField's richtext element via get_context, and want to be able to test that the context I've made contains the relevant modifications. But I'm really struggling to create a mock/stub that has a populated StreamField.

I'm looking at https://docs.wagtail.io/en/stable/advanced_topics/testing.html but need to do more than just test whether creation succeeds and the rich_text function etc. don't seem to output in the right format for other matters (like appending to the body attribute); I've had a little success with making fixtures via dumpdata but they're breaking other tests (presumably due to making the database inconsistent or something)

Are there any good examples out there of tests pre-populating a StreamField?

How to check of exceptions in nested functions when using MagicMock objects in Pytest?

I've a function (myfunc), with a validation input a and and c credentials that will setup a service to call func_z.

For some validation input, func_z will throw an error, and in other cases, it'll return some dictionary of values. And I've an outer_func that modifies the output of func_z:

class XError(Excception):
    pass

def myfunc(a, b, c):
    x = c.setup_client('x')
    try:
        x.func_z(a) # Check if x.func_z(a) works proper
    except:
        raise XError
    
    return b**2


def outer_func(a, b, c):
    return myfunc(a, b, c) + 1

When testing the function, I had to mock the c credentials. So I tried to test with:

import pytest
from unittest.mock import MagicMock


test_data = ( (('fr', 5), 26), ('de', 7, 50), (('zh', 5), XError) )

SIDE_EFFECTS = {'fr': {'status': 'okay'}, 'de': {'status': 'okay'}, 'zh': XError}

@pytest.mark.parametrize("a, b", test_data)
def mytest(a, b, expected):
    mock_creds = MagicMock()
    mock_service = MagicMock()
    mock_creds.setup_client.return_value = mock_service
    mock_service.func_z.return_value = SIDE_EFFECTS[a]
    
    assert outer_func(a, b, c) == expected
    

Somehow the XError didn't get raised in the pytest and the output returns 26 for ('zh', 5) inputs instead of XError.

Did I use the return value in the mock objects wrongly?

Is it possible to allow and check for raised error or outputs with mock objects in pytest?

Integration test flutter packages incompatible with a lot of other packages

When trying to implement flutter integration test in dev_dependencies, while running pub get, the output is that integration test flutter dependencies versions are incompatible with other plug-ins. I get the next error:

[-] flutter pub get
Running "flutter pub get" in --...                       
Because no versions of test_coverage_badge match >0.2.0 <0.3.0 and test_coverage_badge 0.2.0 depends on args ^2.0.0, test_coverage_badge ^0.2.0 requires args ^2.0.0.

And because every version of integration_test from sdk depends on args 1.6.0, test_coverage_badge ^0.2.0 is incompatible with integration_test from sdk.

So, because -- depends on both integration_test any from sdk and test_coverage_badge ^0.2.0, version solving failed.
pub get failed (1; So, because -- depends on both integration_test any from sdk and test_coverage_badge ^0.2.0, version solving failed.)
exit code 1

When I solve this one, there are a lot of others. Is flutter integration outdated? Does anyone have a solution to this problem?

flutter doctor -v output:

[√] Flutter (Channel stable, 2.0.4, on Microsoft Windows [Version 10.0.19041.867], locale en-US)
    • Flutter version 2.0.4 at C:\Users\davor\flutter
    • Framework revision b1395592de (2 weeks ago), 2021-04-01 14:25:01 -0700
    • Engine revision 2dce47073a
    • Dart version 2.12.2

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at C:\Users\davor\AppData\Local\Android\Sdk
    • Platform android-30, build-tools 30.0.2
    • ANDROID_HOME = C:\Users\davor\AppData\Local\Android\Sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 4.1.0)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[√] VS Code (version 1.55.2)
    • VS Code at C:\Users\davor\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.21.0

How to get ARGV options on Rails 6.1

Some of my Rails tests require parameters from command line. After Rails 6.1. ARGV has been (for whatever reason) cleared and not available in application.

Is there an alternative way to get parameters send to rails command?

by TheR

CSP local testing

I need to do some changes to our website, as our CSP prevents Safari from accessing it. Also, the whole security rating of the website is, let's put it nicely, rather bad. Now, is there any way to test changes made to CSP locally, without deploying to the server? I tried ngrok, but that doesn't seem to work (doesn't transmit headers). I'm rather new at this, so any tips would be appreciated!

Test for the PUT method responsible for creating a new entity by TestRestTemplate in the E2E test

I'm building my app with Spring. I am currently trying to test a PUT method that can both update and create an entity called Tank:

public class Tank {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    private boolean tested;
    @NotBlank(message = "Name must be not empty")
    private String name;
    private LocalDateTime productionDate;
   
    public Tank() {}

    public Tank(@NotBlank(message = "Name must be not empty") String name, LocalDateTime productionDate) {
        this.name = name;
        this.productionDate = productionDate;
    }

My PUT method in the controller looks like this:

@Transactional
    @PutMapping("tanks/{id}")
    public ResponseEntity<?> updateTask(@PathVariable int id, @RequestBody Tank source) {
        if(repository.existsById(id)) {
            logger.warn("Updating given tank");
            repository.findById(id)
                    .ifPresent(tank -> tank.update(source));
            return ResponseEntity.noContent().build();
        }
        else {
            logger.warn("Creating new tank with given id");
            var newTank = repository.save(source);
            return ResponseEntity.created(URI.create("/" + newTank.getId())).body(newTank);
        }
    }

everything works. I can both update an existing tank and create a new one. The problem comes when I want to test it.

 @Test
    void httpPut_createsNewTank_returnsResponseEntity() throws JSONException {
        // given
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        // and
        String entity = new JSONObject()
                .put("name", "PUT")
                .put("productionDate", "2020-12-02T12:23:00")
                .toString();
        // and
        HttpEntity<String> request = new HttpEntity<>(entity, headers);
        // and
        int id = repo.findAll().size() + 1;
        URI expectedLocation = URI.create("/" + id);

        // when
        var result = testRestTemplate.exchange(baseUrl + port + "/" + id, HttpMethod.PUT, request, Tank.class);

        // then
        assertThat(result.getBody().getName()).isEqualTo("PUT"); // expected: "PUT"   actual: null
        assertThat(result.getHeaders().getLocation()).isEqualTo(expectedLocation); // expected: /1   actual: null
    }

This is a test placed in the E2E test run on RANDOM_PORT where I am using TestRestTemplate. Testing of other methods works fine, so it is not the fault of some configuration. My question is why does the exchange method return body and headers as null?

Cypress: How to test HTML5 built in validation popup?

How can we catch an HTML5 built in popup validation error when testing an App with Cypress? It does not seem to be showing up in the DOM so I have no clue about how to catch it with a cy command (I'm using testing-library).

enter image description here

Can McFadden statistic be used for continuous variables?

I am running a linear GAM (generalized additive model) and trying to do overfitting tests. Is McFadden pseudo R^2 a good statistic to compare models on?

The issue I have is that McFadden stat seems to only be applicable to for discrete models (logit or logistic GLM), correct me if I am wrong.

Why does exception not return the actually raised error?

I'm getting my function tomato_or_potato() to fail for testing as in potato check

def potato_check:
    if not potato:
        raise SpecificError(
            message='No potato.',
            status_code=409,
        )

In my test, I'm trying to assert that SpecificError was raised:

    with assertRaises(Exception) as context:
        tomato_or_potato(tomato)

    assert SpecificError in context.exception

What I'm getting back tho is always a message 'No potato.' and not the actual SpecificError.

jeudi 15 avril 2021

Jest test fails if two methods are mocked

I have a confusing situation on my tests. See the code below.

file.js

class Test {
  constructor() {}

  async main() {
    const a = await this.aux1("name1");
    const b = await this.aux2("name2");
  }

  async aux1(name) {
      console.log(name)
  }

  async aux2(name) {
    console.log(name)
  }
}

module.exports = Test;

file.spec.js

describe('Concept proof', () => {
    const module = require("./file.js");
    const inst = new module();

    test('should call aux1', async () => {
        const a = jest.fn(() => "return");

        inst.aux1 = a
        inst.main()

        expect(a).toHaveBeenCalled()
    });

    test('should call aux2', async () => {
        const b = jest.fn(() => "return");

        inst.aux2 = b
        inst.main()

        expect(b).toHaveBeenCalled()
    });
});

result

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      18 |         inst.main()
      19 |
    > 20 |         expect(b).toHaveBeenCalled()
         |                   ^
      21 |     });
      22 | });

      at Object.<anonymous> (file.spec.js:20:19)

The method aux2 is not invoked if aux1 is called from main, but behave as expected if I remove aux1 call from main.

I was not able to find an explanation for that behave on the docs. I'm misunderstanding something, or the normal behave should be aux2 be called even if aux1 is called before? Any help will be appreciated!

Any help will be apreciated!

How can I handle UsernameNotFoundException?

I've been using some previous examples of testing methods some of my work partners used and they didn't have any problem but when i use them for this project it doesn't work at all. One of my partners saw the methods and he didn't know either what was wrong. This is my test class:

    @Mock
    UserRepository dataRepository;
    
    @Autowired
    protected UserService userService;
    
    private User u;
    

    @BeforeEach()
    void setUp() {
        u = new User();
        u.setId(23L);
        u.setUsername("test");
        u.setPassword("Pass1234.");
        u.setInfo(null);
        this.dataRepository.save(u);
    }
    
    @Test
    void testLoadUserByUsername() throws Exception {
        when(dataRepository.findByUsername(anyString())).thenReturn(u);
        userService.loadUserByUsername("test");
        assertEquals(u, userService.loadUserByUsername(anyString()));
        verify(dataRepository).findByUsername(anyString());


}
        
    @Test
    void testFindAllUsers() throws Exception {
        List<User> user = this.userService.findAllUsers();
        Assertions.assertNotNull(user);
    
}

}

When i execute the test i get the same trace every time and it is, for the first method:

org.springframework.security.core.userdetails.UsernameNotFoundException: User can't be found
    at com.project.UserService.loadUserByUsername(UserService.java:41)

I don't know what could it be because i'm searching the same name i'm setting just a few lines above so if u could help me i would appreciate it.

The UserService class is:

@Autowired
private BCryptPasswordEncoder               passw;

@Autowired
private UserRepository                  userRepository;

@Autowired
private DataRepository  dataRepository;


@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    User user = this.userRepository.findByUsername(username);

    if (user == null) {
        throw new UsernameNotFoundException("User can't be found");
    }

    return user;
}


public List<User> findAllUsers() {

    List<User> l = new ArrayList<User>();
    l = (List<User>) this.userRepository.findAll();

    return l;
}


public void save(final User u) {
    this.userRepository.save(u);
}

}

And the line of the code that is pointed by the exception is:

userService.loadUserByUsername("test");

Thank u so much.

I'm trying to run a test for a method but i always get the same error.

This is my test class:

private Car car;

@Autowired
protected CarService carService;

@Mock
private CarRepository carRepository;

@BeforeEach
void setUp() {
    car = new Car();
    car.setId(4L);
    car.setName("test1");
    car.setUrlCar("https://carconfigurator.ferrari.com/assets/cars/portofinom/packages/default/car-ferrari-portofino-m_splash.jpg");
    car.setColor("red");
    carRepository.save(car);
    }

@Test
void getCarById() throws Exception {
    Car res = this.carService.getCarById(4L);
    Assertions.assertTrue(res != null);
}

The CarService class is:

@Autowired
private carRepository carRepository;

public Iterable<Car> getAllCars(){
    return carRepository.findAll();
}
public Car getCarById(Long id){
    return carRepository.findById(id).orElse(null);
}

The trace is:

org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)

The trace points to the line Assertions.assertTrue(res != null); and i don't know how to solve the error. If u could help me please.

¿TESTEAR EL METODO MAIN EN JAVA CON JUNIT? [closed]

hola¿Como hago un test del el main? por ejemplo

 public static void main(String[] args){
        int pNumero=1;
        int sNumero=2;
        System.out.println("El resultado de la suma es"+(pNumero+sNumero));

}

AssertionFailedError: i dont understand what is wrong in my code

I'm trying to run a test for a method but i always get the same error.

This is my test class:

private Car car;

@Autowired
protected CarService carService;

@Mock
private CarRepository carRepository;

@BeforeEach
void setUp() {
    car = new Car();
    car.setId(4L);
    car.setName("test1");
    car.setUrlCar("https://carconfigurator.ferrari.com/assets/cars/portofinom/packages/default/car-ferrari-portofino-m_splash.jpg");
    car.setColor("red");
    carRepository.save(car);
    }

@Test
void getCarById() throws Exception {
    Car res = this.carService.getCarById(4L);
    Assertions.assertTrue(res != null);
}

The CarService class is:

@Autowired
private carRepository carRepository;

public Iterable<Car> getAllCars(){
    return carRepository.findAll();
}
public Car getCarById(Long id){
    return carRepository.findById(id).orElse(null);
}

The trace is:

org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)

The trace points to the line Assertions.assertTrue(res != null); and i don't know how to solve the error.

Jest - mocking imported function from another file not working

I have been trying to mock a function which is imported in another file and used in a class. There are similar questions here and I went through a lot of them but still failed to get my tests working. Here is the structure of my code:

//util.js
export const stageHelper = (key) => {
    return STAGE_NAMES[key];
};

//main.js
import {stageHelper} from './util'
class Main {
    static config = {
        value: stageHelper('abc'),
    }
    
    static getValue() {
        return this.config.value;
    }
}

//main.spec.js
import * as util from './util';
import {Configuration} from '../configuration/configuration';
jest.mock('./util');

describe('Main', () => {
    const utilSpy = jest.spyOn(util, 'stageHelper').mockImplementation(() => 'testValue');
    //util.stageHelper = jest.fn().mockImplementation(() => 'testValue'); // tried this too
    //utilSpy.mockReturnValue('ja'); // tried this too
    
    expect(Main.getValue()).toEqual('testValue'); // this test fails - the value is 'undefined'
});

I get undefined when calling Main.getValue() from my test. However, I expect this to return testValue since this is what I have mocked the return value as.

Could someone please help me get this right? This would be much appreciated!

Are Abstract Unit and Integration Tests good or bad practice?

TL;DR Question: Is it good or bad practice to write Unit and/or Integration tests that are abstract? (Class ABFTest extends AbstractP44Test)

We've started writing Unit Tests before we started automating running them. So I'm in the process of cleaning up a lot of broken tests. Some that were written for a specific environment, or just no longer work.

I've come across a large abstract class that other tests are dependant on. A lot of the logic in it and its children seem like they need tests themselves.

Is there a smart way to do abstract tests to avoid rewriting code? Or is it a bad practice in general to do this? Should tests always be isolated?

We're new to testing and haven't worked out how things should be done overall.

Bonus: I'm currently marking abstract test classes as ignore with PHPUnit. Does that also ignore all of its children?

protected function setUp(): void
{
    self::markTestSkipped('Abstract Test');
}

Adding an Express.router() REST endpoint in Apollo Server backend? (for e2e tests cleanup)

Is it possible to add an extra endpoint in an Apollo Server backend (besides the existing /graphql endpoint) using Express.router() or some built in Apollo function?

I have tried to add something like this but the route does not seem to be working:

// controllers/testing
import express from 'express';
import resetDatabase from '../database/resetDB';

const router = express.Router();

router.post('/reset', async (_request, response) => {
  await resetDatabase();    
  response.status(204).end();
});

export default router;

And then add the route in index where Apollo Server is created:

// index.ts
import testingRouter from './controllers/testing';

// ...

  if (process.env.NODE_ENV === 'test') {
    app.use('/api/testing', testingRouter);
  }

For the record, I am trying to do this to provide my Cypress e2e tests in an Apollo Client frontend with an endpoint to reset a testing database after running tests, if there is a better way of doing this, feel free to disregard my question and point me to the righteous path =)

org.springframework.security.core.userdetails.UsernameNotFoundException: User can't be found

I created a test class for some methods. I defined an user and then save it, setting its name and other values. I made a method which tells me that it has been saved correctly, but when i search it by username it says it couldn't be found.

This is my test class:

@Mock
private UserRepository userRepository;


@Autowired
private UserService userService;


private Data data;
private User user;


@Test
void shouldSaveUser() {
    Integer before = this.userService.findAllUsers().size();
    User u = new User();
    u.setId(23L);
    u.setUsername("name");
    u.setPassword("Pass1234");
    Data data= new Data();
    data.setId(3L);
    data.setUser(u);
    u.setData(data);
    this.userService.save(u);
    Integer after = this.userService.findAllUsers().size();
    Assertions.assertTrue(before +1 == after);
    
}

@Test
void testUserByUsername() {
UserDetails res = this.userService.loadUserByUsername("name");
Assertions.assertTrue(res != null);
}
    

}

But every time i run the tests the same error happens:

org.springframework.security.core.userdetails.UsernameNotFoundException: User can't be found

So i dont know where is the error. If u could help me please

How to run test suite collection with verbosity of tests in test suite -selenium+python

I am pretty much new to selenium and i am using python as language to write my tests.

I have created a class with all my tests[imagine this is my suite] and then call the class in my main file.[i have the collection here]

I wanted to know how i can display the verbosity of the tests being run even if i am running them as a collection from the suite.

Please let me know if you need more info. For now it is just telling me that my tests is ok or failed. This is how the output is being generated

Thank you

AngularJS Jasmine controller testing, No Pending requests to flush and Unsatisfied requests GET

I'm completely new to using AngularJS and I have been hopelessly trying to write some tests for my Controller script

EmployeeRegister.js

var EmployeeRegister = angular.module("myApp.EmployeeRegister", [])

EmployeeRegister.controller("EmployeeRegisterController", function($scope, $http) {
    $scope.home = "This is the homepage";

    /*
    * The Handshake test function
    **/
    $scope.getRequest = function() {
        console.log("I've been pressed!");
        $http.get("http://localhost:4200/handshake").then(
            function successCallback(response) {
                $scope.response = response;
                console.log(response);
            },
            function errorCallback(response) {
                console.log("Unable to perform get request");
            }
        );
    };


    /*
    * The function to retrieve all employees from the API
    **/
    $scope.getEmployees = function (){
        $scope.employees = [];
        $http.get("http://localhost:4200/").then(
            function successCallback(employees) {
                $scope.employees = employees;
                console.log(employees);
            },
            function errorCallback(employees) {
                console.log("Unable to perform get request");
            }
        );
    };

    $scope.firstname = null;
    $scope.lastname = null;
    $scope.phonenumber = null;
    $scope.mail = null;

    /*
    * The function to post a specified employee to the http://localhost:4200/add URL
    **/
    $scope.postEmployee = function (firstname, lastname, phonenumber, mail){

        var data = {
            firstname: firstname,
            lastname: lastname,
            phonenumber: phonenumber,
            email: mail
        };
        $http.post("http://localhost:4200/add", JSON.stringify(data)).then(
            function successCallback(response){
                console.log(response);
            },
            function errorCallback(reponse) {
                console.log("Unable to perform postrequest");
            }
        );
    };

    /*
    * The function to search for an employee by the ID on the http://localhost:4200/ID URL
    **/
    $scope.getEmployeesByID = function (){
        $scope.employeesByID = [];
        $http.get("http://localhost:4200/" + $scope.id).then(
            function successCallback(employeesByID) {
                $scope.employeesByID = employeesByID;
                console.log(employeesByID);
            },
            function errorCallback(employeesByID) {
                console.log("Unable to perform get request");
            }
        );
    };

    /*
    * The function to delete an employee specified by the ID in the URL on http://localhost:4200/delete/ID
    **/
    $scope.deleteEmployeesWithID = function (){
        $http.delete("http://localhost:4200/delete/" + $scope.id).then(
            function successCallback(response){
                console.log("success");
            },
            function errorCallback(response){
                console.log("could not delete employee");
            }
        );
    };

});

And expectedly my copied and tweaked Code from somewhere in the internet doesn't work, I realize that the reason I'm getting these errors is because there's never any GET requests fired in the test, what I fail to understand is why

EmployeeRegister.spec.js

describe('EmployeeController', function() {
    var $httpBackend, $rootScope, createController, GetAllEmployeesHandler;

    // Set up the module
    beforeEach(module('myApp.EmployeeRegister'));

    beforeEach(inject(function($injector) {
        // Set up the mock http service responses
        $httpBackend = $injector.get('$httpBackend');
        // backend definition common for all tests
        GetAllEmployeesHandler = $httpBackend.when('GET', 'http://localhost:4200/')
            .respond(200, [{firstname: 'Max', lastname: 'Mustermann', phonenumber: '123456', email: 'Max@example.com'},
                {firstname: 'Hans', lastname: 'Mustermuster', phonenumber: '654321', email: 'Hans@example.com'},
                {firstname: 'Peter', lastname: 'mannmann', phonenumber: '246801', email: 'Peter@example.com'}]);

        // Get hold of a scope (i.e. the root scope)
        $rootScope = $injector.get('$rootScope');
        // The $controller service is used to create instances of controllers
        var $controller = $injector.get('$controller');

        createController = function() {
            return $controller('EmployeeRegisterController', {'$scope' : $rootScope });
        };
    }));


    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });


    it('should fetch authentication token', function() {
        var controller = createController();
        $httpBackend.expectGET('http://localhost:4200/').respond(200, [{firstname: 'Max', lastname: 'Mustermann', phonenumber: '123456', email: 'Max@example.com'},
            {firstname: 'Hans', lastname: 'Mustermuster', phonenumber: '654321', email: 'Hans@example.com'},
            {firstname: 'Peter', lastname: 'mannmann', phonenumber: '246801', email: 'Peter@example.com'}]);
        expect($rootScope.employees).toBe([{firstname: 'Max', lastname: 'Mustermann', phonenumber: '123456', email: 'Max@example.com'},
            {firstname: 'Hans', lastname: 'Mustermuster', phonenumber: '654321', email: 'Hans@example.com'},
            {firstname: 'Peter', lastname: 'mannmann', phonenumber: '246801', email: 'Peter@example.com'}]);
        $httpBackend.flush();
        expect($rootScope.status).toBe('');
    });

});

Here's the HTML file if somehow relevant

<!DOCTYPE html>
<html ng-app="myApp.EmployeeRegister">
<head>
    <title>Employee Register</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body ng-controller="EmployeeRegisterController">

<!-- <h2>Handshake test</h2>
 <div ng-init="getRequest()"></div>
 <div ng-controller="testController">
  <h3></h3>
 </div>

 <hr> -->

<div ng-controller="EmployeeRegisterController">
    <h1>Add an employee</h1>
    <label for="fname">First name:</label>
    <input type="text" id="fname" name="fname" ng-model="firstname"><br><br>
    <label for="lname">Last name:</label>
    <input type="text" id="lname" name="lname" ng-model="lastname"><br><br>
    <label for="pnumber">Phone number:</label>
    <input type="text" id="pnumber" name="pnumber" ng-model="phonenumber"><br><br>
    <label for="email">E-Mail:</label>
    <input type="text" id="email" name="email" ng-model="mail"><br><br>
    <input type="submit" value="Submit" ng-click="postEmployee(firstname, lastname, phonenumber, mail)" onClick="window.location.reload();">
</div>

<h1>Employee list</h1>
<div ng-init="getEmployees()"></div>
<div ng-controller="EmployeeRegisterController">
    <div ng-repeat="item in employees.data">
        <div ng-repeat="(key, val) in item">
            : 
        </div>
        <br><br>
    </div>
</div>

<div ng-controller="EmployeeRegisterController">
    <h1>Find an employee</h1>
    <input type="text" id="id" name="ident" ng-model="id">
    <input type="submit" value="Search" ng-click="getEmployeesByID(id)">
    <div ng-controller="EmployeeRegisterController">
        <div ng-repeat="(key, val) in employeesByID.data">
            : 
        </div>
        <br>
        <input type="submit" value="Delete" ng-click="deleteEmployeesWithID(id)" onClick="window.location.reload();">
    </div>
</div>

<script src="EmployeeRegister.js"></script>
</body>
</html>

An explanation of my errors and maybe some tips to write further tests would be appreciated.