What is wrong with this simple `unittest.mock` use case? - python-3.4

Edit: This may be the same issue as described in this Python bug: https://bugs.python.org/issue26752. But that bug has been sitting for a year, so I'm still interested in people's opinions here.
I'm not sure if this is a bug in unittest.mock or I just misunderstand something.
Here's the code - you can save it as test.py
from unittest.mock import patch, call
class Foo:
def __init__(self):
pass
def my_method(self, value):
pass
def test_foo():
with patch('test.Foo', autospec=True) as MockFoo:
m = Foo()
m.my_method(123)
MockFoo.assert_has_calls([call(), call().my_method(123)])
I run this test like so:
$ py.test test.py
And I get this failure:
...
E AssertionError: Calls not found.
E Expected: [call(), call().my_method(123)]
E Actual: [call(), call().my_method(123)]
The Question: Is this correct behavior? It seems buggy to me.
The list of calls matches up exactly, so what gives?
Interestingly, if I remove the value parameter of my_method and also the 123 inputs in the test, then everything passes!
What am I missing, here?
Version info:
$ py.test --version
This is pytest version 3.0.6, imported from /usr/local/lib/python3.4/site-packages/pytest.py
$python3.4 --version
Python 3.4.5
Also tried this on 3.5 in a virtualenv:
$ py.test --version
This is pytest version 3.0.6, imported from /usr/home/jwd/virtualenv/pytest-3.5/lib/python3.5/site-packages/pytest.py
$ python3.5 --version
Python 3.5.2

EDIT: deleted erroneous previous answer.
Please can you try:
expected_calls = [call(), call().my_method(123)]
assert MockFoo.mock_calls == expected_calls
This works for me on Python 3.5.2.
This is taken directly from the documentation: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_calls

Related

Mypy raises syntax error with pydrake stub

When I try to run mypy in my project that has PyDrake as a depencency I get: venv/lib/python3.9/site-packages/pydrake/common/eigen_geometry.pyi:30: error: invalid syntax
The line in questions is: def cast[AutoDiffXd](self, *args, **kwargs) -> Any: .... I'm assuming this has something to do with PyDrake's custom templating system. How can I make MyPy and PyDrake play nice?
Environment Info
OS: Ubuntu 20.04
Python version: 3.9.16
MyPy version: 0.991
Drake version: 1.11.0
As of the current version of Drake (v1.12.0), we unfortunately do not support Mypy. The purpose of the *.pyi files as of today is solely to enable VSCode suggestion auto-complete.
We didn't have a central issue tracking this, so I've filed a new one. Hopefully we can remove the syntax errors down the road.
The only work-around I know of for today is to delete the *.pyi files if you use Mypy.

Use Mypy with Ruamel.yaml

I am attempting to use MyPy with modules that use ruamel.yaml and Mypy cannot find ruamel.yaml even though Python has no problem finding it. I am puzzled because I can't find a module called YAML.py or class called YAML either, even though these statements work in Python:
from ruamel.yaml import YAML
yaml = YAML()
x = yaml.load()
What do I need to do to get MyPy to recognize ruamel.yaml?
A workaround is to run without the incremental logic of mypy:
python -m mypy --no-incremental myfile.py
Background
There is a known issue in mypy, see here.
In summary:
Something is not working with the incremental logic of mypy when it is encountering ruamel.
When you run it once, all goes ok. This is the command:
python -m mypy myfile.py
Then, when you run it again, you get an error:
error: Skipping analyzing 'ruamel': found module but no type hints or library stubs [import]
Then, when you run it again, it all goes ok
etc.
You should not be looking for a file YAML.py. The YAML in
yaml = YAML()
is a class that is defined in ruamel/yaml/main.py and that gets imported into ruamel/yaml/__init__.py (both under site-packages). That is why you do:
from ruamel.yaml import YAML
(the alternative would be that there is a file yaml.py under the directory ruamel, but the loader/dumper is a bit too much to put in one file).
What might work if the above knowledge doesn't help you resolve things, is explicitly set the global flag mypy_path or the environment variable MYPYPATH. This has to include the directory in which the directory ruamel is located.
( I could not find it mentioned in the documentation, but from the source ( mypy/build.py:mypy_path() ) you can see that this is supposed to be a string that gets split on os.pathsep (which is the colon (:) on my Linux based system))
I have the same issue.
Even after setting MYPYPATH=./.venv/lib/python3.7/site-packages
A temporary 'solution' is ignoring the missing import exception
mypy --ignore-missing-imports

pyinstaller ImportError: C extension: No module named np_datetime not built

I am running a virtual environment with Python 2.7 for my program.
There seems to be a problem after creating the executable file on windows.
I ran venv/Scripts/pyinstaller.exe -F main.py
everything seems fine. But when i click on the created executable main.exe.
There is an error.
Tried and tested
I have re-installed of pandas and pyinstaller
Implemented the hook-pandas.py to the hooks folder in the environment.
hook-pandas
Ensured the environment is activated.
Checked that the program is running fine before building executable.
Re-created the environment.
Yet after all that, I am prompted with this issue [see Importerror] when I run the executable file.
It is an extreme pain to debug this because the command prompt displaying the error will not pause but close almost immediately.
Similar issues
Looking for Suggestions
I am hoping for suggestions to troubleshoot Pyinstaller. Any resources to read up on would be nice.
Usually, I have no trouble with python as Pycharm has several handy debugging tools that will help me identify the problem
I ran into the same problem and found this thread, but I managed to solve it borrowing from the reference you posted (about pandas._libs.tslibs.timedeltas), so thank you for that!
In that article, the module that resulted in the ImportError was, in fact pandas._libs.tslibs.timedeltas, if you look at the poster's logs. But the error you and I ran into refers to np_datetime instead. So, from the traceback logs, I finally figured out that the code we have to write in hook-pandas.py should be the following:
hiddenimports = ['pandas._libs.tslibs.np_datetime']
Maybe that alone will solve your problem, HOWEVER, in my case, once I solved the np_datetime issue, other very similar ImportError problems arose (also related to hiddenimports regarding pandas), so, in case you run into the same issues, just define hiddenimports as follows:
hiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist']
TL;DR:
You can first try to write
hiddenimports = ['pandas._libs.tslibs.np_datetime']
into hook-pandas.py. However, if for some reason you run into the exact same issues I did afterwards, try
hiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist']
If you wish to dive deeper (or run into a different pandas ImportError than the ones I did), this is the code in pandas's __init__.py referenced in your traceback log (lines 23 to 35):
from pandas.compat.numpy import *
try:
from pandas._libs import (hashtable as _hashtable,
lib as _lib,
tslib as _tslib)
except ImportError as e: # pragma: no cover
# hack but overkill to use re
module = str(e).replace('cannot import name ', '')
raise ImportError("C extension: {0} not built. If you want to import "
"pandas from the source directory, you may need to run "
"'python setup.py build_ext --inplace --force' to build "
"the C extensions first.".format(module))
From that I went into the
C:\Python27\Lib\site-packages\pandas_libs
and
C:\Python27\Lib\site-packages\pandas_libs\tslibs
folders and found the exact names of the modules that resulted the errors.
I hope that solves your problem as it did mine.
Cheers!

Python/R ctypes library error: "OSError: lib/libRrefblas.so: undefined symbol: xerbla_"

Firstly, I'm a newbie R, AWS and python guy. So I'm trying to get a python script with embedded R code running in AWS Lambda using rpy2. I created a Lambda package on an EC2 instance following the instructions here (modified for using python 3.4). It seems that there is something funky happening with loading the R libs using ctypes, as per the following error received in the console:
OSError: lib/libRrefblas.so: undefined symbol: xerbla_
The test file (py_test.py) looks like this:
import os
import ctypes
for file in os.listdir('lib'):
if os.path.isfile(os.path.join('lib', file)):
ctypes.cdll.LoadLibrary(os.path.join('lib', file))
os.environ["R_HOME"] = os.getcwd()
os.environ["R_USER"] = os.path.join(os.getcwd(), 'rpy2')
os.environ["R_LIBS"] = os.path.join(os.getcwd(), 'library')
os.environ["LD_LIBRARY_PATH"] = os.path.join(os.getcwd(), 'lib')
import sys
sys.path.append(os.path.join(os.getcwd(),'rpy2'))
import rpy2
from rpy2 import robjects
def test_handler(event, context):
robjects.r('''
f <- function(r, verbose=FALSE) {
if (verbose) {
cat("I am calling f().\n")
}
2 * pi * r
}
print(f(3))
''')
test_handler(None,None)
I have lib/libRrefblas.so in my virtual environment. I have scoured google looking for answers but have come up empty. Any suggestions would be greatly appreciated!
If you can get the traceback, that could help, but I suspect the problem is that it's looking for xerbla_ in the wrong place. Is xerbla_ defined in the path to RLIBS? Maybe in libR.so?
Turns out the BLAS that ships with R is corrupt. Your best bet is to make sure that BLAS and Lapack are installed on the machine you are building R on and see if you can get it to build with those libraries instead.
So steps would be to uninstall R, then run
yum -y install lapack-devel.x86_64 lapack.x86_64
yum -y install blas -devel
yum -y install R.x86_64
Check to see if it has still installed with libRrefblas.so. If it has - try deleting that file and see if it will default to the system BLAS. If you get a error because it is still looking for libRrefblas.so
rm lib/libRrefblas.so
cp /usr/lib64/libblas.so.3 lib/
mv lib/libblas.so.3 lib/libRrefblas.so

"TypeError: expected bytes, str found" when calling .MidiIn() from rtmidi-python

I installed rtmidi_python for Python 3.4.2 from the .whl provided on http://www.lfd.uci.edu/~gohlke/pythonlibs/, and the import works fine, but as soon as I call "rtmidi_python.MidiIn()", I get a TypeError as follows:
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import rtmidi_python
>>> rtmidi_python.MidiIn()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
rtmidi_python.MidiIn()
File "rtmidi_python.pyx", line 72, in rtmidi_python.MidiIn.__cinit__ (rtmidi_python.cpp:1440)
TypeError: expected bytes, str found
As I understand, after some research, this means that the there's a mistake somewhere in the package itself or in the build of it, and there's nothing I can do about it, but I might be wrong. Can anyone confirm?
I use 3.4.2 because that is the version of Python used by the current version of Blender. I want to use rtmidi-python within the Blender Game Engine.
I am currently working on Windows 7 32 bit, and use .whls to install packages as I do not have the necessary C++ compiler for regular pip installs.
For comparison, I previously installed rtmidi-python for 3.5.1, also from the adequate .whl provided on the link above, and there the command worked perfectly fine.
Should any necessary information be missing, feel free to ask. Thanks ahead if the answer comes as a comment and I don't get to upvote it.
While not a perfect solution, this can be fixed in the manner described by sehqlr here...https://github.com/superquadratic/rtmidi-python/issues/17
...by calling MidiIn() like this:
>>> rtmidi_python.MidiIn(b'in')

Resources