Re: Mock object but also assert method calls?

2015-08-15 Thread Thomas Lehmann via Python-list
Am Freitag, 14. August 2015 04:53:56 UTC+2 schrieb Steven D'Aprano:
 On Fri, 14 Aug 2015 07:21 am, Ben Finney wrote:
 
  If find following totally different to the normal API which
  is provided by the mock library:
 
  assert call().test2(hello) in mocked_objects.mock_calls
  
  The 'assert' statement is a crude tool, which knows little about the
  intent of your assertion.
 
 I agree with Ben here. Despite the popularity of nose (I think it is
 nose?) which uses `assert` for testing, I think that is a gross misuse of
 the statement. It is okay to use assertions this way for quick and dirty ad
 hoc testing, say at the command line, but IMO totally inappropriate for
 anything more formal, like unit testing.
 
 If for no other reason than the use of `assert` for testing makes it
 impossible to test your code when running with the Python -O (optimize)
 switch.
 
 For more detail on the uses, and abuses, of `assert` see this:
 
Of course you do NOT use assert in unit tests but I provided
just test code to show my problem. Of course I take nose and
hamcrest and code coverage ...

Here a complete example of my problem (with comments):


from mock import MagicMock, call, patch

class Bla:
def test1(self, value):
pass

mocked_object = MagicMock(Bla)
bla = Bla()
bla.test1(hello)
# empty, why?
print(mocked_object.mock_calls)
# does not work: mocked_object.test1.assert_called_with(hello)

with patch(__main__.Bla) as mocked_object:
bla = Bla()
bla.test1(hello)
# not empty!
print(mocked_object.mock_calls)
# does also not work: mocked_object.test1.assert_called_with(hello)
# but this does work:
assert call().test1(hello) in mocked_object.mock_calls


I don't wanna patch each individual method. Is there no other way?
-- 
https://mail.python.org/mailman/listinfo/python-list


Mock object but also assert method calls?

2015-08-13 Thread Thomas Lehmann via Python-list
Hi,

How about asserting that test2 of class Bar is called?
Of course I can do a patch for a concrete method but
I was looking for something like:

mocked_object.assert_method_called_with(name=test2, hello)

If find following totally different to the normal API which
is provided by the mock library:

assert call().test2(hello) in mocked_objects.mock_calls

Is there a better way?

APPENDIX:
Foo delegates calls to Bar.

[code]
from mock import patch
with patch(__main__.Bar) as mocked_object:
foo = Foo()
foo.test1()
foo.test2(hello)
print(mocked_object.mock_calls)
# print all calls (c'tor as well as normal methods)
for name, args, kwargs in mocked_object.mock_calls:
print(name, args, kwargs)
[/code]

Generates:

class '__main__.Bar'
test1: Foo has been called
test2: Foo has been called with value hello
[call(), call().test1(), call().test2('hello')]
('', (), {})
('().test1', (), {})
('().test2', ('hello',), {})
-- 
https://mail.python.org/mailman/listinfo/python-list


bdist_rpm with --requires and version

2014-11-07 Thread thomas . lehmann
Hi,

using the RPM build I wonder how I can require a certain version
of another RPM like:

Working:
  python setup.py bdist_rpm --requires=another-package

But how to? ...
  python setup.py bdist_rpm --requires=another-package=2.1

Of course this will generate a =2.1 file which is
of course not wanted.

How to do it right?
-- 
https://mail.python.org/mailman/listinfo/python-list


xmlrpc: problems with socket handling, close, shutdown of server, TIME_WAIT, ...

2014-05-06 Thread thomas . lehmann . private
Hi,

taking the xml-rpc derived from standard example is working - basically - but 
with following scenario I do not understand the problem. Maybe you can help:

 - one Unittest that does create the xmlrpc server in a thread
   in setUp and shutdown of it in tearDown.
   The xml-rcp server does store/load a value for a key.
   (It's for testing/learning purpose)

Problem(s):

 - If I run the test method twice (copy and paste and rename)
   then I get a error: [Errno 98] Address already in use
   (I assumend the tearDown would have closed all sockets)

 - Because of this I removed that second method and so it's fine
   but checking with netstat -n | grep port I see as many
   sockets in TIME_WAIT as I did xml-rpc calls. Also that python
   test is not running anymore it take some time until those
   entries vanish from the netstat list.

Question(s):

I assumed that calling the shutdown of the server (in tearDown)
does close all sockets. The SimpleXMLRPCServer is derived from
SocketServer.TCPServer and those one is derived from BaseServer.
Those has the shutdown which is documented to stop the serve_forever loop.
Is this correct or do I have to shutdown in another way?

At client side I'm using the ServerProxy. It does obviously not
have a close. From code it looks like that I could do something
like proxy(close)() but that looks somehow wired?
Can I close a proxy?, should I?, ... what is the way?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why Python 3?

2014-05-06 Thread Thomas Lehmann
Hi,

I can't give you the advise for a concrete version anyway there are lot of 
arguments given by the other posters. BUT there is a way how you can circumvent 
the problem to some extend:

Are you intending to use Jenkins? I don't want to convince you here why to use 
Jenkins but maybe I don't need to and THEN you just install the ShiningPanda 
plugin and each time your project is build automatically because of a change 
all tests are running across multiple Python versions. This way you won't have 
too many problems to switch to another newer Python version. Keep the build 
green.


 
 What is the general feel of /this/ community? I'm about to start a
 
 large scale Python project. Should it be done in 2 or 3? What are the
 
 benefits, aside from the 'it's the future' argument?
-- 
https://mail.python.org/mailman/listinfo/python-list


Pylint across Python versions

2014-02-10 Thread thomas . lehmann
Hi,

somebody who can tell me about pylint experiences across
different Python version.

Example:
I'm using a construct like this:

if sys.version.startswith(3.):
unicode = str

The reason is that Python 3 does not have this
function anymore but pylint yells for Python  3
about redefinition also it does not happen.

How to get forward with this?

Regards,
Thomas
-- 
https://mail.python.org/mailman/listinfo/python-list


Python RPM distribution with altinstall on Centos 5

2013-11-19 Thread thomas . lehmann
Hi all,

I missed to find a Python 2.7.6 Centos 5 distribution.
Here's what I planned to do:

 - building from source on Centos 5 in a chroot (is working fine)
 - using sudo make altinstall (is working fine)

But ...

 - I want to build this via Jenkins (we have this kind of chroot
   build's still in place)
 - how to create a RPM for this concrete Centos 5 - Python version
   with the altinstall feature? (!! we require this !!)

Maybe you also have another idea on how to solve this 

Kind Regards,
Thomas
-- 
https://mail.python.org/mailman/listinfo/python-list


Decode II (more complex)

2010-06-21 Thread Thomas Lehmann
Hi all,

I have written a small python xmlrpc server which checks logfiles of a
build
sending notifications to the responsible teams. On a machine I'm
forced to
a problem with one logfile with special characters inside generated by
a
gnu compiler.

Using cheetah for generating the HTML mail I get a:
('ascii' codec can't decode byte 0xe2 in position 25868: ordinal not
in range(128))

I have found characters like this:
 error: expected type-specifier before â8098Assocâ8099
 (copy and paste of a linux console)

I have tried different mechanism but very probably I do not understand
how the decode/encode functionality is working. Can somebody help me
to get out of that problem?

Thanks in advance
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deduping

2010-06-21 Thread Thomas Lehmann
 universe={}
 for line in outf:
     if line.split(',')[1].strip() in universe.keys():
         a=1
     else:
         if line.split(',')[1].strip() in done_.keys():
             a=1
         else:
             universe[line.split(',')[1].strip()]=0


I can not say too much because I don't see what is processed
but what I can say is: line.split(',')[1].strip() might be
called three times so I would do it once only. And I would write
it like this:

for line in outf:
key = line.split(',')[1].strip()
if not (key in universe.keys()):
if not (key in done_.keys()):
universe[key] = 0

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decode II (more complex)

2010-06-21 Thread Thomas Lehmann
 Your email(s) get send as 7 bit (ASCII). Email them as utf-8 and I guess
 your problem is solved.

 How do you email the notifications?


 I was copying partly the logic from http://code.activestate.com/recipes/473810
 Changing to buffer.decode(utf-8, 'replace') where I'm reading the
file and
 changing the html template at top to utf-8 leads to following output:

 File /srv/buildManager/BuildManagerMail.py, line 27, in sendMail
msgText = MIMEText(htmlMessage, 'html')
  File /usr/lib64/python2.6/email/mime/text.py, line 30, in __init__
self.set_payload(_text, _charset)
  File /usr/lib64/python2.6/email/message.py, line 224, in
set_payload
self.set_charset(charset)
  File /usr/lib64/python2.6/email/message.py, line 264, in
set_charset
cte(self)
  File /usr/lib64/python2.6/email/encoders.py, line 73, in
encode_7or8bit
orig.encode('ascii')
AttributeError: 'DynamicallyCompiledCheetahTemplate' object has no
attribute 'encode'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advanced Dictionary

2010-06-16 Thread Thomas Lehmann

 class AutoValueDict(dict):
     def __makeitem__(self, key):
         return self.setdefault(key, {})

     def __getitem__(self, key):
         return self.get(key, self.__makeitem__(key))

 I would like to have a dictionary which ensures dictionaries as values
 except when I'm assigning another:

 dict[abc][xyz][123][456] = 123

 How can I do this without many if and else?


Oh no... of course like this:
return self.setdefault(key, AutoValueDict())

-- 
http://mail.python.org/mailman/listinfo/python-list


Advanced Dictionary

2010-06-16 Thread Thomas Lehmann
Hi,

I have seen a recipe which allows auto creation of missing values for
dictionaries.
However this recipe is not working for all.

class AutoValueDict(dict):
def __makeitem__(self, key):
return self.setdefault(key, {})

def __getitem__(self, key):
return self.get(key, self.__makeitem__(key))

I would like to have a dictionary which ensures dictionaries as values
except when I'm assigning another:

dict[abc][xyz][123][456] = 123

How can I do this without many if and else?

best regards
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Thomas Lehmann
Hi,

I'm wondering about the behavior. Running this example - it looks like
- that each rpc call is triggered in a visible interval (about one
second).

What's wrong?

Thomas

APPENDIX:

code
import threading
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

class MyServer(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
self.server = SimpleXMLRPCServer((host, port))
self.server.register_function(self.is_even, is_even)
self.server.register_function(self.stop, stop_server)

def run(self):
print(server: waiting for requests...)
self.server.serve_forever()
print(server: is down.)

def stop(self):
print(server: shutdown requested...)
self.stoptimer = threading.Timer(1, self.server.shutdown)
self.stoptimer.start()
return done.

def is_even(self, n):
print(server: check %d to be even % (n))
return n%2 == 0


# server as thread
server = MyServer(localhost, 1234)
server.start()

# client code
serverProxy = xmlrpc.client.ServerProxy(http://localhost:1234;)
for n in range(1,2+1):
print(%d is %s % (n, [odd, even][serverProxy.is_even(n)]))
serverProxy.stop_server()
/code
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Thomas Lehmann
 What's wrong?


Obviously there's a problem with localhost. When using the IP of my
machine everything is working fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with an huge dictionary

2010-05-20 Thread Thomas Lehmann

 The question is:
 Is there a limit on the number of entries a dictionary can have i
 jython?

 I wrote a little app where my data is stored in a huge dictionary
 (11746 entries) generated with a python script.
 When I try to import the dictionary, jython complains with the
 following message:


1) You did not say what you have saved (content of your dictionary).
2) You did not say how you have saved.

From the callstack - also I have never used jython - it looks like
that
there is a try to create a class. It looks like - I may be wrong -
that
you have saved user objects in your dictionary - have you?

If so you might fail on loading those objects - especially when your
program
does not have the code for it.

More details are required...
-- 
http://mail.python.org/mailman/listinfo/python-list


No module named server

2010-05-07 Thread Thomas Lehmann
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
(Intel)] on win32

Script:
from http.server import HTTPServer, CGIHTTPRequestHandler

Result:
Traceback (most recent call last):
  File http.py, line 1, in module
from http.server import HTTPServer, CGIHTTPRequestHandler
  File F:\Checkouts\projects\python\http.py, line 1, in module
from http.server import HTTPServer, CGIHTTPRequestHandler
ImportError: No module named server
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No module named server

2010-05-07 Thread Thomas Lehmann
 Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit

Also after installing Python 3.1.2 the problem is still there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No module named server

2010-05-07 Thread Thomas Lehmann
On 7 Mai, 10:02, Thomas Lehmann t.lehm...@rtsgroup.net wrote:
  Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit

 Also after installing Python 3.1.2 the problem is still there.

I know the problem.

Reading a book about a simple cgi web server the descriptions says
to use httpd.py as name for the file and I forgot the 'd'.

This leads to the wrong behaviour.
-- 
http://mail.python.org/mailman/listinfo/python-list


SAX: Short tag's ...

2009-10-05 Thread Thomas Lehmann
Hi!

Is there a way to recognize short tags in a XML?
I'm implementing a SAX handler...

Problem: storing the XML code I would need this information
in the startElement ...

How can I handle this?

element id=abc /
element id=xyz any text/element
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weak reference to bound method

2009-10-02 Thread Thomas Lehmann
 I am trying to use a weak reference to a bound method:

 class MyClass(object):
 def myfunc(self):
 pass

 o = MyClass()
 print o.myfunc
bound method MyClass.myfunc of __main__.MyClass object at 0xc675d0

 import weakref
 r = weakref.ref(o.myfunc)
 print r()
None

 This is what I do not understand. The object o is still alive, and
 therefore the bound method o.myfunc shall exists.

 Why does the weak reference claim that it is removed? And how can I hold
 the reference to the method until the object is removed?


k = o.myfunc
r = weakref.ref(k)
print r()
  weakref at 00B80750; to 'method' at 00B59918 (myfunc)

Don't ask me why! I have just been interested for what you are
trying...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter - Text - bullets

2009-09-21 Thread Thomas Lehmann
 This is probably why you had all these alignment problems. But it's
 weird, because the script I posted is copied and pasted from a really
 script that I've run, and which doesn't cause any error. What is the
 version of tcl/tk used by your Tkinter module? And what is your Python
 version?

Using python 2.5 (with Tcl/Tk 8.4):

Traceback (most recent call last):
  File Text1.py, line 10, in module
txt.tag_configure('bulleted_list', font=('Times', 18),
lmargin1='10m', lmargin2='15m', tabs=['15m'])
  File E:\Python25\lib\lib-tk\Tkinter.py, line 3066, in
tag_configure
return self._configure(('tag', 'configure', tagName), cnf, kw)
  File E:\Python25\lib\lib-tk\Tkinter.py, line 1188, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: bad screen distance ['15m']
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter - Text - bullets

2009-09-18 Thread Thomas Lehmann
My intention is to write a small custom widget displaying text where
the text can have a simple wiki syntax. The main interest is to
support heading, bold, italic, underline, itemization and enumeration.

How can I implement itemization using the Tkinter.Text widget?
(bullets)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zipped and pickle

2009-09-17 Thread Thomas Lehmann
 Briefly:

 s = cPickle.dumps(obj)
 z = zipfile.Zipfile(filename.zip,w,zipfile.ZIP_DEFLATED)
 z.writestr(arcname.pkl,s)

Thank you very much. I have not been aware that pickle can also do the
job without a file!
Here's the complete scenario for writing and reading the data...

APPENDIX:

import pickle
import zipfile

def test1():
print(test1...)

# create data
data = {}
data[first name ] = Thomas
data[second name] = Lehmann
data[hobbies] = [programming python]
print (data)

# pickle data
pickleString = pickle.dumps(data)
# save string to zip under a name
file = zipfile.ZipFile(ZippedPickle.zip, w,
zipfile.ZIP_DEFLATED)
file.writestr(some data, pickleString)
file.close()

def test2():
print(test2...)
file = zipfile.ZipFile(ZippedPickle.zip, r,
zipfile.ZIP_DEFLATED)
# reading zipped string store under a name
pickleString = file.read(some data)
# unpickle string to original data
data = pickle.loads(pickleString)
print (data)
file.close()

if __name__ == __main__:
test1()
test2()
-- 
http://mail.python.org/mailman/listinfo/python-list


Zipped and pickle

2009-09-16 Thread Thomas Lehmann
How do I implement best to use pickle that way that the file is zipped?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Re: How to improve this code?

2009-09-16 Thread Thomas Lehmann
 otherwise. Given this, I'm just trying to write a method
 are_elements_present(aList) whose job is to return True if and only if
 all elements in aList are present in page's HTML. So here is how


missingItems = [str(ele) for ele in eleLocators if not
selenium.is_element_present(ele)]
if len(missingItems)  0:
   print missing items: %s % (missingItems)


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter only: table widget with canvas...

2009-07-11 Thread Thomas Lehmann

 There's a working app at http://cl1p.net/tkinter_table_headers/

 -John

Thank you for this example. However, one issue to that...
When resizing the window (vertical) then the header moves away
from the table. How can I avoid this with the grid? With pack
I now this...
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter only: table widget with canvas...

2009-07-10 Thread Thomas Lehmann
My intention is to keep dependencies low that means using python and
tkinter
as base package is quite easy because it's available on nearly every
system.

There is good documentation on Tkinter but going into the depth I'm
missing
many details. As an example...

Using the Tkinter.Canvas class I should be able to create a nice
table.
The missing informations are:

a) Assume I would have some different widgets to add per row. How
do I get the maximum row height?

