How to get Python `unittest` `assertRaises` methods to print `msg` parameter? - python-unittest

In the following, the test should fail and print the msg parameter. But it doesn't.
with self.assertRaises(ZeroDivisionError, msg="Unexpected denominator"):
1/1
This parameter (msg) works in every other assert* method. It seems highly unlikely that something so fundamental could be broken in unittest, so what's the deal?
Here's a complete program that demonstrates the problem:
#!/usr/bin/env python2
import unittest
class TestAssertRaisesMsgParam(unittest.TestCase):
def test_assert_raises_msg(self):
"""
Test unittest `assertRaises` msg param is printed
"""
with self.assertRaises(ZeroDivisionError, msg="Unexpected denominator"):
1/1
if __name__ == '__main__':
unittest.main()
Here's my interaction with it:
$ ls -l assertRaises.py
-rwxr-xr-x 1 tom users 440 Jun 10 14:04 assertRaises.py
$ python -m unittest assertRaises
F
======================================================================
FAIL: test_assert_raises_msg (assertRaises.TestAssertRaisesMsgParam)
----------------------------------------------------------------------
Traceback (most recent call last):
File "assertRaises.py", line 14, in test_assert_raises_msg
1/1
AssertionError: ZeroDivisionError not raised
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
And some system info:
$ /usr/bin/env python2
Python 2.7.13 (default, Mar 22 2017, 12:31:17) [GCC] on linux2
$ uname -a
Linux ... 4.4.62-18.6-default #1 SMP Fri Apr 21 16:14:48 UTC 2017 (84f9824) x86_64 x86_64 x86_64 GNU/Linux

Your code works on my box:
$ python -m unittest tester
F
======================================================================
FAIL: test_assert_raises_msg (test.TestAssertRaisesMsgParam)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\danth\src\test.py", line 12, in test_assert_raises_msg
1/1
AssertionError: ZeroDivisionError not raised : Unexpected denominator
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Make sure you run your test like this:
python -m unittest name_of_test_file

Related

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <builtin>, line 1:

I'm having trouble running jq from my linux host. I don't understand why.
$ uname -a
Linux localhost.localdomain 5.3.8-200.fc30.x86_64 #1 SMP Tue Oct 29 14:46:22 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
モ cat /etc/redhat-release
Fedora release 30 (Thirty)
$ echo $SHELL
/bin/bash
$ file $(which jq)
/usr/bin/jq: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=aca83aa7ecf04e5385c4cc94657cfc9ea1df86d3, stripped
$ jq --version
jq-1.6
$ echo '{}' | jq .
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <builtin>, line 1:
ELF
jq: 1 compile error
This happened to me when I tried to use a .jq file with CR/LF line endings on Linux. Changing it to LF fixed the problem.

How does zsh interpret non-absolute paths in shebangs? (WAS: Why does python3 -i permit non-absolute paths in shebang?)

I recently discovered the -i argument to Python, which drops into interactive mode after the script completes. Pretty neat!
$ cat test.py
#!python3 -i
x=5
print('The value of x is ' + str(x))
$ ./test.py
The value of x is 5
>>> print(str(x+1))
6
>>>
zsh: suspended ./test.py
However, when I tried to copy this script to a version that terminates on completion, it fails:
$ cat test1.py
#!python3
x=5
print('The value of x is ' + str(x))
$ ./test.py
/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python: can't open file '
x=5
print('The value of x is ' + str(x))
': [Errno 2] No such file or directory
From some further reading, I discovered that I had originally made a mistake, and #!/usr/bin/env python3 is the correct shebang.
However, I'm curious why a non-absolute path to python3 succeeds only when I give the -i flag. I guess this must be something to do with how zsh interprets non-absolute shebangs, but I don't know enough to know how to investigate that.
System setup: MacOS 10.12.6, iTerm2 3.1.6, zsh 5.2. which python3 gives /usr/local/bin/python3, and that directory is on $PATH.
Interestingly, I don't get the same behaviour on sh:
$ sh
sh-3.2$ cat test.py
#!python3
x=5
print('The value of x is ' + str(x))
sh-3.2$ ./test.py
sh: ./test.py: python3: bad interpreter: No such file or directory
I got some comments suggesting that this is something to do with CWD or permissions. python3 is not in my CWD, and both files have execute permission:
$ ls -al | grep 'py' | awk '{print $1, $10}'
-rw------- .python_history
-rwxr-xr-x test.py
-rwxr-xr-x test1.py
Your kernel will not execute the script unless the interpreter is
specified as an absolute path, or
specified as a path relative to the current working directory
Then if the kernel refuses to execute the script, your shell might take over and try to execute it anyway, interpreting the shebang line according to its own rules (like finding the executable in the $PATH for example).
zsh does attempt to do this. sh does not.
However the way zsh interprets the shebang (and probably subsequent lines) is really really strange. It looks like it always expects a single argument after the command name. See what it does:
$ cat test.py
#!python3 -b -i
x=5
print('The value of x is ' + str(x))
$ strace -f -e execve zsh
execve("/bin/zsh", ["zsh"], 0x7ffd35c9e198 /* 78 vars */) = 0
host% ./test.py
strace: Process 5510 attached
[pid 5510] execve("./test.py", ["./test.py"], 0x558ec6e46710 /* 79 vars */) = -1 ENOENT (No such file or directory)
[pid 5510] execve("/usr/bin/python3", ["python3", "-b -i", "./test.py"], 0x558ec6e46710 /* 79 vars */) = 0
[pid 5510] execve("/usr/lib/python-exec/python3.4/python3", ["/usr/lib/python-exec/python3.4/p"..., "-b -i", "./test.py"], 0x7fffd30eb208 /* 79 vars */) = 0
Unknown option: -
usage: /usr/lib/python-exec/python3.4/python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.
[pid 5510] +++ exited with 2 +++
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=5510, si_uid=1000, si_status=2, si_utime=0, si_stime=0} ---
host%
+++ exited with 2 +++
See how ["python3", "-b -i", "./test.py"] are passed as arguments. It seems highly counterintuitive to me to lump the two switches -b and -i together, but that's what zsh does. Python obviously doesn't understand this.
When there are no arguments, the exact behaviour depends on whether there is a space after the program name, but is strange in either case. Check it with strace yourself because you are not going to believe me.
It is my understanding that zsh handling of the shebang line is just buggy.

