lundi 19 avril 2021

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?