_eq seems to be the equal to self.assertEqual()
But is there also a self.assertNotEqual() in nose?
Thanks
Nose doesn't have an equivalent to self.assertNotEqual(), but you can use all of the unittest.TestCase assert methods via nose.tools. They are renamed to all-lowercase and with underscores. For example:
>>> from nose.tools import assert_not_equal
>>> assert_not_equal(1, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 518, in assertNotEqual
raise self.failureException(msg)
AssertionError: 1 == 1
More info here.
Related
The package addict allows you to use dicts through attribute setting:
Example from the website:
from addict import Dict
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
Now when when I use for example a = body.B and I haven't included B yet it does not throw an error, but just returns nothing. How can I make it throw an error when the attribute was net yet set?
addict.Dict implements the __missing__ method to generate a value for any missing key(/attribute); the current implementation generates a new Dict instance. If you don't want this behaviour, you'll have to override it:
class MyDict(Dict):
def __missing__(self, name):
raise KeyError(name)
Note that this will throw a KeyError for attribute access, which may be confusing; you could also override __getattr__ if you want to throw an AttributeError instead. In use:
>>> body = MyDict()
>>> body.B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'B'
>>> body.B = "hello"
>>> body.B
'hello'
Note also that this will break the other examples you showed as well, as e.g. foo.bar.baz = qux calls __getattr__ on foo before calling __setattr__ on foo.bar (if successful):
>>> body.query.filtered.query.match.description = 'addictive'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'query'
I am using ParaView-5.4.1 under Ubuntu 16.04LTS.
I have an object r of class PVDReader (in pvpython, but this is likely irrelevant).
For the method TimestepValues of that class
>>> callable(r.TimestepValues)
True
>>> type(r.TimestepValues)
<class 'paraview.servermanager.VectorProperty'>
>>> r.TimestepValues
[0.0, 0.002]
>>> r.TimestepValues()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/site-packages/paraview/servermanager.py", line 681, in __call__
raise RuntimeError ("Cannot invoke this property")
RuntimeError: Cannot invoke this property
>>> import inspect
>>> inspect.getargspec(r.TimestepValues)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/santiago/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: [0.0, 0.002] is not a Python function
So, on one hand, it is callable.
On the other hand, it behaves as if it were not.
How can this be understood?
Is this a bug?
tl;dr PS: Other more generic methods behave similarly (but not the same). E.g., compare with __class__:
>>> callable(r.__class__)
True
>>> type(fluid_pr_reader.__class__)
<type 'type'> <-- Rather obvious, just for completitude of the comparison with above
>>> r.__class__
<class 'paraview.servermanager.PVDReader'>
>>> r.__class__()
<paraview.servermanager.PVDReader object at 0x7f57ed56fd10> <-- No error here
>>> inspect.getargspec(r.__class__)
Traceback (most recent call last): <-- Same error here
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <class 'paraview.servermanager.PVDReader'> is not a Python function
EDIT: The result is the same if I do not access it as a straight property prior to accessing it as a callable
>>> callable(r.TimestepValues)
True
>>> r.TimestepValues()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/site-packages/paraview/servermanager.py", line 681, in __call__
raise RuntimeError ("Cannot invoke this property")
RuntimeError: Cannot invoke this property
From time to time, I write a generic function in Python that gets called multiple times with different arguments. Usually, this is driven by a definition somewhere else.
For example:
def issue_sql_query(name, select_stmt):
...
QUERIES = [
"get_user_rows", "SELECT name, rowid FROM table WHERE type == 'USER';"
...
]
results = []
for name, select_stmt in QUERIES:
results.append((name, issue_sql_query(name, select_stmt)))
If there's an exception in the generic function (i.e., issue_sql_query or somewhere deeper), I have relatively little info in the traceback to identify which definition caused the error.
What I'd like to do is dynamically rename or augment the function name/stack frame so that tracebacks would include some identifying info.
What would be nice is something like this:
File "test.py", line 21, in <module>
results.append((name, issue_sql_query(select_stmt)))
File "test.py", line 11, in issue_sql_query(name="get_user_rows")
raise RuntimeError("Some error")
RuntimeError: Some error
I could, of course, stick exception handling at the generic points and rebuild the exception using traceback to have more context, which is pretty straightforward and likely the right choice. It gets a little tricky when you have multiple levels of generic functions, but that's certainly possible to handle.
Any other ideas on how to accomplish this? Did I miss some easy way to change the stack frame name?
Edit:
Adding an example traceback showing a relatively not useful traceback:
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "c:\tmp\report.py", line 767, in <module>
main()
File "c:\tmp\report.py", line 750, in main
charts.append(report.get_chart(title, definition))
File "c:\tmp\report.py", line 614, in get_chart
return self.get_bar_chart(title, definition)
File "c:\tmp\report.py", line 689, in get_bar_chart
definition, cursor, **kwargs))
File "c:\tmp\report.py", line 627, in create_key_table
for row in cursor.execute(full_select_stmt):
sqlite3.OperationalError: near "==": syntax error
You could create wrapper functions for each named query so that you can control the exception thrown:
>>> fns = {}
>>> def issue_sql_query(name, stmt):
... if name not in fns:
... def f(name, stmt):
... # run query here
... raise Exception(name)
...
... fns[name] = f
... return fns[name](name, stmt)
...
>>>
>>> issue_sql_query('b', 'SQL')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in issue_sql_query
File "<stdin>", line 5, in f
Exception: b
>>> issue_sql_query('a', 'SQL')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in issue_sql_query
File "<stdin>", line 5, in f
Exception: a
>>>
Why these below statements are giving error
>>> exec("x={}".format('b'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'b' is not defined
I need the result to be
x='b'
You should provide another pair of quotes
>>> exec("x={}".format("'b'"))
>>> x
'b'
Why?
When you write
exec("x={}".format('b'))
you are trying to write
x=b
obviously python doesn't know what b is unless you have defined it before.
Where as when you write
exec("x={}".format("'b'"))
It is same as
x='b'
If I want to see the str.replace() function: help(str.replace)
the result is:
Help on method_descriptor:
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
(END)
but how use help file.read or readlines?
for example, help(file.read) and help(read) are both errors:
>>> help(file)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(file.read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'read' is not defined
How can I use help see file functions?
The file type has been removed from Python 3. Look at the io module instead:
>>> import io
>>> help(io.TextIOBase.read)
Help on method_descriptor:
read(...)
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.