error: db type is dbm.gnu, but the module is not available in windows

I installed python3.6 in windows machine. And get below error while open my.db file.
my.db file created by my program in ubuntu16.04 in python3.6, using shelve module.
In [1]: import shelve
In [2]: db = shelve.open("etc/my.db")
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-2-b4828c8ee6e1> in <module>()
----> 1 db = shelve.open("etc/my.db")
c:\Python36\Lib\shelve.py in open(filename, flag, protocol, writeback)
241 """
242
--> 243 return DbfilenameShelf(filename, flag, protocol, writeback)
c:\Python36\Lib\shelve.py in __init__(self, filename, flag, protocol, writeback)
225 def __init__(self, filename, flag='c', protocol=None, writeback=False):
226 import dbm
--> 227 Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
228
229
c:\Python36\Lib\dbm\__init__.py in open(file, flag, mode)
89 elif result not in _modules:
90 raise error[0]("db type is {0}, but the module is not "
---> 91 "available".format(result))
92 else:
93 mod = _modules[result]
error: db type is dbm.gnu, but the module is not available
Please help, how can I install a missing module in windows.
As mentioned by #alexander-p , the problem might be the __pycache__ folders in your source code.
In my case was that I did replace a venv folder with a virtual environment by a new folder with the same name but a newer version of Python (~3.8~ → 3.9), and using at the same time PyCharm (that used the venv setup).
Deleting all the Python caches (and restarting PyCharm just in case) solved the problem.
You can do so with:
$ find . -name __pycache__ | xargs rm -Rv
If the venv folder is inside the same folder where your source code is placed, better to execute:
$ find . -name __pycache__ | grep -v venv | xargs rm -Rv
So the cache inside the venv/ folder is not deleted.

NetfilterQueue Implementation

I am trying to use NetfilterQueue for my project. As a beginning, I tried to run this code. You know the source.
from netfilterqueue import NetfilterQueue
def print_and_accept(pkt):
print pkt
pkt.accept()
nfqueue = NetfilterQueue()
nfqueue.bind(1, print_and_accept)
try:
nfqueue.run()
except KeyboardInterrupt:
print
I passed it the packets filtered by the following rule
sudo iptables -I INPUT -s iitp.ac.in -j NFQUEUE --queue-num 1
I got following error
Traceback (most recent call last):
File "pkt_desc_1.py", line 8, in <module>
if nfqueue.bind(0, print_and_accept) < 0:
File "netfilterqueue.pyx", line 144, in netfilterqueue.NetfilterQueue.bind (netfilterqueue.c:2665)
OSError: Failed to create queue 1.
Can anybody help ?
I am new to the topic. So, please don't mind.
identify process number (type)
ps aux | grep python
it will show processes in python
root 1633 0.0 0.4 16664 8680 pts/1 T 13:03 0:00 python netfilter.py
root 1687 0.0 0.0 6136 956 pts/0 S+ 13:12 0:00 grep python
use kill process (type)
kill -9 1633
hope this helps =D

Multiple cronjobs in a single crontab

How do I cd into a directory and run a script in the same crontab? Currently I'm trying to do something like 32 11 19 1 * cd /Users/myusername/Documents && simple.py but when this runs I receive the error:
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=myusername>
X-Cron-Env: <USER=myusername>
X-Cron-Env: <HOME=/Users/myusername>
Date: Mon, 19 Jan 2015 11:32:00 -0500 (EST)
/bin/sh: simple.py: command not found
How can I fix this?
You must precede with ./ when executing the script from the current working directory.
32 11 19 1 * cd /Users/myusername/Documents && ./simple.py
I guess you script is a python script. /bin/sh: seems weird. If your script is a python script then add following line #!/usr/bin/env python if it does not already contain it.

Resources