i am getting pytest ERROR: Unrecognized arguments: -n 4 error, xdist is installed correctly - pytest-xdist

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import pytest
def test_google():
serv_obj = Service(r"path of chrome")
driver = webdriver.Chrome(service=serv_obj)
driver.get("https://www.google.com/")
assert driver.title=="Google"
driver.quit()
def test_naukri():
serv_obj = Service(r"path of chrome")
driver = webdriver.Chrome(service=serv_obj)
driver.get("https://www.naukri.com/mnjuser/homepage")
assert driver.title=="Jobseeker's Login: Search the Best Jobs available in India & Abroad - Naukri.com"
driver.quit()
def test_gmail():
serv_obj = Service(r"path of chrome")
driver = webdriver.Chrome(service=serv_obj)
driver.get("https://mail.google.com/mail/u/0/#inbox")
assert driver.title=="Gmail"
driver.quit()
def test_instagram():
serv_obj = Service(r"path of chrome")
driver = webdriver.Chrome(service=serv_obj)
driver.get("https://www.instagram.com/")
assert driver.title=="Instagram"
driver.quit()
**
#this is my code, when i tried to parallel execution 'pytest My_directory/test_title.py -n 4', it gives error:
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: -n 4
inifile: C:\path\pytest.ini
rootdir: C:\path\pythonProject\Pytest_Practice**

Related

pytest - mockup a complex module import

I have found several posts on how to "hide" a package and simulate an ImportError with pytest, however, I haven't succeeded in my case and I am looking for some help:
Test for import of optional dependencies in __init__.py with pytest: Python 3.5 /3.6 differs in behaviour
Test behavior of code if optional module is not installed
and related
Here is the content of an __about__.py file that I want to test with pytest.
"""Get the metadata from the package or from setup.py."""
try:
import importlib
metadata = importlib.metadata
except ImportError:
import importlib_metadata as metadata
try:
data = metadata.metadata("mypackage")
__version__ = data["Version"]
__author__ = data["Author"]
__name__ = data["Name"]
except metadata.PackageNotFoundError:
# The repo of the package is accessible to python to get at least the version
import re
from pathlib import Path
try:
from nested_grid_plotter import __file__ as loc
with open(Path(loc).parent.joinpath("../setup.py"), "r") as f:
data = f.read()
except FileNotFoundError:
data = ""
def version_parser(v):
"""Parse the version from the setup file."""
version_pattern = (
r"""(version\s*=\s*)["|'](\d+(=?\.(\d+(=?\.(\d+)*)*)*)*)["|']"""
)
regex_matcher = re.compile(version_pattern).search(v)
if regex_matcher is None:
return "unknwon"
return regex_matcher.group(2)
try:
__version__ = version_parser(data)
except Exception:
__version__ = "unknown"
__author__ = "unknown"
__name__ = "unknown"
Here is the __init__.py at the root of the package:
from .__about__ import __version__, __name__, __author__
And here is the tests that I have come up with until now. However, I am not able to hide importlib.
"""Test the file __about__.py."""
import pytest
import sys
class PackageDiscarder:
def __init__(self):
self.pkgnames = []
def find_spec(self, fullname, path, target=None):
if fullname in self.pkgnames:
raise ImportError()
#pytest.fixture
def no_requests():
sys.modules.pop("importlib", None)
d = PackageDiscarder()
d.pkgnames.append("importlib")
sys.meta_path.insert(0, d)
yield
sys.meta_path.remove(d)
#pytest.fixture(autouse=True)
def cleanup_imports():
yield
sys.modules.pop("mypackage", None)
def test_requests_available():
import mypackage
assert mypackage.__version__ != "unknwon"
#pytest.mark.usefixtures("no_requests")
def test_requests_missing():
import mypackage
assert mypackage.__version__ != "unknwon"
Here is the coverage report:
Name Stmts Miss Cover Missing
----------------------------------------------------------------
mypackage/__about__.py 31 10 68% 5-6, 10-12, 23-24, 33, 38-39
----------------------------------------------------------------
TOTAL 31 10 68%

Pytest: How to parametrize input

Is there a way to pass input to pytest.mark.parametrize()?
If I try…
import pytest
from typing import List
#pytest.mark.parametrize("rotation", range(len(input_sequence)))
def test_sequence_rotation(
input_sequence: List[float],
rotation: int,
) -> None:
sequence = input_sequence[rotation:] + input_sequence[:rotation]
print(f"Testing sequence {sequence}")
… I get NameError: name 'input_sequence' is not defined.
For some context, I have input_sequence defined as a pytest command option in conftest.py:
import pytest
from typing import List
from _pytest.config.argparsing import Parser
from _pytest.fixtures import SubRequest
def pytest_addoption(parser: Parser) -> None:
parser.addoption("--sequence-csv", type=str, required=True)
#pytest.fixture()
def input_sequence(request: SubRequest) -> List[float]:
csv = request.config.getoption("--sequence-csv")
return [float(i) for i in csv.split(",")]
You're referring to a variable input_sequence in your call to #pytest.mark.parametrize, but no such variable is in scope. You would need to define this at the module level (either directly or by importing it from somewhere).
You would also need to remove it from the parameter list of test_sequence_rotation.
E.g., something like:
import pytest
from typing import List
input_sequence = ['a', 'b', 'c', 'd', 'e']
#pytest.mark.parametrize("rotation", range(len(input_sequence)))
def test_sequence_rotation(rotation: int) -> None:
sequence = input_sequence[rotation:] + input_sequence[:rotation]
print(f"Testing sequence {sequence}")
The above code will produce output like this when run via pytest -v:
============================= test session starts ==============================
platform linux -- Python 3.9.4, pytest-6.0.2, py-1.10.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/lars/tmp/python
plugins: cov-2.11.1, flake8-1.0.7, asyncio-0.14.0, xonsh-0.9.26
collecting ... collected 5 items
test_sequence.py::test_sequence_rotation[0] PASSED [ 20%]
test_sequence.py::test_sequence_rotation[1] PASSED [ 40%]
test_sequence.py::test_sequence_rotation[2] PASSED [ 60%]
test_sequence.py::test_sequence_rotation[3] PASSED [ 80%]
test_sequence.py::test_sequence_rotation[4] PASSED [100%]
============================== 5 passed in 0.03s ===============================

How to execute a Scala3 script when system has both Scala2 and Scala3 installed?

I want to execute a following script using Scala3:
#main def m() =
println("Hello, world! I'm a script")
When I type the command, scala hello.scala, I get the following error:
/Users/avirals/dev/learning-scala/hello-world/hello.scala:1: error: not found: type main
#main def m() =
^
one error found
I think it is because I have both the versions of Scala installed (2 and 3). I know how to start a REPL for both (as mentioned here) but I am not able to execute a Scala3 script from the command line.
[Update]
I tried scala3-repl hello.scala and it just opens the REPL:
➜ learning-scala git:(main) scala3-repl hello.scala
scala> m()
1 |m()
|^
|Not found: m
How do I execute a Scala 3 script from the command line given I have two different versions (2 and 3) of Scala installed?
My OS: MacOS
Update 2
As suggested in this answer, I tried running with amm and it worked for a few scripts. However, the following script failed:
Script:
#main def m(args: String*) =
var i = 0
while i < args.length do
println(args(i))
i += 1
Error:
➜ learning-scala git:(main) amm printargs.scala
printargs.scala:2:3 expected (If | While | Try | DoWhile | For | Throw | Return | ImplicitLambda | SmallerExprOrLambda)
var i = 0
^
Running the above script in a Scala3-REPL works:
➜ learning-scala git:(main) scala3-repl
scala> #main def m(args: String*) =
| var i = 0
| while i < args.length do
| println(args(i))
| i += 1
|
def m(args: String*): Unit
scala> m("aviral", "srivastava")
aviral
srivastava
Running the same script in a system (MacOS) that has only Scala3 installed works just fine as well.
There exists currently Minimal scripting support #11379. I was able to get it working by manually downloading a release from https://github.com/lampepfl/dotty/releases/download/3.0.0-RC3/scala3-3.0.0-RC3.zip, unzipping, and giving executable permission to launchers
./scala3-3.0.0-RC3/bin/scala hello.scala
Hello, world! I'm a script
With scala3-repl launcher you could at least do
$ scala3-repl
scala> :load hello.scala
def m(): Unit
scala> m()
Hello, world! I'm a script

Unable to use pytest parameterize functionality to update the YAML config

