I have a problem writing self-testable modules using doctest when these
modules have internationaliz ed strings using gettext _('...').
- The main module of an application (say app.py) calls gettext.install ()
to install the special _ function inside Python builtin. Other modules,
taken from a general purpose collection of Python modules, also support
internationalis ation and doctest testing.
For example:
utstring.py would contain some code like this:
def onOffStr(isOn) :
"""Return the "ON" string for True, "OFF" for False.
**Example** onOffStr(True)
u'ON' onOffStr(False)
u'OFF'
"""
if isOn:
return _(u"ON") # notice the underscore
else:
return _(u"OFF")
The utstring module does not call any of the gettext calls, because some
other module does it when the application runs. So the doctest fails:
*************** *************** *************** *************** *****
Failure in example: onOffStr(True)
from line #4 of utstring.onOffS tr
Exception raised:
Traceback (most recent call last):
File "C:\Python23\Li b\doctest.py", line 442, in _run_examples_i nner
compileflags, 1) in globs
File "<string>", line 1, in ?
File "C:\dev\python\ utstring.py", line 513, in onOffStr
return _(u"ON")
TypeError: 'tuple' object is not callable
*************** *************** *************** *************** *****
I tried to define a _() function when testing with the code below but
the doctest still fails. The following code is at the end of my
utstring.py module
def _test():
"""_test() perform docstring test"""
import doctest, utstring
return doctest.testmod (utstring)
if __name__ == "__main__":
def _(aString):
# dummy _() attempting to get doctest to pass.
return aString
_test()
----------
Does anyone know why the doctest still fails when I define the dummy _()
function?
Thanks in advance.
Pierre 14 2671
Pierre> I tried to define a _() function when testing with the code
Pierre> below but the doctest still fails. The following code is at the
Pierre> end of my utstring.py module
...
I suspect it's because your dummy _ is not in builtins. Why not just call
gettext.install () where you are currently defining _?
Skip
Skip Montanaro wrote: Pierre> I tried to define a _() function when testing with the code Pierre> below but the doctest still fails. The following code is at the Pierre> end of my utstring.py module ...
I suspect it's because your dummy _ is not in builtins. Why not just call gettext.install () where you are currently defining _?
Skip, this looks like the way to go.
I was trying to avoid it because the translation files for these library
modules are constructed at the application level somewhere else. But I
was also considering creating a translation library for these module, so
I guess that is one more incentive to do so...
Thanks
Pierre I suspect it's because your dummy _ is not in builtins. Why not just call gettext.install () where you are currently defining _?
Pierre> Skip, this looks like the way to go.
Pierre> I was trying to avoid it because the translation files for these
Pierre> library modules are constructed at the application level
Pierre> somewhere else. But I was also considering creating a
Pierre> translation library for these module, so I guess that is one
Pierre> more incentive to do so...
If you really want a dummy _() you can also stuff your version into
builtins: import __builtin__ def foo(s): return s
... __builtin__._ = foo _
<function foo at 0x1d6670> _("hi")
'hi'
Skip
Skip Montanaro wrote: If you really want a dummy _() you can also stuff your version into builtins:
>>> import __builtin__ >>> def foo(s): return s ... >>> __builtin__._ = foo >>> _ <function foo at 0x1d6670> >>> _("hi") 'hi'
I tried that, but it only works for the first call...
[Shell buffer started: python.exe]
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright" , "credits" or "license" for more information. import __builtin__ def foo(s): return s
.... __builtin__._ = foo _
<function foo at 0x008F98B0> _
<function foo at 0x008F98B0> _('hi')
'hi' _
'hi' _('Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
Pierre
Pierre Rouleau wrote: Skip Montanaro wrote:
If you really want a dummy _() you can also stuff your version into builtins:
>>> import __builtin__ >>> def foo(s): return s ... >>> __builtin__._ = foo >>> _ <function foo at 0x1d6670> >>> _("hi") 'hi'
I tried that, but it only works for the first call...
Setting __builtin__._ to the result of the last calculation is a side effect
of sys.displayhook . Therefore you need to change that too:
Python 2.3.3 (#1, Jan 3 2004, 13:57:08)
[GCC 3.2] on linux2
Type "help", "copyright" , "credits" or "license" for more information. import sys def mydisplayhook(a ):
.... if a is not None: sys.stdout.writ e("%r\n" % a)
.... def foo(s): return s
.... sys.displayhook = mydisplayhook import __builtin__ __builtin__._ = foo _("hi")
'hi' _("hello")
'hello'
Peter
Pierre Rouleau wrote: Skip Montanaro wrote:
Pierre> I tried to define a _() function when testing with the code Pierre> below but the doctest still fails. The following code is at the Pierre> end of my utstring.py module ...
I suspect it's because your dummy _ is not in builtins. Why not just call gettext.install () where you are currently defining _?
Skip, this looks like the way to go.
I was trying to avoid it because the translation files for these library modules are constructed at the application level somewhere else. But I was also considering creating a translation library for these module, so I guess that is one more incentive to do so...
I implemented the dictionary and use it in the code just fine, but the
doctest still fails :(
My teststr.py module is:
#--[---------------------------------------------------------------
if __name__ == "__main__":
# install gettext for testing this module because of the string
translation
# performed in the code.
import gettext
gettext.install ('impathpl', './locale', unicode=False)
presLan_en = gettext.transla tion('impathpl' , "./locale",
languages=['en'])
presLan_en.inst all()
def onOffStr(isOn) :
"""Return the "ON" string for True, "OFF" for False.
**Example** onOffStr(True)
'ON' onOffStr(False)
'OFF'
"""
if isOn:
return _("ON")
else:
return _("OFF")
def _test():
"""_test() perform docstring test"""
import doctest, teststr
return doctest.testmod (teststr)
if __name__ == "__main__":
_test()
#--]-------------------------------------------------
Running the following script shows that the module runs OK:
[Shell buffer started: python.exe]
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright" , "credits" or "license" for more information. import teststr import gettext gettext.install ('impathpl', './locale', unicode=False) presLan_en = gettext.transla tion('impathpl' , "./locale",
languages=['en']) presLan_en.inst all() teststr.onOffSt r(True)
'ON'
BUT, the doctest fails:
D:\dev\python>t eststr
*************** *************** *************** *************** *****
Failure in example: onOffStr(False)
from line #6 of teststr.onOffSt r
Exception raised:
Traceback (most recent call last):
File "c:\Python23\li b\doctest.py", line 442, in _run_examples_i nner
compileflags, 1) in globs
File "<string>", line 1, in ?
File "teststr.py ", line 23, in onOffStr
return _("OFF")
TypeError: 'str' object is not callable
*************** *************** *************** *************** *****
1 items had failures:
1 of 2 in teststr.onOffSt r
***Test Failed*** 1 failures.
I'm still puzzled...
Pierre
Peter Otten wrote: Pierre Rouleau wrote:
Skip Montanaro wrote:
If you really want a dummy _() you can also stuff your version into builtins:
>>> import __builtin__ >>> def foo(s): return s ... >>> __builtin__._ = foo >>> _ <function foo at 0x1d6670> >>> _("hi") 'hi'
I tried that, but it only works for the first call...
Setting __builtin__._ to the result of the last calculation is a side effect of sys.displayhook . Therefore you need to change that too:
Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright" , "credits" or "license" for more information.
import sys def mydisplayhook(a ): ... if a is not None: sys.stdout.writ e("%r\n" % a) ... def foo(s): return s ... sys.display hook = mydisplayhook import __builtin__ __builtin__ ._ = foo _("hi") 'hi' _("hello" )
'hello'
Thanks Peter, it does work!
Pierre> BUT, the doctest fails:
...
Looks like Peter Otten's sys.displayhook hack is required for doctest.
Skip
Pierre> I tried that, but it only works for the first call...
:-)
Pierre> [Shell buffer started: python.exe]
Pierre> Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
Pierre> win32
Pierre> Type "help", "copyright" , "credits" or "license" for more information. import __builtin__ def foo(s): return s
Pierre> ... __builtin__._ = foo _
Pierre> <function foo at 0x008F98B0> _
Pierre> <function foo at 0x008F98B0> _('hi')
Pierre> 'hi' _
Pierre> 'hi' _('Hello')
Pierre> Traceback (most recent call last):
Pierre> File "<stdin>", line 1, in ?
Pierre> TypeError: 'str' object is not callable
That's true. In interactive mode _ is assigned the value of the last
expression evaluated. Try it from a script.
Skip This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics | |
by: Alan G Isaac |
last post by:
> python doctest.py -v
Running doctest.__doc__
Trying: .remove(42)
Expecting:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list
ok
Trying: x = 12
Expecting: nothing
|
by: Michele Simionato |
last post by:
I am getting a strange error with this script:
$ cat doctest-threads.py
"""
>>> import time, threading
>>> def example():
.... thread.out =
.... while thread.running:
.... time.sleep(.01)
.... thread.out.append(".")
|
by: Runsun Pan |
last post by:
I intend to use the doctect heavily. For this I am thinking of
coding a class that comes with a built-in doctest functionality.
I'd like to seek for input before I start.
The idea is to have a class MyObj from where all my other
classes will subclass.
lets say:
class C(MyObj):
|
by: p.lavarre |
last post by:
From: http://docs.python.org/lib/doctest-soapbox.html ...
Can I somehow tell doctest that it's time to quit?
I ask because not all doctest examples are created equal. Some
failures are catastrophic, making all subsequent failures at least
uninteresting, and maybe painfully slow. Other failures are
negligible, making the print of any subsequent failure valuable.
So sys.exit() doesn't do what I mean: it raises SystemExit, but doctest
|
by: Stuart D. Gathman |
last post by:
I am trying to create a doctest test case for the following:
def quote_value(s):
"""Quote the value for a key-value pair in Received-SPF header field
if needed. No quoting needed for a dot-atom value.
'"abc\\\\\\\\def"'
'"abc..def"'
'""'
'"-all\\\\\\\\x00"'
| | |
by: Eric Mahurin |
last post by:
Noob here. Just got into python a little over a week ago...
One of the (unique?) things I really like about python is the concept
of doctesting. But, now I want more! Here's what I'd like to see:
* easy debugging. As soon as there is a failure (unexpected exception
or mismatch), drop down into the debugger in a way to isolates the bug
down to the nearest test/example as much as possible.
* integrated with code coverage. I'd like...
|
by: jiang.haiyun |
last post by:
Hi,
I am having some serious problems with PyQT4,
when i run pyqt script, I always get 'Segmentation fault'.
the script is simple:
======================
%less qttest.py
from PyQt4 import QtGui, QtCore
import sys
|
by: =?iso-8859-1?B?QW5kcuk=?= |
last post by:
I've encountered a problem using gettext with properties while using a
Python interpreter.
Here's a simple program that illustrate the problem.
==============
# i18n_test.py: test of gettext & properties
import gettext
fr = gettext.translation('i18n_test', './translations',
|
by: Bzyczek |
last post by:
Hello,
I have problems with running doctests if I use czech national
characters in UTF-8 encoding.
I have Python script, which begin with encoding definition:
# -*- coding: utf-8 -*-
I have this function with doctest:
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| | |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| | |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |