[Tutor] doctest: how to test a single function?
I'm an admitted newb trying to enter the Python community and use Python significantly (versus occassionally). dockets seems to be much more powerful than I can figure out how to tap. I have a function inside a file that's an embedded test that (currently) works fine. However, the package has a ton of these, and running all of the tests on all functions just to check the changed function is very time consuming. I can't make heads or tails out of what the manual means. I've read section 25.2 and think I understand it, but clearly do not. What I do is: >>> import doctest >>> doctest.run_docstring_examples("functionname",globs[name="filename.py"]) ^ SyntaxError: invalid syntax I've also tried import filename help(filename.functionname) (works fine) doctest.run_docstring_examples("filename.functionname") Traceback (most recent call last): File "", line 1, in TypeError: run_docstring_examples() missing 1 required positional argument: 'globs' Now, if I do >>> doctest.run_docstring_examples("sigp.frfestH1",globs=None) nothing happens. Everything works fine from a command line: bash:> python filename.py (I have the end of the file set to run doctest per easily found numerous examples) except I have a ridiculous lag due to running tests that are unnecessary. Trying to send options doesn't work either bash:> python -m 'doctest.run__docstring_examples("filename.functionname",globs="")' filename.py /opt/local/bin/python: Error while finding spec for 'doctest.run__docstring_examples("sigp.frfestH1",globs="")' (: No module named 'doctest.run__docstring_examples("sigp'; 'doctest' is not a package) or bash:> python -m 'doctest.run__docstring_examples("functionname",globs=None)' filename.py /opt/local/bin/python: Error while finding spec for 'doctest.run__docstring_examples("sigp.frfestH1",globs="")' (: No module named 'doctest.run__docstring_examples("sigp'; 'doctest' is not a package) I appreciate your efforts to address my cluelessness. Thank You, Joe ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest question
On 27/11/12 20:50, Albert-Jan Roskam wrote: Function name "_setMultRespDefsEx" is not self-explanatory, or even *hint* at what the function is supposed to do. It appears to take a dictionary of stuff, and formats it as a string. It would be nice[1] if your docstring explained what sort of stuff. But in my defense (a little bit, at least), this is a helper function for another function that *does* have a good explanation/docstring. I should mention that in this function's docstring though. Yes! You're not just writing documentation for others. You're also writing documentation for yourself, in six months time, or even six weeks time, when the function is no longer fresh in your mind and you only have the vaguest memory of what it is supposed to do. [...] Doctesting anything to do with dictionaries is tricky, because you cannot rely on the order of a dict. There are a couple of different ways to solve that: Huh? Although I am iterating over a dictionary (which is unordered), the return value will, given a certain input, always be the same. Why is the 'unorderedness' relevant here? Because if you don't sort the dictionary items, the doctest fails. I know this, because the first time I ran it, it failed for exactly this reason. Feel free to take the call to sorted() out. When you do, your input dict looks like this: {'mesetx': ..., 'mesety': ...} # X first, Y second and your doctest, *as you wrote it*, has the same order: $mesetx= ... $mesety= ... BUT the actual output of the function may be in the opposite order, Y first and X second. Or at least, that's the order *I* get, running CPython 2.7.2 under Centos Linux built with gcc 4.1.2. What *you* get, running some other version of Python, built with a different compiler, under a different operating system, may be different. With only two items in the dict, you have a 50% chance of the doctest matching the actual run of the dict. The only promise that Python makes about the order of iterating over a dict is that if you iterate over the same dict twice, without making any changes, in the same Python run, you will get the same output. That is all. You might get a different order if you do any of these things: - modify the dict between runs, even if you reverse the changes; - change the way you assemble the dict in the first place; - use a different version of Python; - or a different implementation; - or theoretically even the same version but on a different OS; - or even if you merely exit Python and run the script again. [steve@ando ~]$ python3.3 -c "print({'a': None, 'b': None})" {'b': None, 'a': None} [steve@ando ~]$ python3.3 -c "print({'a': None, 'b': None})" {'a': None, 'b': None} -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest question
On 11/27/2012 04:50 AM, Albert-Jan Roskam wrote: > >> On 27/11/12 08:06, Albert-Jan Roskam wrote: >>> (Steven D'Aprano wrote, even though the indentation is wrong) >>> >>> >>> >>> Doctesting anything to do with dictionaries is tricky, because you >>> cannot rely on the order of a dict. There are a couple of different >>> ways to solve that: > > Huh? Although I am iterating over a dictionary (which is unordered), > the return value will, given a certain input, always be the same. Why > is the 'unorderedness' relevant here? > It's only promised to be the same for a single run of the program. http://permalink.gmane.org/gmane.comp.python.devel/131826 In particular, """ Hash randomization causes the iteration order of dicts and sets to be unpredictable and differ across Python runs. Python has never guaranteed iteration order of keys in a dict or set, and applications are advised to never rely on it. Historically, dict iteration order has not changed very often across releases and has always remained consistent between successive executions of Python.""" Starting with the releases described in that document, hash randomization was introduced, but disabled by default. But a user might enable it (with the -R cmd switch, or an environment variable). And in the latest version (3.3, i believe it's enabled by default, as a protection against a security threat. Even if you somehow can assure that your code will never run on those versions, it has never been assured that the hash ordering remains stable between even minor versions of the releases. > (Steven again:) >> * the lazy solution: always use doctests on dicts with a single item; >> >> * change the function to always process the dict in a known order; >> >> * change the doctest to post-process the function result, e.g. pull >> the string apart into separate lines, sort the lines, put it >> back together. >> >> >> As Steven points out, it's dangerous to doctest with a dictionary without some form of enforced ordering. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest question
> On 27/11/12 08:06, Albert-Jan Roskam wrote: >> Hi, >> >> I am using doctest and I am struggling with newlines characters >> (see below). One is the newline escape (backslash) for a long >> dictionary definition. The other is an embedded \n in the output. >> I used the +NORMALIZE_WHITESPACE directive. I also tried using a >> triple-quoted raw docstring. Any ideas? > > Yes, quite a few. > > Your following example is hard to understand and, as they say in > English, "as clear as mud". It would help a lot if you laid out the > example dictionary so that it was easier to read, and if you followed > the standard convention to end the docstring with a single """ so > that it separates the end of the docstring from the start of the code. Ok, good idea. After all, "Readability counts" > Function name "_setMultRespDefsEx" is not self-explanatory, or even > *hint* at what the function is supposed to do. It appears to take a > dictionary of stuff, and formats it as a string. It would be nice[1] > if your docstring explained what sort of stuff. But in my defense (a little bit, at least), this is a helper function for another function that *does* have a good explanation/docstring. I should mention that in this function's docstring though. You're right that I could, at the very least, start by saying: """ Helper function to set extended multiple response definitions (see function 'blaah' for further info) """ > The example given should be simple, not complex. If you must give a > complex example, always give a simple example first. > > Examples should be written for clarity, not as code golf. There is no > prize for stuffing everything into one or two lines. > > Doctext directives are not global to the docstring, they must appear > on the same line as the doctest itself. AHA! I missed that from the online documentation. Thank you. > Take advantage of Python's implicit line continuation to avoid > problems with backslash line continuations. > > Doctesting anything to do with dictionaries is tricky, because you > cannot rely on the order of a dict. There are a couple of different > ways to solve that: Huh? Although I am iterating over a dictionary (which is unordered), the return value will, given a certain input, always be the same. Why is the 'unorderedness' relevant here? > * the lazy solution: always use doctests on dicts with a single item; > > * change the function to always process the dict in a known order; > > * change the doctest to post-process the function result, e.g. pull > the string apart into separate lines, sort the lines, put it > back together. > > > Here's my attempt: > > > import doctest > import copy > > def _setMultRespDefsEx(multRespDefs): > """Format a dictionary of stuff as a string. Expects that > dict contains: > > {breakfast: {spam: foo, ham: bar} blah blah blah ...} # or whatever > > >>> xdict = {'countedValue': '1', > 'firstVarIsLabel': True, 'label': '', > ... 'setType': 'E','varNames': > ['mevar1', 'mevar2', 'mevar3']} > >>> ydict = {'countedValue': 'Yes', > 'firstVarIsLabel': False, > ... 'label': 'Enhanced set with user specified > label', > ... 'setType': 'E', 'varNames': > ['mevar4', 'mevar5', 'mevar6']} > >>> adict = {'mesetx': xdict, 'mesety': ydict} > >>> print(_setMultRespDefsEx(adict)) > $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 > $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 > mevar6 > > KNOWN BUGS: > > 1) Sometimes this function returns a dict instead of a string. > 2) The formatted string output is ambiguous. > > """ > mrDefs = [] # "That's Mister Defs to you" :-) ;-))) > for setName, rest in sorted(multRespDefs.iteritems()): > if rest["setType"] != "E": > return {} > rest["setName"] = setName > v = int(rest["firstVarIsLabel"]) > rest["firstVarIsLabel"] = v if v == 1 else "" > rest["valueLen"] = len(rest["countedValue"]) > rest["lblLen"] = len(rest["label"]) > rest["label"] = rest["label"] > rest["varNames"] = " > ".join(rest["varNames"]) > mrDef = "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s > %(valueLen)s " > mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" > mrDefs.append((mrDef % rest).replace(" ", " ")) > return "\n".join(mrDefs) > > > > And running the doctest: > > py> doctest.testmod() > TestResults(failed=0, attempted=4) > > > > > > [1] By "nice" I mean *essential*. > > > -- Steven > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest question
On 27/11/12 09:02, Steven D'Aprano wrote: Here's my attempt: def _setMultRespDefsEx(multRespDefs): """Format a dictionary of stuff as a string. Expects that dict contains: [...] KNOWN BUGS: 1) Sometimes this function returns a dict instead of a string. 2) The formatted string output is ambiguous. """ Oops, I forgot one: 3) This modifies the input argument. Never call this function except on a temporary deep copy of your dict. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest question
On 27/11/12 08:06, Albert-Jan Roskam wrote: Hi, I am using doctest and I am struggling with newlines characters (see below). One is the newline escape (backslash) for a long dictionary definition. The other is an embedded \n in the output. I used the +NORMALIZE_WHITESPACE directive. I also tried using a triple-quoted raw docstring. Any ideas? Yes, quite a few. Your following example is hard to understand and, as they say in English, "as clear as mud". It would help a lot if you laid out the example dictionary so that it was easier to read, and if you followed the standard convention to end the docstring with a single """ so that it separates the end of the docstring from the start of the code. Function name "_setMultRespDefsEx" is not self-explanatory, or even *hint* at what the function is supposed to do. It appears to take a dictionary of stuff, and formats it as a string. It would be nice[1] if your docstring explained what sort of stuff. The example given should be simple, not complex. If you must give a complex example, always give a simple example first. Examples should be written for clarity, not as code golf. There is no prize for stuffing everything into one or two lines. Doctext directives are not global to the docstring, they must appear on the same line as the doctest itself. Take advantage of Python's implicit line continuation to avoid problems with backslash line continuations. Doctesting anything to do with dictionaries is tricky, because you cannot rely on the order of a dict. There are a couple of different ways to solve that: * the lazy solution: always use doctests on dicts with a single item; * change the function to always process the dict in a known order; * change the doctest to post-process the function result, e.g. pull the string apart into separate lines, sort the lines, put it back together. Here's my attempt: import doctest import copy def _setMultRespDefsEx(multRespDefs): """Format a dictionary of stuff as a string. Expects that dict contains: {breakfast: {spam: foo, ham: bar} blah blah blah ...} # or whatever >>> xdict = {'countedValue': '1', 'firstVarIsLabel': True, 'label': '', ... 'setType': 'E','varNames': ['mevar1', 'mevar2', 'mevar3']} >>> ydict = {'countedValue': 'Yes', 'firstVarIsLabel': False, ... 'label': 'Enhanced set with user specified label', ... 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6']} >>> adict = {'mesetx': xdict, 'mesety': ydict} >>> print(_setMultRespDefsEx(adict)) $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 KNOWN BUGS: 1) Sometimes this function returns a dict instead of a string. 2) The formatted string output is ambiguous. """ mrDefs = [] # "That's Mister Defs to you" :-) for setName, rest in sorted(multRespDefs.iteritems()): if rest["setType"] != "E": return {} rest["setName"] = setName v = int(rest["firstVarIsLabel"]) rest["firstVarIsLabel"] = v if v == 1 else "" rest["valueLen"] = len(rest["countedValue"]) rest["lblLen"] = len(rest["label"]) rest["label"] = rest["label"] rest["varNames"] = " ".join(rest["varNames"]) mrDef = "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s %(valueLen)s " mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" mrDefs.append((mrDef % rest).replace(" ", " ")) return "\n".join(mrDefs) And running the doctest: py> doctest.testmod() TestResults(failed=0, attempted=4) [1] By "nice" I mean *essential*. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] doctest question
Hi, I am using doctest and I am struggling with newlines characters (see below). One is the newline escape (backslash) for a long dictionary definition. The other is an embedded \n in the output. I used the +NORMALIZE_WHITESPACE directive. I also tried using a triple-quoted raw docstring. Any ideas? While we're at it: is this a good book? http://www.packtpub.com/python-testing-beginners-guide/book It should be complete, not too shallow, nor so detailed that is becomes too impractical. Thanks! import doctest import copy def _setMultRespDefsEx(multRespDefs): """>>> multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ 'label': '', 'setType': 'E','varNames': ['mevar1', 'mevar2', \ 'var3']}, 'mesety': {'countedValue': 'Yes', 'firstVarIsLabel': \ False, 'label': 'Enhanced set with user specified label', \ 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6']}} >>> _setMultRespDefsEx(multRespDefs) $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 # doctest: +NORMALIZE_WHITESPACE""" mrDefs = [] for setName, rest in multRespDefs.iteritems(): if rest["setType"] != "E": return {} rest["setName"] = setName v = int(rest["firstVarIsLabel"]) rest["firstVarIsLabel"] = v if v == 1 else "" rest["valueLen"] = len(rest["countedValue"]) rest["lblLen"] = len(rest["label"]) rest["label"] = rest["label"] rest["varNames"] = " ".join(rest["varNames"]) mrDef = "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s %(valueLen)s " mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" mrDefs.append((mrDef % rest).replace(" ", " ")) return "\n".join(mrDefs) if __name__ == "__main__": x = {"setType": "E", "label": "Enhanced set with user specified label", "varNames": ["mevar4", "mevar5", "mevar6"], "countedValue": "Yes", "firstVarIsLabel": False} d = {'testme': copy.deepcopy(x), 'testmeMore': copy.deepcopy(x)} print _setMultRespDefsEx(d) # prints desired result doctest.testmod() # fails because of newline! See below ** File "__main__", line 3, in __main__._setMultRespDefsEx Failed example: _setMultRespDefsEx(multRespDefs) Expected: $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 # doctest: +NORMALIZE_WHITESPACE Got: mesetx {'countedValue': '1', 'firstVarIsLabel': True, 'setType': 'E', 'varNames': ['mevar1', 'mevar2', 'var3'], 'label': ''} mesety {'countedValue': 'Yes', 'firstVarIsLabel': False, 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6'], 'label': 'Enhanced set with user specified label'} '$mesetx=E 11 1 1 0 mevar1 mevar2 var3\n$mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6' ** 1 items had failures: 1 of 2 in __main__._setMultRespDefsEx ***Test Failed*** 1 failures. ** 1st error with r-escaped docstring ** File "__main__", line 5, in __main__._setMultRespDefsEx Failed example: multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ Exception raised: Traceback (most recent call last): File "C:\Python26\lib\doctest.py", line 1241, in __run compileflags, 1) in test.globs File "", line 1 multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ ^ SyntaxError: unexpected EOF while parsing * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
On 11/17/2011 10:56 PM, Nidian Job-Smith wrote: Date: Thu, 17 Nov 2011 22:49:33 -0500 From: d...@davea.name To: nidia...@hotmail.com CC: tutor@python.org Subject: Re: [Tutor] Doctest error! On 11/18/2011 10:29 AM, John wrote: Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ type(rot13("bob")) len(rot13("foobar")) 6 rot13("abc") 'nop' rot13("XYZ") 'KLM' rot13('5 The Parade') '5 Gur Cnenqr' rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result The line "if int:" is clearly wrong. Did you write this code yourself, or was it typed in from a listing somewhere? I'd assume that you wanted to do some check on the char value. But if int will always be true. -- DaveA I want it to look in s, and only perform this code on the letters in s(not numbers): char_low = s.lower()if char_low<= 'm':dist = 13else:dist = -13 Your formatting is messed up, and I can now see there at least one other bug in it anyway. The method to check if a particular character is alphabetic is str.isalpha(). See if you can see what variable to call that on. Hint: it's not s, since you want to check one character at a time in your loop. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
> Date: Thu, 17 Nov 2011 22:49:33 -0500 > From: d...@davea.name > To: nidia...@hotmail.com > CC: tutor@python.org > Subject: Re: [Tutor] Doctest error! > > On 11/18/2011 10:29 AM, John wrote: > > > > Hi all, > > When i run a doctest on this piece of code (shown at bottom) i get > > this error message [from the doctest]: > > > > > > > > Trying: > > rot13('5 The Parade') > > Expecting: > > '5 Gur Cnenqr' > > ** > > File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 > > Failed example: > > rot13('5 The Parade') > > Expected: > > '5 Gur Cnenqr' > > Got: > > 'B-aur-]n\x7fnqr' > > Trying: > > rot13('5 Gur Cnenqr') > > Expecting: > > '5 The Parade' > > ** > > File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 > > Failed example: > > rot13('5 Gur Cnenqr') > > Expected: > > '5 The Parade' > > Got: > > 'B-T\x82\x7f-P{r{~\x7f' > > > > > > > > An one have any idea why? (I'm guessing its to do with the numbers) > > > > > > code: > > > > def rot13(s): > > > > """ > > >>> type(rot13("bob")) > > > > >>> len(rot13("foobar")) > > 6 > > >>> rot13("abc") > > 'nop' > > >>> rot13("XYZ") > > 'KLM' > > >>> rot13('5 The Parade') > > '5 Gur Cnenqr' > > >>> rot13('5 Gur Cnenqr') > > '5 The Parade' > > """ > > result = '' # initialize output to empty > > for char in s: # iterate over string > > if int: > > char_low = s.lower() > > if char_low<= 'm': > > dist = 13 > > else: > > dist = -13 > > char = chr(ord(char) + dist) > > result+=char > > return result > > The line "if int:" is clearly wrong. Did you write this code > yourself, or was it typed in from a listing somewhere? I'd assume that > you wanted to do some check on the char value. But if int will always > be true. > > > > > -- > > DaveA I want it to look in s, and only perform this code on the letters in s(not numbers): char_low = s.lower() if char_low <= 'm': dist = 13 else: dist = -13 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest error!
On 11/18/2011 10:29 AM, John wrote: Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result The line "if int:" is clearly wrong. Did you write this code yourself, or was it typed in from a listing somewhere? I'd assume that you wanted to do some check on the char value. But if int will always be true. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Doctest error!
Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest, object references and the use of ellipses
[Tim Peters] >> That "should work", provided there aren't differences in whitespace >> that are invisible to us in this medium. For example, if, in your >> source file, there's actually a (one or more) trailing space on your >> line of expected output, then it would _not_ match the actual output. >> Try adding +REPORT_NDIFF to your #doctest options; that will point out >> all differences (including whitespace). [Don Taylor] > Oh, thank you! Cool -- glad it worked! > Yes, there was a trailing whitespace. And yes I did read the manual > that warned about this but I guess it did not register deep enough into > my reptile brain (you know, the Python brain). > > I will try not to do this again (and I probably won't). I'll share a secret :-) I work on Python development, and a few times per week I run this from the root of a Python checkout (this is on Windows, BTW): python \Python24\Tools\Scripts\reindent.py -r . reindent.py is in your distribution too. It ensures (by rewriting files as needed) that all .py files reachable from "." conform to core Python's whitespace standards, which includes things like 4-space indentation, no hard tab characters, and no trailing whitespace on any lines. All the .py files in a distribution are automatically kept free of "whitespace surprises" this way. You're allowed to run that on your code too ;-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest, object references and the use of ellipses
Tim Peters wrote: > That "should work", provided there aren't differences in whitespace > that are invisible to us in this medium. For example, if, in your > source file, there's actually a (one or more) trailing space on your > line of expected output, then it would _not_ match the actual output. > Try adding +REPORT_NDIFF to your #doctest options; that will point out > all differences (including whitespace). Oh, thank you! Yes, there was a trailing whitespace. And yes I did read the manual that warned about this but I guess it did not register deep enough into my reptile brain (you know, the Python brain). I will try not to do this again (and I probably won't). Don. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest, object references and the use of ellipses
[Don Taylor] > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ...pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] That "should work", provided there aren't differences in whitespace that are invisible to us in this medium. For example, if, in your source file, there's actually a (one or more) trailing space on your line of expected output, then it would _not_ match the actual output. Try adding +REPORT_NDIFF to your #doctest options; that will point out all differences (including whitespace). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest, object references and the use of ellipses
Kent Johnson wrote: > Don Taylor wrote: > >>Hi: >> >>I am trying to use Doctest and am having trouble using the ellipsis >>feature when trying to match an object reference. > > > What version of Python are you using? The ELLIPSIS comment was added in > Python 2.4. > I am using 2.4.2 Don. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doctest, object references and the use of ellipses
Don Taylor wrote: > Hi: > > I am trying to use Doctest and am having trouble using the ellipsis > feature when trying to match an object reference. What version of Python are you using? The ELLIPSIS comment was added in Python 2.4. Kent > > Here is the code: > > def add_change_listener(self, listener): > ''' > > Returns list of listeners just for testing. > >>> def mock_listener(): > ...pass > >>> model = Model() > >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > [] > > ''' > > self.listeners.append(listener) > return self.listeners > > This is what I get back: > > Trying: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expecting: > [] > ** > File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, > in __main__.Model.add_change_listener > Failed example: > model.add_change_listener(mock_listener) #doctest: +ELLIPSIS > Expected: > [] > Got: > [] > > As far as I can tell from the Doctest documentation this test should > have passed. > > Any help on what I am doing wrong would be much appreciated. > > Thanks, > > Don. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Doctest, object references and the use of ellipses
Hi: I am trying to use Doctest and am having trouble using the ellipsis feature when trying to match an object reference. Here is the code: def add_change_listener(self, listener): ''' Returns list of listeners just for testing. >>> def mock_listener(): ...pass >>> model = Model() >>> model.add_change_listener(mock_listener) #doctest: +ELLIPSIS [] ''' self.listeners.append(listener) return self.listeners This is what I get back: Trying: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expecting: [] ** File "D:\ProgrammingProjects\MVCExperiments\src\mvcmodel.py", line 14, in __main__.Model.add_change_listener Failed example: model.add_change_listener(mock_listener) #doctest: +ELLIPSIS Expected: [] Got: [] As far as I can tell from the Doctest documentation this test should have passed. Any help on what I am doing wrong would be much appreciated. Thanks, Don. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
Alan Gauld wrote: Also, anything I can do... Presently, since I'm running windows xp, I would have to hunt for the command prompt and type in the command Start->Run Type cmd, Hit OK :-) Or drag the icon from accessories into the start menu or to the desktop. Or drag the icon to the left side of the task bar Or, my favorite, add a 'Command Prompt' item to the right-click menu so you can right-click a directory and open a command prompt at that directory. The recipe is here: http://www.petri.co.il/add_command_prompt_here_shortcut_to_windows_explorer.htm Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
Jacob S. wrote: Even so, doctest doesn't seem to recognize the module level docstring. It will run the test inside the functions, but it says there isn't a test on the module level. I put the docstring just like in the example at the link you provided... Please post the code for the module you are testing. Also, anything I can do... Presently, since I'm running windows xp, I would have to hunt for the command prompt and type in the command '"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working python programs\testmodules.py" -v' You should put C:\python24 in your PATH environment variable. Not sure how to do that on XP; on Win2K I - right-click My Computer and select Properties - click the Advanced tab - click Environment Variables - find the System variable Path and edit it - append ";C:\python24" to Path (no quotes; the semicolon is needed, it is a separator for the Path variable) - click OK a few times - restart your DOS shell so it gets the new variable Now you should be able to open a command line in the directory containing your program and type > python testmodules.py -v Oh, the light goes on...you want to be able to just double-click testmodules.py. See below for the fix for -v ...or make a batch file to do it for me... How can I make testmodules.py (shown below) append the -v to itself? Is there a self.results or something in testmod? From the docs at http://docs.python.org/lib/doctest-basic-api.html: "Optional argument verbose prints lots of stuff if true" So try doctest.testmod(eval(modtotest), verbose=True) ## testmodules.py ### import doctest modtotest = 'FractionReducer2' exec "import %s" % modtotest doctest.testmod(eval(modtotest)) raw_input() # Since you will be editing this to change the module under test, I don't think there is any benefit to putting the module name in a string. I would write it like this: import doctest import FractionReducer2 as test_module doctest.testmod(test_module, verbose=True) raw_input() This preserves the single point of change when you want to test a different module, but it is IMO much more readable. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
> Also, anything I can do... Presently, since I'm running windows xp, I would > have to hunt for the command prompt and type in the command Start->Run Type cmd, Hit OK :-) Or drag the icon from accessories into the start menu or to the desktop. > '"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working > python programs\testmodules.py" -v' Why not create a shortcut and add that to your right click menu? Or to your desktop if you want - but I hate cluttered desktops! > ...or make a batch file to do it for me... A shortcut will suffice, a batch job is overkill for a one liner Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
> Also, anything I can do... Presently, since I'm running windows xp, I > would have to hunt for the command prompt and type in the command Click Start, click Run, type CMD, press Enter. Voila! :) Patric > > '"C:\python24\python.exe" "C:\documents and > settings\jacob\desktop\working python programs\testmodules.py" -v' > > ...or make a batch file to do it for me... > How can I make testmodules.py (shown below) append the -v to itself? > Is there a self.results or something in testmod? > > ## testmodules.py ### > import doctest > > modtotest = 'FractionReducer2' > > exec "import %s" % modtotest > doctest.testmod(eval(modtotest)) > raw_input() > # > > > Thanks, > Jacob Schmidt > > > > What docs are you looking at?? The module docs at > http://docs.python.org/lib/module-doctest.html > > have a complete example of testing a module with a main function. Or > > you > can use the code in my last > > post. > > > > Kent > > > > Jacob S. wrote: > > > Hi. > > > > > > Okay, so I look at the documentation at it says (in my words): > > > > > > "First Class - DocTest -- Make a test object with such and such > attributes > > > that you can test. > > > Second Class - i don't remember the name - Make Jacob look stupid > > > with > big > > > words > > > Third Class - DocTestSuite - Convert a doctest object to a > > > unittest > object - > > > Okay... so how does that help? > > > Fourth Class - DocTestFinder - Find the docstrings that contain > > > test > code > > > and extract them." > > > > > > So, my question, I guess, is How did the documentation help, and, > > > How do > I > > > have doctest test all of my module's function's docstrings? > > > > > > Thanks in advance, > > > Jacob Schmidt > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
I forgot to mention... When I explicitly define the variable __doc__ at the module level, it *does* recognize the module level docstring. > I think I'm losing my mind... > > Maybe it's because I go back to school the day after tomorrow? > The thing that helped the most was the -v parameter... > > Even so, doctest doesn't seem to recognize the module level docstring. > It will run the test inside the functions, but it says there isn't a test on > the module level. > I put the docstring just like in the example at the link you provided... > > Also, anything I can do... Presently, since I'm running windows xp, I would > have to hunt for the command prompt and type in the command > > '"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working > python programs\testmodules.py" -v' > > ...or make a batch file to do it for me... > How can I make testmodules.py (shown below) append the -v to itself? Is > there a self.results or something in testmod? > > ## testmodules.py ### > import doctest > > modtotest = 'FractionReducer2' > > exec "import %s" % modtotest > doctest.testmod(eval(modtotest)) > raw_input() > # > > > Thanks, > Jacob Schmidt > > > > What docs are you looking at?? The module docs at > http://docs.python.org/lib/module-doctest.html > > have a complete example of testing a module with a main function. Or you > can use the code in my last > > post. > > > > Kent > > > > Jacob S. wrote: > > > Hi. > > > > > > Okay, so I look at the documentation at it says (in my words): > > > > > > "First Class - DocTest -- Make a test object with such and such > attributes > > > that you can test. > > > Second Class - i don't remember the name - Make Jacob look stupid with > big > > > words > > > Third Class - DocTestSuite - Convert a doctest object to a unittest > object - > > > Okay... so how does that help? > > > Fourth Class - DocTestFinder - Find the docstrings that contain test > code > > > and extract them." > > > > > > So, my question, I guess, is How did the documentation help, and, How do > I > > > have doctest test all of my module's function's docstrings? > > > > > > Thanks in advance, > > > Jacob Schmidt > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
I think I'm losing my mind... Maybe it's because I go back to school the day after tomorrow? The thing that helped the most was the -v parameter... Even so, doctest doesn't seem to recognize the module level docstring. It will run the test inside the functions, but it says there isn't a test on the module level. I put the docstring just like in the example at the link you provided... Also, anything I can do... Presently, since I'm running windows xp, I would have to hunt for the command prompt and type in the command '"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working python programs\testmodules.py" -v' ...or make a batch file to do it for me... How can I make testmodules.py (shown below) append the -v to itself? Is there a self.results or something in testmod? ## testmodules.py ### import doctest modtotest = 'FractionReducer2' exec "import %s" % modtotest doctest.testmod(eval(modtotest)) raw_input() # Thanks, Jacob Schmidt > What docs are you looking at?? The module docs at http://docs.python.org/lib/module-doctest.html > have a complete example of testing a module with a main function. Or you can use the code in my last > post. > > Kent > > Jacob S. wrote: > > Hi. > > > > Okay, so I look at the documentation at it says (in my words): > > > > "First Class - DocTest -- Make a test object with such and such attributes > > that you can test. > > Second Class - i don't remember the name - Make Jacob look stupid with big > > words > > Third Class - DocTestSuite - Convert a doctest object to a unittest object - > > Okay... so how does that help? > > Fourth Class - DocTestFinder - Find the docstrings that contain test code > > and extract them." > > > > So, my question, I guess, is How did the documentation help, and, How do I > > have doctest test all of my module's function's docstrings? > > > > Thanks in advance, > > Jacob Schmidt > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doctest
What docs are you looking at?? The module docs at http://docs.python.org/lib/module-doctest.html have a complete example of testing a module with a main function. Or you can use the code in my last post. Kent Jacob S. wrote: Hi. Okay, so I look at the documentation at it says (in my words): "First Class - DocTest -- Make a test object with such and such attributes that you can test. Second Class - i don't remember the name - Make Jacob look stupid with big words Third Class - DocTestSuite - Convert a doctest object to a unittest object - Okay... so how does that help? Fourth Class - DocTestFinder - Find the docstrings that contain test code and extract them." So, my question, I guess, is How did the documentation help, and, How do I have doctest test all of my module's function's docstrings? Thanks in advance, Jacob Schmidt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] doctest
Hi. Okay, so I look at the documentation at it says (in my words): "First Class - DocTest -- Make a test object with such and such attributes that you can test. Second Class - i don't remember the name - Make Jacob look stupid with big words Third Class - DocTestSuite - Convert a doctest object to a unittest object - Okay... so how does that help? Fourth Class - DocTestFinder - Find the docstrings that contain test code and extract them." So, my question, I guess, is How did the documentation help, and, How do I have doctest test all of my module's function's docstrings? Thanks in advance, Jacob Schmidt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor