pytest -k <keyword> --co | grep "collected" | tail -1 | awk '{print $2}'
Category: Python
Count how many tests each module has via pytest
python -m pytest --co -q | grep "::" | awk -F'::' '{print $1}' | uniq -c
How to check the root cause of the difference between “pytest” and “python -m pytest”?
| Command | Uses which Python? | Risk |
|---|---|---|
pytest | Whatever executable is first in PATH | May run wrong environment |
python -m pytest | The Python you explicitly called | Much safer |
cat $(which pytest)
The shebang line can show which “python” that pytest uses.
python -c "import sys; print(sys.executable)"
or
which python
This shows the interpreter you’re explicitly invoking.
unittest setUp vs. pytest setup_class
unittest:
import unittest
class MyTest( unittest.TestCase ):
def setUp( self ):
self.variable = ...
pytest:
import pytest
class MyTest:
@classmethod
def setup_class( cls ):
cls.variable = ...
Install pytorch cpu only
pip install torch --index-url https://download.pytorch.org/whl/cpu
Check where python packages are installed in a docker
Usually here:
/usr/local/lib/<python version>/site-packages
Or
pip show request <package name>
Assert exception during python unit test
If using unittest:
import unittest
with self.assertRaises( Exception ) as error:
...
If using pytest:
import pytest
with pytest.raises( Exception ) as error:
...
Use ElementTree to add elements and sub-elements
import xml.etree.ElementTree as ET
root = ET.Element('Configuration')
student = ET.SubElement(root, 'student')
ET.SubElement(student, 'name').text = 'A'
ET.SubElement(student, 'years').text = '20'
# Test the result
import xml.dom.minidom
dom = xml.dom.minidom.parseString(ET.tostring(root))
print(dom.toprettyxml())
The result is below.
<?xml version="1.0" ?>
<Configuration>
<student>
<name>A</name>
<years>20</years>
</student>
</Configuration>
Pretty printing XML in Python
import xml.dom.minidom
dom = xml.dom.minidom.parse(xml_fname)
# or
# dom = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = dom.toprettyxml()
Python unit test and nose test
| unittest | nosetests |
| python -m unittest tests/test_something.py -v | nosetests tests/test_something.py -v |
| python setup.py test | python setup.py nosetests |