b) Assume something like a label in one column. The length of all
texts
in a column will differ. How do I choose the maxium column width?

c) Placing headers in a canvas does not look like a good idea because
I don't want to scroll the headers. Am I right?
c.1) How do I place a none scrollable header in a canvas?  or
c.2) How do I place all headers outside the canvas correctly above
the relating column?

best regards
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Fast Dictionary Access

2009-06-27 Thread Thomas Lehmann
Hi!

In C++, programming STL you will use the insert method which always
provides a position and a flag which indicates whether the position
results from a new insertion or an exisiting element. Idea is to have
one search only.

code
if  data.has_key(key):
   value = data[key]
/code

But this does mean (does it?) that the dictionary is searched two
times! If so, can somebody show me how to do this in one step?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginning with Python; the right choice?

2009-06-27 Thread Thomas Lehmann
 read and have started to go through them.  I was wondering, as someone
 with virtually no programming experience (I am a photographer by
 trade), is Python the right language for me to try and learn?

Well, I'm a 100% C++ programmer but I like programming python for
prototyping and tools.

The answer on your question depends on your requirements. Some are
saying
that using Java and Swing are the best way to write applications.
But nothing is for free except the most languages you can download and
install. When you have no idea about software development you should
have a look there first. Do you want some little scripting only to get
some jobs easier done - well - you're right to use python.

However - you should be aware of: When you have learned python a while
and
when you will be forced to programm C++, Java or C# you have to start
again!
Check your requirements...


-- 
http://mail.python.org/mailman/listinfo/python-list