I am using ruamel.yaml module to update the YAML using python.
I wanted to use pytest parameterize functionality to update the YAML config.
Here is the test.yaml file:
TestConfig:
hostname: 10.2.4.6
Organisation:
Employee:
Name: Smriti
Skilss: Python
OrganizationName: ABC
UserId: smriti_test#gmail.com
Here is the conftest file so that we need to not to explicitly import the fixture functionality:
from ruamel.yaml import YAML
import pytest
#pytest.fixture(scope='function')
def yaml_loader(request):
yaml = YAML()
file_path = 'test.yaml'
with open(file_path) as fp:
data = yaml.load(fp)
test = data['TestConfig']
x = request.param
print(x)
with open(file_path, "w") as file:
yaml.dump(data, file)
print(data)
Here is the implementation of sample testfile for running the test and using the fixture from conftest and update the config in YAML and perform the test.
import pytest
class TestYAML:
""" TestYAML """
#pytest.mark.parametrize("yaml_loader",[("test['Organisation']['Employee']\
['Name']='Arushi'")],indirect=True)
#pytest.mark.usefixtures("yaml_loader")
def test_update_yamlconfig(self):
pass
In the result I am seeing the x is printing the updated Value of Name to Arushi but in the YAML file the config is not updating.
After couple of tries i am able to find the solution to this question.
So Here is the updated code for reference:-
For test file i have taken two different param and i will assign that param individually when i call the fixtures and this has worked
test_yaml.py
import pytest
class TestYAML:
""" TestYAML """
#pytest.mark.parametrize("yaml_loader",
[("hostname","10.5.6.8")],indirect=True)
#pytest.mark.usefixtures("yaml_loader")
def test_update_yamlconfig(self):
pass
Here is the updated conftest where i have defined the fixture:-
from ruamel.yaml import YAML
import pytest
#pytest.fixture(scope='function')
def yaml_loader(request):
yaml = YAML()
file_path = 'test.yaml'
file_path1 = 'my.yaml'
with open(file_path) as fp:
data = yaml.load(fp)
test = data['TestConfig']
test[request.param[0]] = request.param[1]
with open(file_path1, "w") as file:
yaml.dump(data, file)
print(data)
And you will get the output as :-
platform linux -- Python 3.8.0, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 --
/mnt/c/Users/smaheshw/PycharmProjects/YAML/venv/bin/python3.8
cachedir: .pytest_cache
rootdir: /mnt/c/Users/smaheshw/PycharmProjects/YAML
collected 1 item
test_yaml.py::TestYAML::test_update_yamlconfig[yaml_loader0] Request parameters
hostname
ordereddict([('TestConfig', ordereddict([('hostname', '10.5.6.8'), ('Organisation',
ordereddict([('Employee', ordereddict([('Name', 'Smriti'), ('Skilss', 'Python'),
('OrganizationName', 'A
BC'), ('UserId', 'smriti_test#gmail.com')]))]))]))])
PASSED
If you are stuck with pytest not behaving as you want, you should take a step back and make sure
your yaml_laoder() function does what you expect:
import sys
from pathlib import Path
from ruamel.yaml import YAML
yaml_str = """\
TestConfig:
hostname: 10.2.4.6
Organisation:
Employee:
Name: Smriti
Skilss: Python
OrganizationName: ABC
UserId: smriti_test#gmail.com
"""
Path('test.yaml').write_text(yaml_str) # write out the file so that it is fresh every time
class R: pass
r = R()
r.param = "XXXXXX"
def yaml_loader(request):
yaml = YAML()
file_path = 'test.yaml'
with open(file_path) as fp:
data = yaml.load(fp)
test = data['TestConfig']
x = request.param
print(x)
with open(file_path, "w") as file:
yaml.dump(data, file)
print(data)
yaml_loader(r)
print('\n######### YAML #########\n')
print(Path('test.yaml').read_text())
which gives:
XXXXXX
ordereddict([('TestConfig', ordereddict([('hostname', '10.2.4.6'), ('Organisation', ordereddict([('Employee', ordereddict([('Name', 'Smriti'), ('Skilss', 'Python'), ('OrganizationName', 'ABC'), ('UserId', 'smriti_test#gmail.com')]))]))]))])
######### YAML #########
TestConfig:
hostname: 10.2.4.6
Organisation:
Employee:
Name: Smriti
Skilss: Python
OrganizationName: ABC
UserId: smriti_test#gmail.com
As you can clearly sea from the YAML content, it never gets updated with XXXXXX. This is because you don't assign to data
before writing out the test.yaml file.
Fix that first and then inject the code into your test.

Run Scala application on different process

Hi I want to create a program that starts another application on a new process:
object A{
def main(args: Array[String]) {
Process(????).run
println("new process has been created")
}
}
the application that should run on the new process:
object B{
def main(args: Array[String]) {
print("Hello world")
}
}
I know I can run a script using Process(script_string_to_run), but I don't know how to make it run another application..
Run Scala program from another Scala program
Scala Program
B.scala
object B {
def main(args: Array[String]): Unit = println("hello world")
}
Now execute the above program like this from another Scala program.
scala> import sys.process._
import sys.process._
scala> "scala B.scala" !!
warning: there was one feature warning; re-run with -feature for details
res1: String =
"hello world
"
Note that the file name of the file is same as the object name containing main method. This way scala would recognise the main class/object and execute the main method of the program. If the name of the file is not the name of the object containing the main method then It would not know what to execute.
! gives the exit status of the program after execution whereas !! gives the output of the program.
scala> import sys.process._
import sys.process._
scala> val status = "scala B.scala" !
warning: there was one feature warning; re-run with -feature for details
hello world
status: Int = 0
scala> val output = "scala B.scala" !!
warning: there was one feature warning; re-run with -feature for details
output: String =
"hello world
Scala Script
Test.sh
#!/usr/bin/env scala
object B{
def main(args: Array[String]) {
print("Hello world")
}
}
B.main(Array[String]())
Now Just run the B program using
"./Test.sh" !!
Command Line Activity
➜ cd demo
➜ demo ./Test.sh
zsh: permission denied: ./Test.sh
➜ demo chmod +rwx Test.sh
➜ demo ./Test.sh
Hello world%
➜ demo ./Test.sh
Hello world%
➜ demo scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions for evaluation. Or try :help.
scala> import sys.process._
import sys.process._
scala> "./Test.sh" !!
warning: there was one feature warning; re-run with -feature for details
res0: String =
"Hello world
"
scala> :q