Re: [Tutor] unittest difficulty
Is `0.0` the troublesome float here? On Wed, Jul 19, 2017 at 7:35 AM, Shall, Sydney wrote: > I am learning to use unittest. > > I have written a program that runs as it should. > 247 tests give me a satisfactory answer. > > I have now added one more test and I get an error which I do not > understand. > > The two relevant tests are: > > def test_type_capitalsadvanced(self): > self.assertEqual(type(self.capitalsadvanced), numpy.ndarray) > > def test_zero_in_capitalsadvanced(self): > self.assertIn(self.capitalsadvanced, 0.0) > > The error message is: > > Traceback (most recent call last): > File > "/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", > line 320, in test_zero_in_capitalsadvanced > self.assertIn(self.capitalsadvanced, 0.0) > File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line > 1077, in assertIn > if member not in container: > TypeError: argument of type 'float' is not iterable > > Final output from the tests is : > > Ran 247 tests in 1.179s > > FAILED (failures=9, errors=1) > > The failures all arise from a 'nan'. > It is this problem that I am trying to resolve. > > My problem is that the first test tells me correctly that the object > capitalsadvanced is a numpy.ndarray. But the second test error message says > it is a float. > > I should add that the program creates the initial data set by making use > of the random function which is given a mean to work with. Thus each test > run will be with different input data. But repeated tests show the same > errors. > > Any guidance will be very welcome. > > Sydney > > _ > > Professor Sydney Shall > Department of Haematology/Oncology > Phone: +(0)2078489200 > E-Mail: sydney.shall > [Correspondents outside the College should add @kcl.ac.uk] > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest not working
On Thu, Nov 19, 2015 at 8:25 AM, Mike wrote: > I'm trying to unit test a self-built regular expression processor for an > assignment. I'm trying to set up unit tests for the package, but it's not > executing them. This is my first time trying to use the unittest module, so > I'm sure I'm missing something, I'm just not sure what. I even put a test > case in there I knew would fail just to try it. > > Unit Test code: > import unittest > from regex import regexp > class RegexTest(unittest.TestCase): > def fail_test(self): > self.assertEqual(1, 2) > > def basic_test(self): > self.assertEqual(regexp('Hello', 'Goodbye'), '') > self.assertEqual(regexp('hello', 'ello'), 'ello') > with self.assertRaises(SyntaxError): > regexp('hello', 'he)') > Your functions should start with the word 'test'. For example: def test_fail_test(self): According to the docs, "This naming convention informs the test runner about which methods represent tests." ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest not working
On 19 November 2015 at 13:25, Mike wrote: > I'm trying to unit test a self-built regular expression processor for an > assignment. I'm trying to set up unit tests for the package, but it's not > executing them. This is my first time trying to use the unittest module, so > I'm sure I'm missing something, I'm just not sure what. I even put a test > case in there I knew would fail just to try it. > > Unit Test code: > import unittest > from regex import regexp > > class RegexTest(unittest.TestCase): > def fail_test(self): > self.assertEqual(1, 2) > > def basic_test(self): > self.assertEqual(regexp('Hello', 'Goodbye'), '') > self.assertEqual(regexp('hello', 'ello'), 'ello') > with self.assertRaises(SyntaxError): > regexp('hello', 'he)') > > if __name__ == '__main__': > unittest.main() > > Output: > > -- > Ran 0 tests in 0.000s > > OK > Exit code: False The unittest.main() call will attempt to find all of the TestCase subclasses and for each class, create an instance and call all of the methods that are named test_xxx. So if you rename your methods as test_fail and test_basic then I think it should work. The reason for this is that you might want to add other methods to your TestCase subclass that will not be directly called by the test runner but that you can use in your tests. -- Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest not working
Mike wrote: > I'm trying to unit test a self-built regular expression processor for an > assignment. I'm trying to set up unit tests for the package, but it's not > executing them. This is my first time trying to use the unittest module, > so I'm sure I'm missing something, I'm just not sure what. I even put a > test case in there I knew would fail just to try it. > > Unit Test code: > import unittest > from regex import regexp > > class RegexTest(unittest.TestCase): > def fail_test(self): > self.assertEqual(1, 2) > > def basic_test(self): > self.assertEqual(regexp('Hello', 'Goodbye'), '') > self.assertEqual(regexp('hello', 'ello'), 'ello') > with self.assertRaises(SyntaxError): > regexp('hello', 'he)') > > if __name__ == '__main__': > unittest.main() > > Output: > > -- > Ran 0 tests in 0.000s > > OK > Exit code: False Rename the mathods fail_test to test_fail, and basic_test to test_basic. Test methods are recognized by their prefix. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
[ I've taken this discussion back to the tutor list. - Cameron ] On 01Jun2015 18:14, Sydney Shall wrote: On 31/05/2015 03:00, Cameron Simpson wrote: You say that your results are "all rather close, consistent with the sigma value I have chosen for the spread of my population". I would advocate making some "contraint" tests that verify this property for _any_ input data set. Then you can run with random and _changing_ input data sets to verify that your code produces the expected _kind_ of results with many data sets. [...] range class which stores contiguous ranges efficiently (a sequence of (low,high) pairs). It has a few add/remove operations which are meant to maintain that sequence on ordered minimal form. cutting and merging adjacent ranges is very easy to get wrong, very sensitive to off-by-one logic errors. So my tests for this class include some random tests which do random unpredictable add/remove operations, and run a consistency check on the object after each operation. This gives me good odds of exercising some tricky sequence which I have not considered explicitly myself. You can see the test suite here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py I have studied the material you indicated and it has been most helpful. I think that I have understood the principle involved, but I have had some problem implementing it. The range tests are mostly clear to me but there is one aspect I cannot follow. You use in this suite imports from Range, including Range, overlap, spans and Span. Are these programs that you have written? If so, are they specific to your set up or are they generic? If so, is it possible to obtain these programs? The "cs.range" is a module of my own. As you might imagine, cs.range_tests has the entire purpose of testing cs.range. cs.range is here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range.py Feel free. Since it in turn has some dependencies the easiest way to get it is to use "pip" to install it, as pip will also fetch and insteall its dependencies. But if you just want something to read, fetch and enjoy. I have established a very primitive test suite based on your cs.range >notions and it works fine, but it would be better, I am sure, to do it >properly. There are many other people whose test writing ability surpasses mine. But you're welcome to learn anything you can from mine, and to ask questions. Finally, I have one comment for the respected Moderator, if he is not out on a walk in the highlands in this cold and wet weather. I have taken the liberty of raising my problem here rather than elsewhere, because I have observed that the biological and bio-medical community, who always come late to new notions, is now rapidly discovering python. A great deal of work in these fields involve either stochastic simulations or statistical problems of analysis. The latter are more or less straight-forward, but the simulations are not. You might ask a separate question on the python-l...@python.org about simulations. It has a wider audience than the tutor list and may well include people doing simulation work, or who know where to look. Thanks for all the help. You people are a model of how we could perhaps civilize humanity. Nah. We might all be striving to be a model of how humanity might be when civilised though... Cheers, Cameron Simpson You my man are a danger to society and should be taken out of society for all our sakes. As to what is done to you once removed I couldn't care less. - Roy G. Culley, Unix Systems Administrator ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
On 01/06/15 18:14, Sydney Shall wrote: Finally, I have one comment for the respected Moderator, if he is not out on a walk in the highlands in this cold and wet weather. No, that's on tomorrow's schedule :-) I have taken the liberty of raising my problem here rather than elsewhere, because I have observed that the biological and bio-medical community, who always come late to new notions, is now rapidly discovering python. A great deal of work in these fields involve either stochastic simulations or statistical problems of analysis. The latter are more or less straight-forward, but the simulations are not. I have no problem with this kind of material on tutor because, although the list is for "beginners to Python", that includes those with much experience in other languages and who may expect to use TDD from the beginning. So TDD techniques using standard library modules is a valid topic even though it may be too advanced for those beginners who are new to programming. We need to balance coverage to cater for both categories of "beginner". -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
On 31/05/2015 03:00, Cameron Simpson wrote: On 30May2015 12:16, Sydney Shall wrote: Following advice from you generous people, I have chosen a project >that interests me, to develop some knowledge of python. My projest is a simulation of a biological population. I have a base class and a simulation function, which uses instances of the class. This, after many months of work and lots of advice, now seems to work well. It generates sensible data and when I write a small test program it gives sensible output. Now I want to learn to use unittest. I have written a unittest class which works OK. But the problem I have is that because I use the random module to populate my initial arrays, my data is not strictly predictable even though I am using seed(0). So the tests return many *fails* because the numbers are not exactly correct, although they are all rather close, consistent with the sigma value I have chosen for the spread of my population. I do of course use *almostEqual* and not *Equal*. First of all, several people have posted suggestions for getting identical results on every run. However, there is another approach, which you might consider. (And use in addition, not inseadt of, the reproducable suggestions). It is all very well to have a unit test that runs exactly the same with a test set of data - it lets you have confidence that algorithm changes do not change the outcome. But on for that data set. You say that your results are "all rather close, consistent with the sigma value I have chosen for the spread of my population". I would advocate making some "contraint" tests that verify this property for _any_ input data set. Then you can run with random and _changing_ input data sets to verify that your code produces the expected _kind_ of results with many data sets. So you would have one test which ran with a fixed data set which confirms preidctable unchanging results. And you have other tests with run with randomly chosen data and confirms that outcomes fall within the parameters you expect. You can apply those checks ("outcome in range") to both sets of tests. As an exmaple, I have a few classes which maintain data structures which are sensitive to boundary conditions. The glaring example is a numeric range class which stores contiguous ranges efficiently (a sequence of (low,high) pairs). It has a few add/remove operations which are meant to maintain that sequence on ordered minimal form. cutting and merging adjacent ranges is very easy to get wrong, very sensitive to off-by-one logic errors. So my tests for this class include some random tests which do random unpredictable add/remove operations, and run a consistency check on the object after each operation. This gives me good odds of exercising some tricky sequence which I have not considered explicitly myself. You can see the test suite here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py It has a bunch of explicit specific tests up the top, and then the random consistency test down the bottom as "test30random_set_equivalence". Cheers, Cameron Simpson MS-Word is Not a document exchange format - Jeff Goldberg http://www.goldmark.org/netrants/no-word/attach.html Cameron, Thanks for your most helpful reply. I have studied the material you indicated and it has been most helpful. I think that I have understood the principle involved, but I have had some problem implementing it. The range tests are mostly clear to me but there is one aspect I cannot follow. You use in this suite imports from Range, including Range, overlap, spans and Span. Are these programs that you have written? If so, are they specific to your set up or are they generic? If so, is it possible to obtain these programs? I have established a very primitive test suite based on your cs.range notions and it works fine, but it would be better, I am sure, to do it properly. Finally, I have one comment for the respected Moderator, if he is not out on a walk in the highlands in this cold and wet weather. I have taken the liberty of raising my problem here rather than elsewhere, because I have observed that the biological and bio-medical community, who always come late to new notions, is now rapidly discovering python. A great deal of work in these fields involve either stochastic simulations or statistical problems of analysis. The latter are more or less straight-forward, but the simulations are not. Thanks for all the help. You people are a model of how we could perhaps civilize humanity. -- Sydney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
On 02/06/2015 07:59, Steven D'Aprano wrote: Please keep your replies on the tutor list, so that others may offer advice, and learn from your questions. Thanks, Steve On Mon, Jun 01, 2015 at 06:03:08PM +0100, Sydney Shall wrote: On 31/05/2015 00:41, Steven D'Aprano wrote: On Sat, May 30, 2015 at 12:16:01PM +0100, Sydney Shall wrote: I have written a unittest class which works OK. But the problem I have is that because I use the random module to populate my initial arrays, my data is not strictly predictable even though I am using seed(0). Please show us how you populate your arrays, because what you describe sounds wrong. Seeding to the same value should give the same sequence of values: py> import random py> random.seed(0) py> a = [random.random() for i in range(10**6)] py> random.seed(0) py> b = [random.random() for i in range(10**6)] py> a == b True Thank you for the advice Steven. I was of course aware that I had to use random.seed(0), which I had done. I was puzzled by the fact that it did not give me reprocibly results, which it did when I was learning python. But because you drew attention to the problem, I have looked at again. I surmised that perhaps I had put the seed statement in the wrong place. I have tried several places, but I always get the sam spread of results. Perhaps, to help get advice I should explain that I populate a a list thus: self.ucc = np.random.normal(self.mean_ucc, self.sigma_ucc, 200) This does give me list of 200 slightly different numbers. The mean_ucc is always 15.0 and the sigma value is always 3.75. The actual mean and sigma of the random numbers is checked that it is within 5.0% of 15.0 and 3.75 respectively. Following your advice I did a little test. I repeated a little test program that I have written, which gives me sensible and proper results. I repeated the test 8 times and a then noted a useful output result. When I plot the actual mean of the population used against the output result I chose, I obtain a perfect straight line, which I should. Now I still think that I am using the random.seed(0) either incorrectly or in the wrong place. If there is any other information that might clarify my problem, I will be grateful to be told. I would be most grateful for any guidance you may have, indicating where I should look for what I suspect is a beginner's error. -- Sydney Apolgies. I thought that I had dione so. I will be more careeful infuture. -- Sydney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
On 30May2015 12:16, Sydney Shall wrote: Following advice from you generous people, I have chosen a project >that interests me, to develop some knowledge of python. My projest is a simulation of a biological population. I have a base class and a simulation function, which uses instances of the class. This, after many months of work and lots of advice, now seems to work well. It generates sensible data and when I write a small test program it gives sensible output. Now I want to learn to use unittest. I have written a unittest class which works OK. But the problem I have is that because I use the random module to populate my initial arrays, my data is not strictly predictable even though I am using seed(0). So the tests return many *fails* because the numbers are not exactly correct, although they are all rather close, consistent with the sigma value I have chosen for the spread of my population. I do of course use *almostEqual* and not *Equal*. First of all, several people have posted suggestions for getting identical results on every run. However, there is another approach, which you might consider. (And use in addition, not inseadt of, the reproducable suggestions). It is all very well to have a unit test that runs exactly the same with a test set of data - it lets you have confidence that algorithm changes do not change the outcome. But on for that data set. You say that your results are "all rather close, consistent with the sigma value I have chosen for the spread of my population". I would advocate making some "contraint" tests that verify this property for _any_ input data set. Then you can run with random and _changing_ input data sets to verify that your code produces the expected _kind_ of results with many data sets. So you would have one test which ran with a fixed data set which confirms preidctable unchanging results. And you have other tests with run with randomly chosen data and confirms that outcomes fall within the parameters you expect. You can apply those checks ("outcome in range") to both sets of tests. As an exmaple, I have a few classes which maintain data structures which are sensitive to boundary conditions. The glaring example is a numeric range class which stores contiguous ranges efficiently (a sequence of (low,high) pairs). It has a few add/remove operations which are meant to maintain that sequence on ordered minimal form. cutting and merging adjacent ranges is very easy to get wrong, very sensitive to off-by-one logic errors. So my tests for this class include some random tests which do random unpredictable add/remove operations, and run a consistency check on the object after each operation. This gives me good odds of exercising some tricky sequence which I have not considered explicitly myself. You can see the test suite here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py It has a bunch of explicit specific tests up the top, and then the random consistency test down the bottom as "test30random_set_equivalence". Cheers, Cameron Simpson MS-Word is Not a document exchange format - Jeff Goldberg http://www.goldmark.org/netrants/no-word/attach.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
On Sat, May 30, 2015 at 12:16:01PM +0100, Sydney Shall wrote: > I have written a unittest class which works OK. > But the problem I have is that because I use the random module to > populate my initial arrays, my data is not strictly predictable even > though I am using seed(0). Please show us how you populate your arrays, because what you describe sounds wrong. Seeding to the same value should give the same sequence of values: py> import random py> random.seed(0) py> a = [random.random() for i in range(10**6)] py> random.seed(0) py> b = [random.random() for i in range(10**6)] py> a == b True -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
In a message of Sat, 30 May 2015 12:16:01 +0100, Sydney Shall writes: >MAC OSX 10.10.3 >Enthought Python 2.7 > >I am an almost beginner. > >Following advice from you generous people, I have chosen a project that >interests me, to develop some knowledge of python. >My projest is a simulation of a biological population. >I have a base class and a simulation function, which uses instances of >the class. >This, after many months of work and lots of advice, now seems to work >well. It generates sensible data and when I write a small test program >it gives sensible output. >Now I want to learn to use unittest. >I have written a unittest class which works OK. >But the problem I have is that because I use the random module to >populate my initial arrays, my data is not strictly predictable even >though I am using seed(0). So the tests return many *fails* because the >numbers are not exactly correct, although they are all rather close, >consistent with the sigma value I have chosen for the spread of my >population. I do of course use *almostEqual* and not *Equal*. >So, I would be very grateful for guidance. How does one proceed in this >case? Should I simply create an arbitrary array or value to input into >the function that I want to test? >I would be grateful for any guidance. > >-- >Sydney You can mock your random number generator function to return something that isn't random for the purposes of testing. Mock is part of unittest for Python 3.3 or later, but since you are on 2.7 you will have to import mock as a separate library. This nice blog post http://fgimian.github.io/blog/2014/04/10/using-the-python-mock-library-to-fake-regular-functions-during-tests/ gives a whole slew of examples for how to use mock to mock the random number generator function os.urandom . But you can use it to mock any function you like. If you have trouble getting it to work, come back with code. It is tricky the first time you mock anything, to make sure you put the mock in the correct place, but once you get the hang of this it is dirt simple. Happy hacking, Laura ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest with random population data
Sydney Shall wrote: > MAC OSX 10.10.3 > Enthought Python 2.7 > > I am an almost beginner. > > Following advice from you generous people, I have chosen a project that > interests me, to develop some knowledge of python. > My projest is a simulation of a biological population. > I have a base class and a simulation function, which uses instances of > the class. > This, after many months of work and lots of advice, now seems to work > well. It generates sensible data and when I write a small test program > it gives sensible output. > Now I want to learn to use unittest. > I have written a unittest class which works OK. > But the problem I have is that because I use the random module to > populate my initial arrays, my data is not strictly predictable even > though I am using seed(0). So the tests return many *fails* because the > numbers are not exactly correct, although they are all rather close, > consistent with the sigma value I have chosen for the spread of my > population. I do of course use *almostEqual* and not *Equal*. > So, I would be very grateful for guidance. How does one proceed in this > case? Should I simply create an arbitrary array or value to input into > the function that I want to test? > I would be grateful for any guidance. With the same input your program should produce exactly the same output. Are you entering data into dicts? Try to set the PYTHONHASHSEED environment variable to get reproducible results. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest for: Raises an exception
On 18/02/2015 20:40, Ben Finney wrote: Sydney Shall writes: My test code is the following: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) [This last line should indented, but it refuses to do so!] What is “it” which refuses to indent your text? You might need to use a better message composition tool. If you're typing into a Web application, please see the discussion happening in this forum about appropriate email clients for posting program code. So I'll reformat that code for readability:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)) The traceback is as follows: == ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) -- Traceback (most recent call last): […] "/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line 475, in assertRaises callableObj(*args, **kwargs) TypeError: 'float' object is not callable The error message is correct: the ‘assertRaises’ method expects a callable object in the second parameter, but you've supplied an object which is not callable (a float). Have a closer look at the documentation for ‘TestCase.assertRaises’:: assertRaises(exception, callable, *args, **kwds) Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises> It's unfortunate the documentation doesn't give an example. But note that clause “when `callable` is called with any […] arguments that *are also passed to assertRaises*”. So you don't call the function yourself; if you do, you get back its return value (in your case, a float object) and *that's* your argument to ‘assertRaises’ — not the function you're trying to test! Instead of calling the function and getting its return value, you pass *the function itself* to ‘assertRaises’, along with any arguments you want *the test method* to call it with. This indirection is a little confusing, and again I'm unhappy the documentation doesn't show an example. Here's one:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime, self.cwp.ww, self.cwp.uvc) What the documentation does show as an example, though, is a new-ish feature that might suit you better. You can now make your test code more comprehensible by instead using the ‘assertRaises’ method as a context manager, and then you just call your function normally. Like this:: def test_func_getSurplusLabourTime_Exc(self): with self.assertRaises(ValueError): self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc) Context managers are a very helpful feature that can make code more elegant and readable. They might seem a little magic for now if you haven't learned about them yet, but this is a good demonstration of the improvement they can make. Raul and Ben, Many thanks for the advice. The use of this test is much clearer to me now, and I think it is now working with your help. But I will practice my use of it. As for my formatting, this problem of indentation has not occurred before. I use Thunderbird and Firefox and I have not had this problem up to now. I shall examine the problem and see what is wrong and correct it. Thanks, Sydney -- Sydney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest for: Raises an exception
Sydney Shall writes: > My test code is the following: > > def test_func_getSurplusLabourTime_Exc(self): > > self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) > > > [This last line should indented, but it refuses to do so!] What is “it” which refuses to indent your text? You might need to use a better message composition tool. If you're typing into a Web application, please see the discussion happening in this forum about appropriate email clients for posting program code. So I'll reformat that code for readability:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)) > The traceback is as follows: > > == > ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) > -- > Traceback (most recent call last): […] > "/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", > line 475, in assertRaises > callableObj(*args, **kwargs) > TypeError: 'float' object is not callable The error message is correct: the ‘assertRaises’ method expects a callable object in the second parameter, but you've supplied an object which is not callable (a float). Have a closer look at the documentation for ‘TestCase.assertRaises’:: assertRaises(exception, callable, *args, **kwds) Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises> It's unfortunate the documentation doesn't give an example. But note that clause “when `callable` is called with any […] arguments that *are also passed to assertRaises*”. So you don't call the function yourself; if you do, you get back its return value (in your case, a float object) and *that's* your argument to ‘assertRaises’ — not the function you're trying to test! Instead of calling the function and getting its return value, you pass *the function itself* to ‘assertRaises’, along with any arguments you want *the test method* to call it with. This indirection is a little confusing, and again I'm unhappy the documentation doesn't show an example. Here's one:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime, self.cwp.ww, self.cwp.uvc) What the documentation does show as an example, though, is a new-ish feature that might suit you better. You can now make your test code more comprehensible by instead using the ‘assertRaises’ method as a context manager, and then you just call your function normally. Like this:: def test_func_getSurplusLabourTime_Exc(self): with self.assertRaises(ValueError): self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc) Context managers are a very helpful feature that can make code more elegant and readable. They might seem a little magic for now if you haven't learned about them yet, but this is a good demonstration of the improvement they can make. -- \ “… one of the main causes of the fall of the Roman Empire was | `\that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.” —Robert Firth | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest for: Raises an exception
Hi, When using self.assertRaises like this you should pass a callable (the function you are going to call), but not call the function on the test. The problem is when the function takes arguments. At this point you need to create a callable with the two arguments. That can be done with functools but it's not easy to follow (If you want me to explain more on this path I can happily do it). For me the nicest syntax to test raising exceptions is to use a context manager. As the following: with self.assertRaises(ValueError): self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc) Kind Regards, Raul On Wed, Feb 18, 2015 at 6:15 PM, Sydney Shall wrote: > I use a MAC OSX 10.9.5 > Enthought Canopy Python 2.7.6 > > I am a learner. > > I am now trying to learn unittests as is often emphasised on this list. > I think that I have understood the simple unit tests such as Equal, > Greater etc. > But I am struggling with the syntax of a test for Raises an exception. > > The function that I am tring to test is: > For some reason my indentation has not been correctly copied. > I am sure that it is correct becuase I have chacked it as well as the > program. Also the 20 tests that are OK refer to all the other functions in > the program. > > def getSurplusLabourTime(self, ww, uvc): > self.ww = ww > self.uvc = uvc > try: > self.surplus_labour_time = self.ww - self.uvc > return self.surplus_labour_time > except: > if self.surplus_labour_time <= 0.0: > raise ValueError("Surplus labour time cannot be" + \ > " equal to or shorter than zero!") > > My test code is the following: > > def test_func_getSurplusLabourTime_Exc(self): > > self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) > > [This last line should indented, but it refuses to do so!] > > The traceback is as follows: > > == > ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) > -- > Traceback (most recent call last): > File > "/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current > version/TestCWP_WorkDuration.py", line 88, in test_func_ > getSurplusLabourTime_Exc > self.assertRaises(ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, > self.cwp.uvc)) > File "/Applications/Canopy.app/appdata/canopy-1.5.1.2730. > macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line > 475, in assertRaises > callableObj(*args, **kwargs) > TypeError: 'float' object is not callable > > -- > Ran 21 tests in 0.005s > > FAILED (errors=1) > > > I do know that I have not added the arguments that would sause an > exception to be raised. But I have tried several forms and none have > worked. I get the same traceback as above. > > > Any guidance would be appreciated. > > > > -- > Sydney > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest decorators
> From: Peter Otten <__pete...@web.de> >To: tutor@python.org >Sent: Thursday, April 3, 2014 3:13 PM >Subject: Re: [Tutor] unittest decorators > > >Albert-Jan Roskam wrote: > >> The unittest module has some really handy decorators: @unittest.skip >> and @unittest.skipIf. I use the former for temporary TODO or FIXME things, >> but I use the latter for a more permanent thing: >> @unittest.skipif(sys.version_info()[0] > 2). Yet, in the test summary you >> just see error, skipped, failed. Is it possible to not count the skipIf >> tests? > >You mean like this? > >$ cat skiptest.py >import unittest >import sys > >def hide_if(condition): > def g(f): > return None if condition else f > return g > >class T(unittest.TestCase): > @hide_if(sys.version_info[0] > 2) > def test_two(self): > pass > @hide_if(sys.version_info[0] < 3) > def test_three(self): > pass > >if __name__ == "__main__": > unittest.main() >$ python skiptest.py -v >test_two (__main__.T) ... ok > >-- >Ran 1 test in 0.000s > >OK >$ python3 skiptest.py -v >test_three (__main__.T) ... ok > >-- >Ran 1 test in 0.000s > >OK >$ Wow, yes, this is exactly what I meant! Thank you! Now the "bad/code smell/TODO" skips are separated from the legitimately skipped tests. >> (other than using if-else inside the test --not really a bad >> solution either ;-)? > >I don't understand that remark. Ok, that was indeed a bit cryptic, sorry. I meant something like this: class T(unittest.TestCase): def test_combined(self): if(sys.version_info[0] > 2: pass else: pass ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest decorators
Albert-Jan Roskam wrote: > The unittest module has some really handy decorators: @unittest.skip > and @unittest.skipIf. I use the former for temporary TODO or FIXME things, > but I use the latter for a more permanent thing: > @unittest.skipif(sys.version_info()[0] > 2). Yet, in the test summary you > just see error, skipped, failed. Is it possible to not count the skipIf > tests? You mean like this? $ cat skiptest.py import unittest import sys def hide_if(condition): def g(f): return None if condition else f return g class T(unittest.TestCase): @hide_if(sys.version_info[0] > 2) def test_two(self): pass @hide_if(sys.version_info[0] < 3) def test_three(self): pass if __name__ == "__main__": unittest.main() $ python skiptest.py -v test_two (__main__.T) ... ok -- Ran 1 test in 0.000s OK $ python3 skiptest.py -v test_three (__main__.T) ... ok -- Ran 1 test in 0.000s OK $ > (other than using if-else inside the test --not really a bad > solution either ;-)? I don't understand that remark. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest skipping tests
On 01/08/13 14:22, Matthew Ngaha wrote: Thanks guys. i was following some examples and noticed it. I tried to use it in my program and the same thing happened. In this example, there are 6 tests, and only 4 run. http://bpaste.net/show/abLNTHU49w1j2M8Fey8X/ You're still just teasing us. You show us the code and say 4 methods run. But which 4? And how are you running the test? And what output do you get that tells you 4 ran? We need to know what is happening in more detail. While you are at it, which OS and Python version too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest skipping tests
Hi, On 1 August 2013 14:22, Matthew Ngaha wrote: > Thanks guys. i was following some examples and noticed it. I tried to > use it in my program and the same thing happened. In this example, > there are 6 tests, and only 4 run. > > http://bpaste.net/show/abLNTHU49w1j2M8Fey8X/ > The reason that 2 of the tests are apparently ignored, is because they are overwritten/redefined by the last 2 test methods in the class, which have the same name as the prior 2. You cannot have have multiple methods with the same name in the same class.Change the name of the last 2 methods in your class and your problem will go away. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest skipping tests
Hi, On 1 August 2013 13:11, Matthew Ngaha wrote: > im trying to do some unittesting and i've written 1 class with 4 test > methods and it skips 2 of these methods for no reason. If i comment > out the 2 it doesn't skip, it will now test the 2 it previously > skipped. Is this the default behaviour to only test 2 methods in a > class? No. (That would be silly, nay, crazy even.) > Anyone have any ideas how i can solve this problem? Alan's answer is the first port of call. You really need to give us more to work with, otherwise we're just guessing, and if we have to guess it makes our lives and your life more difficult than it needs to be. That said, what you describe makes me suspect indentation problems of some sort. It sounds almost as if the latter test methods are somehow considered to be inside the former test code, such that they're not "seen" by the testing framework's test discovery process. And, when you then comment out the prior 2 methods, the latter 2 become "visible" due to not being in the former's enclosing scope. Or something like that. But, that's just a guess, and may be way off base... Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest skipping tests
On 01/08/13 13:11, Matthew Ngaha wrote: im trying to do some unittesting and i've written 1 class with 4 test methods and it skips 2 of these methods for no reason. If i comment out the 2 it doesn't skip, it will now test the 2 it previously skipped. Is this the default behaviour I'm pretty sure its not the default but it might help if you posted the code and a cut n' paste of your test session. That way we can see what framework you use, how you use it and what actually happens. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest + tkinter
"Wayne Werner" wrote I'm trying my hand at test driven development via the unittest module. Since my program is using Tkinter, my thought is that I need to create the main window. The only problem is that when I launch the main loop, further lines of code aren't executed. Thats a feature of event driven programs. All the action takes place inside the event loop. I don't know how you drive a GUI with unittest though so can't help solve your problem. But the behaviour is normal for any GUI. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On Tue, 28 Sep 2010 08:07:30 am Modulok wrote: > On 9/27/10, Steven D'Aprano wrote: > > On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: > >> List, > >> > >> When using the unittest module, tests are run in alphanumeric > >> order. What's the suggested way of specifying a test order? > > > > There isn't one. It shouldn't matter what order the tests run, no > > test should *rely* on another test. > > > > (Although of course, if one test fails, any tests which assume the > > missing functionality will also fail.) > > In an ideal world, I agree. This is possible for pure functional > programming where state is avoided. However, when dealing with object > oriented, imperative programming, state changes cannot be avoided. > Thus if a method requires an object be passed to it, I'd like to > verify that object is being constructed correctly by the object > factory, before verifying that the method which uses said object, is > correct. It is reasonable to write two tests: test_construction # verify object is constructed correctly test_method # verify object is used correctly But you shouldn't rely on the tests being *executed* in any specific order, just as you shouldn't rely on them being *written* in any specific order. You should be able to go back at any time and add an extra test: test_special_construction even though test_method already exists. Likewise because every test is independent, it doesn't matter whether test_construction executes before or after test_method, or even simultaneously! (An advanced testing infrastructure might execute each test in its own thread.) Tests can have their own setup and teardown code. You should not put the setup code to test_method in test_construction -- they should be independent. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On 27-Sep-10 15:07, Modulok wrote: In an ideal world, I agree. This is possible for pure functional programming where state is avoided. However, when dealing with object oriented, imperative programming, state changes cannot be avoided. Generally, a unit test should test a single aspect of a single unit of your program. This is used all the time in object oriented programming. You set up an object (or collection of them), set up an initial state, test the behavior, and tear it down again. The state should not affect the assumptions of any other unit test. Thus if a method requires an object be passed to it, I'd like to verify that object is being constructed correctly by the object factory, before verifying that the method which uses said object, is correct. No problem. The object's constructor will have a number of unit tests of its own to ensure objects are constructed correctly, and the method has unit tests for them which test various cases about their behavior, etc. I suggest picking up a good book or two about unit testing so you get off to the right foot about how this is usually done. I'm not sure you're seeing the complete point of this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On 9/27/10, Steven D'Aprano wrote: > On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: >> List, >> >> When using the unittest module, tests are run in alphanumeric order. >> What's the suggested way of specifying a test order? > > There isn't one. It shouldn't matter what order the tests run, no test > should *rely* on another test. > > (Although of course, if one test fails, any tests which assume the > missing functionality will also fail.) In an ideal world, I agree. This is possible for pure functional programming where state is avoided. However, when dealing with object oriented, imperative programming, state changes cannot be avoided. Thus if a method requires an object be passed to it, I'd like to verify that object is being constructed correctly by the object factory, before verifying that the method which uses said object, is correct. Or is there some other way of doing this? I'm new to unittesting. Thanks! -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
>> List, >> >> When using the unittest module, tests are run in alphanumeric order. >> What's the suggested way of specifying a test order? > > There isn't one. It shouldn't matter what order the tests run, no test > should *rely* on another test. > > (Although of course, if one test fails, any tests which assume the > missing functionality will also fail.) Steven is right that unittests should be independent. I did once, however, come across an option to order the tests. Scanning through the unittest docs, I found "sortTestMethodsUsing": "Function to be used to compare method names when sorting them in getTestCaseNames() and all the loadTestsFrom*() methods. The default value is the built-in cmp() function; the attribute can also be set to None to disable the sort." Perhaps that does what you want. But I would indeed not recommend it. Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: > List, > > When using the unittest module, tests are run in alphanumeric order. > What's the suggested way of specifying a test order? There isn't one. It shouldn't matter what order the tests run, no test should *rely* on another test. (Although of course, if one test fails, any tests which assume the missing functionality will also fail.) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest
On Thu, 4 Mar 2010 05:32:22 pm you wrote: > Steven D'Aprano wrote: > > On Thu, 4 Mar 2010 04:27:23 am C.T. Matsumoto wrote: > >> Hello, > >> > >> Can someone tell me the difference between unittests assertEqual > >> and assertEquals? > > > > assertEqual, assertEquals and failUnless are three spellings for > > the same thing. There is no difference. > > Thanks, > Okay, does anyone know why unittests have 3 ways to do the same > thing? They're not three different ways, they are three names for the same way. The unittest module is meant to be equivalent to Java's unit test library, so possibly it is because Java has three names for the same thing, and so Python's version tried to be as similar as possible. Or possibly because the author(s) of the unittest module couldn't agree on what name to give the functions. Or possibly it was deliberate, because the authors felt that sometimes you want a positive test "assert this is true" and sometimes you want a negative test "fail unless this is true". -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest
Steven D'Aprano wrote: On Thu, 4 Mar 2010 04:27:23 am C.T. Matsumoto wrote: Hello, Can someone tell me the difference between unittests assertEqual and assertEquals? assertEqual, assertEquals and failUnless are three spellings for the same thing. There is no difference. Thanks, Okay, does anyone know why unittests have 3 ways to do the same thing? Thanks. T ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest
On Thu, 4 Mar 2010 04:27:23 am C.T. Matsumoto wrote: > Hello, > > Can someone tell me the difference between unittests assertEqual and > assertEquals? assertEqual, assertEquals and failUnless are three spellings for the same thing. There is no difference. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest
And also: Getting this in console when trying to generate report via HTMLTestRunner (it displayed text correctly when tried simple unittest.main) pass output_list['pt1.1'] = '!!! True\nÐ"омен \'foobar\' занÑÑ. РекомендованнÑе ÑвободнÑе доменÑ: ffoobar foobar.foobar foofoo fofo\n[]\n'; On Thu, Jul 17, 2008 at 10:01 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > beryl:~ oleg$ env > MANPATH=/usr/share/man:/usr/local/share/man:/usr/X11/man > TERM_PROGRAM=Apple_Terminal > TERM=xterm-color > SHELL=/bin/bash > TMPDIR=/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/ > Apple_PubSub_Socket_Render=/tmp/launch-UNXiC6/Render > TERM_PROGRAM_VERSION=237 > USER=oleg > COMMAND_MODE=unix2003 > SSH_AUTH_SOCK=/tmp/launch-hfpsIl/Listeners > __CF_USER_TEXT_ENCODING=0x1F6:0:0 > PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > PWD=/Users/oleg > LANG=ru_RU.UTF-8 > SHLVL=1 > HOME=/Users/oleg > PYTHONPATH=:/Users/oleg/Documents/wishes_Test > LOGNAME=oleg > DISPLAY=/tmp/launch-1kgALC/:0 > SECURITYSESSIONID=a206d0 > > > > On Thu, Jul 17, 2008 at 9:58 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > >> See previous message (sent it few seconds ago) >> >> >> On Thu, Jul 17, 2008 at 9:55 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL >> PROTECTED]>> >> wrote: >> >>> OK, your console is set to 'ascii' ('cp437' was my example and is the >>> Windows console encoding). 'ascii' won't be able to display Russian. >>> It shouldn't have displayed the "ИзвениÑ" characters either. >>> Are you still running on the same terminal that display those >>> characters? Can you change your terminals encoding preference via an >>> environment variable? >>> -- >>> Mark >>> >>> "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message >>> news:[EMAIL PROTECTED] >>> >>> And in case: >>> # coding: utf-8 >>> >>> import traceback >>> try: >>> raise Exception(u'Зрегиться') >>> except Exception,e: >>> print traceback.format_exc().decode('utf-8').encode('cp437', >>> 'replace') >>> >>> >>> Getting >>> >>> beryl:~ oleg$ python ./wish/newaccount/reg.py >>> Traceback (most recent call last): >>> File "./wish/newaccount/reg.py", line 5, in >>> raise Exception(u'?') >>> Exception: >>> >>> >>> >>> My console settings: >>> >>> In [1]: import sys >>> >>> In [2]: sys.getdefaultencoding() >>> Out[2]: 'ascii' >>> >>> In [3]: sys.stdout.encoding >>> Out[3]: 'US-ASCII' >>> >>> >>> On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> >>> wrote: >>> OK the output: # coding: utf-8 > > import traceback > try: > raise Exception(u'Зрегиться') > except Exception,e: > print traceback.format_exc().decode('utf-8') > >>> Traceback (most recent call last): File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line 7, in print traceback.format_exc().decode('utf-8') UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL PROTECTED]>> wrote: > The Exception is output in the encoding of the source file. If the > terminal you are displaying the exception on is in a different encoding, > it > will be garbled. I'm not familiar with OS X's terminal. Try running > python > and printing sys.stdout.encoding. > > Alternatively, wrap your code in a try/except handler and translate the > exception yourself. > > # coding: utf-8 > import traceback > try: > raise Exception(u'Зарегистрироваться') > except Exception,e: > print traceback.format_exc().decode('utf-8') > > The last line translates the utf-8 traceback into Unicode. Printing > Unicode will encode the output with the terminal's decoding. If there are > characters it can't display, you'll still get an error, though. You can > be > more explicit however: > > print > traceback.format_exc().decode('utf-8').encode('cp437','replace') > > In this case you'll get ? whenever a character can't be represented in > the selected encoding. cp437, for example, can't display any russian > characters, so for me (on Windows) I just get all ???. When I > tried > it with a character string that could be displayed in cp437, it worked > fine: > > Traceback (most recent call last): > File "", line 1, in > File "t4.py", line 4, in > raise Exception('MàΓ£ΦΘΩδ') > Exception: MàΓ£ΦΘΩδ > > Another option is to redirect the output to a file and read the file > with an editor that can display utf-8 (such as Notepad on Windows). > > python testfile.py 2>error.txt # this redirects stderr to > a file. > > Hope that helps, > Mark > >
Re: [Tutor] Unittest
beryl:~ oleg$ env MANPATH=/usr/share/man:/usr/local/share/man:/usr/X11/man TERM_PROGRAM=Apple_Terminal TERM=xterm-color SHELL=/bin/bash TMPDIR=/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/ Apple_PubSub_Socket_Render=/tmp/launch-UNXiC6/Render TERM_PROGRAM_VERSION=237 USER=oleg COMMAND_MODE=unix2003 SSH_AUTH_SOCK=/tmp/launch-hfpsIl/Listeners __CF_USER_TEXT_ENCODING=0x1F6:0:0 PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin PWD=/Users/oleg LANG=ru_RU.UTF-8 SHLVL=1 HOME=/Users/oleg PYTHONPATH=:/Users/oleg/Documents/wishes_Test LOGNAME=oleg DISPLAY=/tmp/launch-1kgALC/:0 SECURITYSESSIONID=a206d0 On Thu, Jul 17, 2008 at 9:58 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > See previous message (sent it few seconds ago) > > > On Thu, Jul 17, 2008 at 9:55 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL > PROTECTED]>> > wrote: > >> OK, your console is set to 'ascii' ('cp437' was my example and is the >> Windows console encoding). 'ascii' won't be able to display Russian. >> It shouldn't have displayed the "ИзвениÑ" characters either. >> Are you still running on the same terminal that display those >> characters? Can you change your terminals encoding preference via an >> environment variable? >> -- >> Mark >> >> "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> >> And in case: >> # coding: utf-8 >> >> import traceback >> try: >> raise Exception(u'Зрегиться') >> except Exception,e: >> print traceback.format_exc().decode('utf-8').encode('cp437', >> 'replace') >> >> >> Getting >> >> beryl:~ oleg$ python ./wish/newaccount/reg.py >> Traceback (most recent call last): >> File "./wish/newaccount/reg.py", line 5, in >> raise Exception(u'?') >> Exception: >> >> >> >> My console settings: >> >> In [1]: import sys >> >> In [2]: sys.getdefaultencoding() >> Out[2]: 'ascii' >> >> In [3]: sys.stdout.encoding >> Out[3]: 'US-ASCII' >> >> >> On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> >> wrote: >> >>> OK >>> the output: >>> >>> # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8') >>> >>> >>> >>> Traceback (most recent call last): >>> File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", >>> line 7, in >>> print traceback.format_exc().decode('utf-8') >>> UnicodeEncodeError: 'ascii' codec can't encode characters in position >>> 148-156: ordinal not in range(128) >>> >>> >>> >>> >>> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL >>> PROTECTED]>> >>> wrote: >>> The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File "", line 1, in File "t4.py", line 4, in raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2>error.txt # this redirects stderr to a file. Hope that helps, Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > The code # -*- coding: utf-8 -*- #!/usr/bin/python """ This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message
Re: [Tutor] Unittest
You get the "D" characters when decoding Russian encoded in UTF-8 using Latin-1 instead. # coding: utf-8 x=u'Зарегистрироваться' print x.encode('utf-8').decode('latin-1') ÐаÑегиÑÑÑиÑоваÑÑÑÑ Check that your html encoding is declared correctly. -- Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Ok, seems it's my console setting. Tried console with koi8-r (from http://vak.ru/doku.php/macosx-russian), and it looks ok there. Mean the satndard output, but still getting "D" chars instead of russian when trying to convert it to html via HTMLTestRunner (see http://tungwaiyip.info/software/HTMLTestRunner.html) On Thu, Jul 17, 2008 at 9:33 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: And in case: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') Getting beryl:~ oleg$ python ./wish/newaccount/reg.py Traceback (most recent call last): File "./wish/newaccount/reg.py", line 5, in raise Exception(u'?') Exception: My console settings: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: OK the output: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8') >>> Traceback (most recent call last): File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line 7, in print traceback.format_exc().decode('utf-8') UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]> wrote: The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File "", line 1, in File "t4.py", line 4, in raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2>error.txt # this redirects stderr to a file. Hope that helps, Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python """ This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message """ from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = "foobar" self.email = self.name + "@meta.ua" self.verificationErrors = [] self.selenium = selenium("localhost", ,config.browser, config.link)
Re: [Tutor] Unittest
Ok, seems it's my console setting. Tried console with koi8-r (from http://vak.ru/doku.php/macosx-russian), and it looks ok there. Mean the satndard output, but still getting "D" chars instead of russian when trying to convert it to html via HTMLTestRunner (see http://tungwaiyip.info/software/HTMLTestRunner.html) On Thu, Jul 17, 2008 at 9:33 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > > And in case: > # coding: utf-8 > > import traceback > try: > raise Exception(u'Зрегиться') > except Exception,e: > print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') > > > Getting > > beryl:~ oleg$ python ./wish/newaccount/reg.py > Traceback (most recent call last): > File "./wish/newaccount/reg.py", line 5, in > raise Exception(u'?') > Exception: > > > > My console settings: > > In [1]: import sys > > In [2]: sys.getdefaultencoding() > Out[2]: 'ascii' > > In [3]: sys.stdout.encoding > Out[3]: 'US-ASCII' > > > On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > >> OK >> the output: >> >> # coding: utf-8 >>> >>> import traceback >>> try: >>> raise Exception(u'Зрегиться') >>> except Exception,e: >>> print traceback.format_exc().decode('utf-8') >>> >> >> >> >>> Traceback (most recent call last): >> File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", >> line 7, in >> print traceback.format_exc().decode('utf-8') >> UnicodeEncodeError: 'ascii' codec can't encode characters in position >> 148-156: ordinal not in range(128) >> >> >> >> >> On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL >> PROTECTED]>> >> wrote: >> >>> The Exception is output in the encoding of the source file. If the >>> terminal you are displaying the exception on is in a different encoding, it >>> will be garbled. I'm not familiar with OS X's terminal. Try running python >>> and printing sys.stdout.encoding. >>> >>> Alternatively, wrap your code in a try/except handler and translate the >>> exception yourself. >>> >>> # coding: utf-8 >>> import traceback >>> try: >>> raise Exception(u'Зарегистрироваться') >>> except Exception,e: >>> print traceback.format_exc().decode('utf-8') >>> >>> The last line translates the utf-8 traceback into Unicode. Printing >>> Unicode will encode the output with the terminal's decoding. If there are >>> characters it can't display, you'll still get an error, though. You can be >>> more explicit however: >>> >>> print >>> traceback.format_exc().decode('utf-8').encode('cp437','replace') >>> >>> In this case you'll get ? whenever a character can't be represented in >>> the selected encoding. cp437, for example, can't display any russian >>> characters, so for me (on Windows) I just get all ???. When I tried >>> it with a character string that could be displayed in cp437, it worked fine: >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> File "t4.py", line 4, in >>> raise Exception('MàΓ£ΦΘΩδ') >>> Exception: MàΓ£ΦΘΩδ >>> >>> Another option is to redirect the output to a file and read the file with >>> an editor that can display utf-8 (such as Notepad on Windows). >>> >>> python testfile.py 2>error.txt # this redirects stderr to a >>> file. >>> >>> Hope that helps, >>> Mark >>> >>> "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message >>> news:[EMAIL PROTECTED] >>> The code >>> >>> # -*- coding: utf-8 -*- >>> #!/usr/bin/python >>> >>> >>> """ >>> >>> This test case check how system works in the situation, when user tries >>> to use already >>> used username (domain) >>> >>> We are creating two accounts with such parameters: >>> 1. Sex = Femle >>> 2. Name1=Name2 = foobar%S >>> 3. Pass1 = Name >>> 4. Pass2 = Name >>> 5. Email address1 = Email address2 = [EMAIL PROTECTED] >>> >>> >>> In the test we use verification point - warning message about incorrect >>> input of domain name and the >>> sugestion message >>> >>> """ >>> >>> from selenium import selenium >>> import unittest, time, re >>> import HTMLTestRunner >>> import config >>> import Creating_account_basic >>> >>> >>> >>> >>> class Same_domain_name(unittest.TestCase): >>> >>> def setUp(self): >>> self.name = "foobar" >>> self.email = self.name + "@meta.ua" >>> self.verificationErrors = [] >>> self.selenium = selenium("localhost", ,config.browser, >>> config.link) >>> self.selenium.start() >>> >>> def test_create_account_to_check(self): >>> """Creating sample account for next test""" >>> sel = self.selenium >>> sel.open("/") >>> sel.click(u"link=Регистрация") >>> sel.wait_for_page_to_load("7") >>> sel.click("id_gender_1") >>> sel.type("id_first_name", self.name) >>> sel.type("id_last_name", self.name) >>> sel.type("id_email", self.email) >>> sel.type("id_username", self.name) >>> >>> #sel.wait_for_condition(sel.is
Re: [Tutor] Unittest
OK, your console is set to 'ascii' ('cp437' was my example and is the Windows console encoding). 'ascii' won't be able to display Russian. It shouldn't have displayed the "ИзвениÑ" characters either. Are you still running on the same terminal that display those characters? Can you change your terminals encoding preference via an environment variable? -- Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] And in case: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') Getting beryl:~ oleg$ python ./wish/newaccount/reg.py Traceback (most recent call last): File "./wish/newaccount/reg.py", line 5, in raise Exception(u'?') Exception: My console settings: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: OK the output: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8') >>> Traceback (most recent call last): File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line 7, in print traceback.format_exc().decode('utf-8') UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]> wrote: The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File "", line 1, in File "t4.py", line 4, in raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2>error.txt # this redirects stderr to a file. Hope that helps, Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python """ This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message """ from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = "foobar" self.email = self.name + "@meta.ua" self.verificationErrors = [] self.selenium = selenium("localhost", ,config.browser, config.link) self.selenium.start() def test_create_account_to_check(self): """Creating sample account for next test""" sel = self.selenium sel.open("/") sel.click(u"link=Регистрация") sel.wait_for_page_to_load("7") sel.click("id_gender_1") sel.type("id_first_name", self.name) sel.type("id_last_name", self.name) s
Re: [Tutor] Unittest
And in case: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') Getting beryl:~ oleg$ python ./wish/newaccount/reg.py Traceback (most recent call last): File "./wish/newaccount/reg.py", line 5, in raise Exception(u'?') Exception: My console settings: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > OK > the output: > > # coding: utf-8 >> >> import traceback >> try: >> raise Exception(u'Зрегиться') >> except Exception,e: >> print traceback.format_exc().decode('utf-8') >> > > > >>> Traceback (most recent call last): > File "/var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT", line > 7, in > print traceback.format_exc().decode('utf-8') > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 148-156: ordinal not in range(128) > > > > > On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen <[EMAIL PROTECTED]<[EMAIL > PROTECTED]>> > wrote: > >> The Exception is output in the encoding of the source file. If the >> terminal you are displaying the exception on is in a different encoding, it >> will be garbled. I'm not familiar with OS X's terminal. Try running python >> and printing sys.stdout.encoding. >> >> Alternatively, wrap your code in a try/except handler and translate the >> exception yourself. >> >> # coding: utf-8 >> import traceback >> try: >> raise Exception(u'Зарегистрироваться') >> except Exception,e: >> print traceback.format_exc().decode('utf-8') >> >> The last line translates the utf-8 traceback into Unicode. Printing >> Unicode will encode the output with the terminal's decoding. If there are >> characters it can't display, you'll still get an error, though. You can be >> more explicit however: >> >> print traceback.format_exc().decode('utf-8').encode('cp437','replace') >> >> In this case you'll get ? whenever a character can't be represented in the >> selected encoding. cp437, for example, can't display any russian >> characters, so for me (on Windows) I just get all ???. When I tried >> it with a character string that could be displayed in cp437, it worked fine: >> >> Traceback (most recent call last): >> File "", line 1, in >> File "t4.py", line 4, in >> raise Exception('MàΓ£ΦΘΩδ') >> Exception: MàΓ£ΦΘΩδ >> >> Another option is to redirect the output to a file and read the file with >> an editor that can display utf-8 (such as Notepad on Windows). >> >> python testfile.py 2>error.txt # this redirects stderr to a >> file. >> >> Hope that helps, >> Mark >> >> "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message >> news:[EMAIL PROTECTED] >> >>> The code >> >> # -*- coding: utf-8 -*- >> #!/usr/bin/python >> >> >> """ >> >> This test case check how system works in the situation, when user tries to >> use already >> used username (domain) >> >> We are creating two accounts with such parameters: >> 1. Sex = Femle >> 2. Name1=Name2 = foobar%S >> 3. Pass1 = Name >> 4. Pass2 = Name >> 5. Email address1 = Email address2 = [EMAIL PROTECTED] >> >> >> In the test we use verification point - warning message about incorrect >> input of domain name and the >> sugestion message >> >> """ >> >> from selenium import selenium >> import unittest, time, re >> import HTMLTestRunner >> import config >> import Creating_account_basic >> >> >> >> >> class Same_domain_name(unittest.TestCase): >> >> def setUp(self): >> self.name = "foobar" >> self.email = self.name + "@meta.ua" >> self.verificationErrors = [] >> self.selenium = selenium("localhost", ,config.browser, >> config.link) >> self.selenium.start() >> >> def test_create_account_to_check(self): >> """Creating sample account for next test""" >> sel = self.selenium >> sel.open("/") >> sel.click(u"link=Регистрация") >> sel.wait_for_page_to_load("7") >> sel.click("id_gender_1") >> sel.type("id_first_name", self.name) >> sel.type("id_last_name", self.name) >> sel.type("id_email", self.email) >> sel.type("id_username", self.name) >> >> #sel.wait_for_condition(sel.is_element_present("check_username_block"), >> 7) >> time.sleep(10) >> print "!!!", sel.is_element_present("check_username_block") >> sel.type("id_password", self.name) >> print sel.get_text("check_username_block").decode('cp-1252') >> sel.type("id_password2", self.name) >> sel.click(u"//[EMAIL PROTECTED]'Зарегистрироваться']") >> sel.wait_for_page_to_load("7") >> if config.debugMode is True: >> time.sleep(5) >> >> >> def tearDown(self): >> self.selenium.stop() >> prin
Re: [Tutor] Unittest
The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File "", line 1, in File "t4.py", line 4, in raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2>error.txt # this redirects stderr to a file. Hope that helps, Mark "Oleg Oltar" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python """ This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message """ from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = "foobar" self.email = self.name + "@meta.ua" self.verificationErrors = [] self.selenium = selenium("localhost", ,config.browser, config.link) self.selenium.start() def test_create_account_to_check(self): """Creating sample account for next test""" sel = self.selenium sel.open("/") sel.click(u"link=Регистрация") sel.wait_for_page_to_load("7") sel.click("id_gender_1") sel.type("id_first_name", self.name) sel.type("id_last_name", self.name) sel.type("id_email", self.email) sel.type("id_username", self.name) #sel.wait_for_condition(sel.is_element_present("check_username_block"), 7) time.sleep(10) print "!!!", sel.is_element_present("check_username_block") sel.type("id_password", self.name) print sel.get_text("check_username_block").decode('cp-1252') sel.type("id_password2", self.name) sel.click(u"//[EMAIL PROTECTED]'Зарегистрироваться']") sel.wait_for_page_to_load("7") if config.debugMode is True: time.sleep(5) def tearDown(self): self.selenium.stop() print self.verificationErrors self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() #HTMLTestRunner.main() On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: Seems need help there. Start getting Traceback (most recent call last): File "./newaccount/Same_domain_name.py", line 56, in test_create_account_to_check print sel.get_text("check_username_block") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) when trying to get the text of one of the elements. How to solve it? On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: OK, I just run the program from terminal. OS: OS X, IDLE = Emacs:). Yep used the string "# -*- coding: utf-8 -*-" to setup encoding On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <[EMAIL PROTECTED]> wrote: Another possibility - do you have a coding declaration in your source file, something like # -*- codin
Re: [Tutor] Unittest
> > The code # -*- coding: utf-8 -*- #!/usr/bin/python """ This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message """ from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = "foobar" self.email = self.name + "@meta.ua" self.verificationErrors = [] self.selenium = selenium("localhost", ,config.browser, config.link) self.selenium.start() def test_create_account_to_check(self): """Creating sample account for next test""" sel = self.selenium sel.open("/") sel.click(u"link=Регистрация") sel.wait_for_page_to_load("7") sel.click("id_gender_1") sel.type("id_first_name", self.name) sel.type("id_last_name", self.name) sel.type("id_email", self.email) sel.type("id_username", self.name) #sel.wait_for_condition(sel.is_element_present("check_username_block"), 7) time.sleep(10) print "!!!", sel.is_element_present("check_username_block") sel.type("id_password", self.name) print sel.get_text("check_username_block").decode('cp-1252') sel.type("id_password2", self.name) sel.click(u"//[EMAIL PROTECTED]'Зарегистрироваться']") sel.wait_for_page_to_load("7") if config.debugMode is True: time.sleep(5) def tearDown(self): self.selenium.stop() print self.verificationErrors self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() #HTMLTestRunner.main() On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > In [1]: import sys > > In [2]: sys.getdefaultencoding() > Out[2]: 'ascii' > > In [3]: sys.stdout.encoding > Out[3]: 'US-ASCII' > > > On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > >> Seems need help there. Start getting >> >> Traceback (most recent call last): >> File "./newaccount/Same_domain_name.py", line 56, in >> test_create_account_to_check >> print sel.get_text("check_username_block") >> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: >> ordinal not in range(128) >> >> >> when trying to get the text of one of the elements. >> >> How to solve it? >> >> >> On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <[EMAIL PROTECTED]> >> wrote: >> >>> OK, >>> >>> I just run the program from terminal. OS: OS X, IDLE = Emacs:). >>> >>> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding >>> >>> >>> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <[EMAIL PROTECTED]> wrote: >>> Another possibility - do you have a coding declaration in your source file, something like # -*- coding: -*- If so, does the coding declaration match the actual encoding of the file? Kent On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <[EMAIL PROTECTED]> wrote: >> Hi I am using unittest framework with selenium. >> >> When I tried this code (my verification point) >> >> self.assertEqual(True, sel.is_text_present(u"Извените пароли не >> совпадают"), "System didn't give a correct warning about the password >> misstype") >> >>> Where u"Извените пароли не совпадают" is russian = "Sorry passwords aren't >>> equal", and sel.is_text_present - searches text string on the page >> >> The output I get in case of failure was: >> >> >> Traceback (most recent call last): >> >> File "./newaccount/Password_matching.py", line 50, in >> test_passwordMatching >> self.assertEqual(True, sel.is_text_present(u"Извените >> пароли не Ñ Ð¾Ð²Ð¿Ð°Ð´Ð°ÑŽÑ‚"), "System didn't give a correct >> warning about the password misstype") >> >> AssertionError: System didn't give a correct warning about the password >> misstype >> >> Is there any way to get normal russian text instead of these strange D chars >> "Изве" > > I don't have the solution but maybe I can give you a useful clue. The > D characters are most likely the utf-8 encoding of the Russian text, > when displayed as if it is latin-1. So something in the system is > converting the text to utf-8 and your console probably has latin-1 or > cp1252 encoding. > > Some details might help - how are you running the pr
Re: [Tutor] Unittest
In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > Seems need help there. Start getting > > Traceback (most recent call last): > File "./newaccount/Same_domain_name.py", line 56, in > test_create_account_to_check > print sel.get_text("check_username_block") > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: > ordinal not in range(128) > > > when trying to get the text of one of the elements. > > How to solve it? > > > On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > >> OK, >> >> I just run the program from terminal. OS: OS X, IDLE = Emacs:). >> >> Yep used the string "# -*- coding: utf-8 -*-" to setup encoding >> >> >> On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <[EMAIL PROTECTED]> wrote: >> >>> Another possibility - do you have a coding declaration in your source >>> file, something like >>> # -*- coding: -*- >>> >>> If so, does the coding declaration match the actual encoding of the file? >>> >>> Kent >>> >>> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: >>> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <[EMAIL PROTECTED]> >>> wrote: >>> >> Hi I am using unittest framework with selenium. >>> >> >>> >> When I tried this code (my verification point) >>> >> >>> >> self.assertEqual(True, sel.is_text_present(u"Извените пароли >>> не >>> >> совпадают"), "System didn't give a correct warning about the password >>> >> misstype") >>> >> >>> >>> Where u"Извените пароли не совпадают" is russian = "Sorry passwords >>> aren't >>> >>> equal", and sel.is_text_present - searches text string on the page >>> >> >>> >> The output I get in case of failure was: >>> >> >>> >> >>> >> Traceback (most recent call last): >>> >> >>> >> File "./newaccount/Password_matching.py", line 50, in >>> >> test_passwordMatching >>> >> self.assertEqual(True, sel.is_text_present(u"Извените >>> >> пароли не Ñ Ð¾Ð²Ð¿Ð°Ð´Ð°ÑŽÑ‚"), "System didn't give a correct >>> >> warning about the password misstype") >>> >> >>> >> AssertionError: System didn't give a correct warning about the >>> password >>> >> misstype >>> >> >>> >> Is there any way to get normal russian text instead of these strange D >>> chars >>> >> "Изве" >>> > >>> > I don't have the solution but maybe I can give you a useful clue. The >>> > D characters are most likely the utf-8 encoding of the Russian text, >>> > when displayed as if it is latin-1. So something in the system is >>> > converting the text to utf-8 and your console probably has latin-1 or >>> > cp1252 encoding. >>> > >>> > Some details might help - how are you running the program - console, >>> > IDLE...? What OS? What are the values of sys.getdefaultencoding() and >>> > sys.stdout.encoding? >>> > >>> > Kent >>> > >>> >> >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest
Seems need help there. Start getting Traceback (most recent call last): File "./newaccount/Same_domain_name.py", line 56, in test_create_account_to_check print sel.get_text("check_username_block") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) when trying to get the text of one of the elements. How to solve it? On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > OK, > > I just run the program from terminal. OS: OS X, IDLE = Emacs:). > > Yep used the string "# -*- coding: utf-8 -*-" to setup encoding > > > On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson <[EMAIL PROTECTED]> wrote: > >> Another possibility - do you have a coding declaration in your source >> file, something like >> # -*- coding: -*- >> >> If so, does the coding declaration match the actual encoding of the file? >> >> Kent >> >> On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: >> > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <[EMAIL PROTECTED]> >> wrote: >> >> Hi I am using unittest framework with selenium. >> >> >> >> When I tried this code (my verification point) >> >> >> >> self.assertEqual(True, sel.is_text_present(u"Извените пароли не >> >> совпадают"), "System didn't give a correct warning about the password >> >> misstype") >> >> >> >>> Where u"Извените пароли не совпадают" is russian = "Sorry passwords >> aren't >> >>> equal", and sel.is_text_present - searches text string on the page >> >> >> >> The output I get in case of failure was: >> >> >> >> >> >> Traceback (most recent call last): >> >> >> >> File "./newaccount/Password_matching.py", line 50, in >> >> test_passwordMatching >> >> self.assertEqual(True, sel.is_text_present(u"Извените >> >> пароли не Ñ Ð¾Ð²Ð¿Ð°Ð´Ð°ÑŽÑ‚"), "System didn't give a correct >> >> warning about the password misstype") >> >> >> >> AssertionError: System didn't give a correct warning about the password >> >> misstype >> >> >> >> Is there any way to get normal russian text instead of these strange D >> chars >> >> "Изве" >> > >> > I don't have the solution but maybe I can give you a useful clue. The >> > D characters are most likely the utf-8 encoding of the Russian text, >> > when displayed as if it is latin-1. So something in the system is >> > converting the text to utf-8 and your console probably has latin-1 or >> > cp1252 encoding. >> > >> > Some details might help - how are you running the program - console, >> > IDLE...? What OS? What are the values of sys.getdefaultencoding() and >> > sys.stdout.encoding? >> > >> > Kent >> > >> > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest
Another possibility - do you have a coding declaration in your source file, something like # -*- coding: -*- If so, does the coding declaration match the actual encoding of the file? Kent On Wed, Jul 16, 2008 at 5:11 PM, Kent Johnson <[EMAIL PROTECTED]> wrote: > On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <[EMAIL PROTECTED]> wrote: >> Hi I am using unittest framework with selenium. >> >> When I tried this code (my verification point) >> >> self.assertEqual(True, sel.is_text_present(u"Извените пароли не >> совпадают"), "System didn't give a correct warning about the password >> misstype") >> >>> Where u"Извените пароли не совпадают" is russian = "Sorry passwords aren't >>> equal", and sel.is_text_present - searches text string on the page >> >> The output I get in case of failure was: >> >> >> Traceback (most recent call last): >> >> File "./newaccount/Password_matching.py", line 50, in >> test_passwordMatching >> self.assertEqual(True, sel.is_text_present(u"Извените >> пароли не Ñ Ð¾Ð²Ð¿Ð°Ð´Ð°ÑŽÑ‚"), "System didn't give a correct >> warning about the password misstype") >> >> AssertionError: System didn't give a correct warning about the password >> misstype >> >> Is there any way to get normal russian text instead of these strange D chars >> "Изве" > > I don't have the solution but maybe I can give you a useful clue. The > D characters are most likely the utf-8 encoding of the Russian text, > when displayed as if it is latin-1. So something in the system is > converting the text to utf-8 and your console probably has latin-1 or > cp1252 encoding. > > Some details might help - how are you running the program - console, > IDLE...? What OS? What are the values of sys.getdefaultencoding() and > sys.stdout.encoding? > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest
On Wed, Jul 16, 2008 at 2:40 PM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > Hi I am using unittest framework with selenium. > > When I tried this code (my verification point) > > self.assertEqual(True, sel.is_text_present(u"Извените пароли не > совпадают"), "System didn't give a correct warning about the password > misstype") > >> Where u"Извените пароли не совпадают" is russian = "Sorry passwords aren't >> equal", and sel.is_text_present - searches text string on the page > > The output I get in case of failure was: > > > Traceback (most recent call last): > > File "./newaccount/Password_matching.py", line 50, in > test_passwordMatching > self.assertEqual(True, sel.is_text_present(u"Извените > пароли не Ñ Ð¾Ð²Ð¿Ð°Ð´Ð°ÑŽÑ‚"), "System didn't give a correct > warning about the password misstype") > > AssertionError: System didn't give a correct warning about the password > misstype > > Is there any way to get normal russian text instead of these strange D chars > "Изве" I don't have the solution but maybe I can give you a useful clue. The D characters are most likely the utf-8 encoding of the Russian text, when displayed as if it is latin-1. So something in the system is converting the text to utf-8 and your console probably has latin-1 or cp1252 encoding. Some details might help - how are you running the program - console, IDLE...? What OS? What are the values of sys.getdefaultencoding() and sys.stdout.encoding? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest. Run test case independently
On Wed, Jul 16, 2008 at 2:58 AM, Oleg Oltar <[EMAIL PROTECTED]> wrote: > Is that possible to run test cases independently (without unittest.main) and > how to do it > > E.g. I tried it this way: > > import random > import unittest > > class TestSequenceFunctions(unittest.TestCase): > > def setUp(self): > self.seq = range(10) > > def testchoice(self): > element = random.choice(self.seq) > self.assert_(element in self.seq) > if __name__ == '__main__': > a = TestSequenceFunctions().testchoice().run() Try this: unittest.main(defaulTest='TestSequenceFunctions.testchoice') You can run a single test from the command line using nose: http://somethingaboutorange.com/mrl/projects/nose/#usage ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest traceback
Oleg Oltar wrote: > Hi! > > I am trying to use unittest in python first time. But have a strange > traceback each time I run my sample tests. How are you running the test? My guess is that you are running it in an IDE or something that shows the normal system exit exception. Calling sys.exit() raises the SystemExit exception with a result code. Normally this is not shown by the runner. In Python False == 0 so your program is exiting normally with a code of 0 (no error). It is probably the program runner that is showing the traceback. Try running the program from the command line. Kent > Can you please explain why I have it. No info about it in the doc. > e.g. the code is > > import unittest > import squaren > > class TestCases(unittest.TestCase): > def setUp(self): > pass > > def testsmall(self): > self.assertEqual(True, True) > > > > if __name__ == '__main__': > unittest.main() > > And the traceback is > > -- > Ran 1 test in 0.000s > > OK > Traceback (most recent call last): > File "/tmp/py359hJx", line 14, in > unittest.main() > File "/opt/local/lib/python2.5/unittest.py", line 768, in __init__ > self.runTests() > File "/opt/local/lib/python2.5/unittest.py", line 806, in runTests > sys.exit(not result.wasSuccessful()) > SystemExit: False ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest not running all test cases
Kent: > -Original Message- > From: Kent Johnson [mailto:[EMAIL PROTECTED] > Sent: Friday, April 07, 2006 3:59 PM > To: Carroll, Barry > Subject: Re: [Tutor] Unittest not running all test cases > > Carroll, Barry wrote: > > Kent: > > > > I just rechecked my class names, and there are no duplicates. I was > > careful to preface all of the classes in testsymc39 with 'C39...', and > > used 'S25...' in testsym25. Likewise, the classes in each module have > > names that describe the type of data being tested, so names are unique > > within each module as well. > > > > Is there a maximum length for class names? Some of my class names are > > pretty long, and only differ in the last few characters. I'd be > > surprised if that were the case in Python, but I'm short on other ideas. > > I don't know of any limits on class names. They are just strings in > dictionaries after all. > > Try running your tests in verbose mode, you should at least be able to > figure out which ones aren't running. Try > > unittest.main(argv=['', '-v']) > > Kent > I tried your suggestion. Lo and behold, all the test cases ran! So I tried the terse mode again. All the test cases STILL ran! So the problem has vanished without a trace. Or a good reason. Having a problem just disappear like that bothers me almost more than the original problem. (It's also a little embarrassing.) =8^( Anyway, thanks for your help. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest not running all test cases
Kent: I just rechecked my class names, and there are no duplicates. I was careful to preface all of the classes in testsymc39 with 'C39...', and used 'S25...' in testsym25. Likewise, the classes in each module have names that describe the type of data being tested, so names are unique within each module as well. Is there a maximum length for class names? Some of my class names are pretty long, and only differ in the last few characters. I'd be surprised if that were the case in Python, but I'm short on other ideas. Thanks for your help. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -Original Message- > Date: Fri, 07 Apr 2006 15:42:15 -0400 > From: Kent Johnson <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Unittest not running all test cases > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > <> > > I don't think there is a limit like this. I wonder, do you have any name > collisions? For example if testsymc39 and testsym25 both contain class > TestSym then only the second one will run because it will shadow the > name from the first module. > > If this is the case you need a more sophisticated way of accumulating > tests. You might want to look into using nose or one of the other > test-discovery frameworks listed here: > http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools > > Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest not running all test cases
Carroll, Barry wrote: > Greetings: > > I'm not certain this is the right forum for this question. If not, please point me to the correct one. > > I am using the unittest module to test a package our team is writing. > I presently have three modules of test cases and a top level module to run the entire suite. The hierarchy looks like this: > testsymgen top level > testsymc39 61 test cases > testsym2544 test cases > testsymc93 0 test cases (so far) > > testsymgen is a very simple file. Here it is: > > import unittest > from testsymc39 import * > from testsym25 import * > from testsymc93 import * > > > if __name__=='__main__': > unittest.main( ) > > Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test cases are executed. Can anyone tell me why this should happen. Is there some sort of limit on the number of test cases that can be run in a batch? I don't think there is a limit like this. I wonder, do you have any name collisions? For example if testsymc39 and testsym25 both contain class TestSym then only the second one will run because it will shadow the name from the first module. If this is the case you need a more sophisticated way of accumulating tests. You might want to look into using nose or one of the other test-discovery frameworks listed here: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest and private methods
lemeia wrote: > kent wrote: >>Rereading your mail another possibility comes to mind. It sounds like >>extractTo() is a general-purpose function that is used for a specific >>purpose by the module you are testing. Why not extract extractTo to a >>utility module? Then you can test it as much as you like in the unit >>tests for the utility and you can reuse it in other code if the need >>arises. Almost all of my projects have 'util' packages containing >>collections of miscellaneous useful stuff. The utils have their own unit >>tests and get included as needed in other modules and projects. >> >> This makes sense to me and I hadn't thought of that in all honesty. >> I get so involved in object orientated design, I sometimes forget about the convenience of a few general functions to "help out". Would I lose my OO membership card though? No, not at all, in fact you jeopardize your OO membership if you use it where it is not needed ;) But seriously, one of the strengths of Python is that I can write OO code where appropriate, I can write procedural code when I don't need the extra power of classes, and I can write straight-line code when my needs are very simple, I can write in a functional style too. I can even mix the four styles in a single module if I want to. So go ahead and make a utility module, or a public helper function at global scope in the same module as your class. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest and private methods
> I'm really enjoying Python. I don't like the "sentence structure" quite > as much as Smalltalk (ie I like anObject actOn: a untilYouSee: b), Have you looked at Objective C? It uses Smalltalk style messaging, but in a C language framework. > I find it much faster to do things in Python even over Visual Basic. For sure, other than GUI design. > some reason I struggled with OO in C++ when I looked into it C++ was fairly easy up until v2 but then the ISO process added so many twisted features that it just became unusable IMHO. > and Java always seemed to be a big red stop sign for me You are not alone! Java ranks alongside COBOL as one of my least favourite languages and unfortunately I have to work with both! (Fortunately not too often) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest and private methods
kent wrote: > > I currently have a class where I have quite a few private methods. > > One > of these methods is a small general utility that extracts characters > from provided text up until it reaches a delimiter. Something like > extractTo(self, text, delimiter). > > > > It's not a relevant interface to the class, just a utility for the > class' public methods, which is why I've made it private. That seems to > be a logical decision to me. > > Yes, that is good reasoning. When you say it is private, do you mean the > name starts with two underscores? > Yes - it is __extractTo(self, text, delimiter) > > > However, the public methods within the class that call it currently > only do so to extract numeric events from the text. extractTo is a > little more generalised than that and so I decided that I would use > unittest to build test cases for the extractTo method and exercise it to > its fullest in case the class requires its extended functionality in the > future. > > > > You'll probably see what my problem is. I can't exercise this method > directly from an external test case as the method is not part of the > class' public interface. If I call a method in the interface that > currently utilises this private method I'm not testing the method as > fully as I would like. > > I'm not sure I understand this part. You mean the private methods have > capabilities that can't currently be exercised through the public > interface? That smells of "Speculative Generality" - writing code > because you think you might need it later. If that is the case the best > answer might be to rip it out and wait until you need it. > > > I like the term Speculative Generality - never heard that before. If the method was already extremely complicated I would agree that you should only alter when needed. However, this method is simpler in design and I don't see the harm in generalising in this particular case. Once I'd made the decision to generalise it I consequently saw several worthwhile refactoring possibilities in my class, which I shall probably exercise a little later. > Now I can build arbitrary interfaces into my class just for testing > this method but that sounds like a messy way to maintain a program. > Additionally, I could make this method public, but that also seems like > an unsatisfactory solution. > > > > The example isn't so important to my question, but I wanted to give > some context before asking.. > > > > Is there a way to specifically target and unit test private methods > > in > a class via unittest without testing them through the class' public > interface? > > Python's notion of privacy is pretty weak. I would have no problem with > a unit test that called single-underscore methods in the class under > test. Unit test purists object to this, saying a class should only be > tested through its public interface, but "practicality beats purity" in > my mind. > > Rereading your mail another possibility comes to mind. It sounds like > extractTo() is a general-purpose function that is used for a specific > purpose by the module you are testing. Why not extract extractTo to a > utility module? Then you can test it as much as you like in the unit > tests for the utility and you can reuse it in other code if the need > arises. Almost all of my projects have 'util' packages containing > collections of miscellaneous useful stuff. The utils have their own unit > tests and get included as needed in other modules and projects. > > This makes sense to me and I hadn't thought of that in all honesty. I get so > involved in object orientated design, I sometimes forget about the > convenience of a few general functions to "help out". Would I lose my OO > membership card though? I think I might stick to the public interface testing wherever possible and I have done so with other private methods in my class. This particular one just seemed to benefit from direct testing. I'm really enjoying Python. I don't like the "sentence structure" quite as much as Smalltalk (ie I like anObject actOn: a untilYouSee: b), but there's something quite friendly about its syntax all the same. I find it much faster to do things in Python even over Visual Basic. I really like developing using OO and so far, Python has been the easiest to adopt (besides Smalltalk perhaps). For some reason I struggled with OO in C++ when I looked into it and Java always seemed to be a big red stop sign for me (not sure why). Patrick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest and private methods
lemeia wrote: > I currently have a class where I have quite a few private methods. > One of these methods is a small general utility that extracts characters from provided text up until it reaches a delimiter. Something like extractTo(self, text, delimiter). > > It's not a relevant interface to the class, just a utility for the class' public methods, which is why I've made it private. That seems to be a logical decision to me. Yes, that is good reasoning. When you say it is private, do you mean the name starts with two underscores? > > However, the public methods within the class that call it currently only do so to extract numeric events from the text. extractTo is a little more generalised than that and so I decided that I would use unittest to build test cases for the extractTo method and exercise it to its fullest in case the class requires its extended functionality in the future. > > You'll probably see what my problem is. I can't exercise this method directly from an external test case as the method is not part of the class' public interface. If I call a method in the interface that currently utilises this private method I'm not testing the method as fully as I would like. I'm not sure I understand this part. You mean the private methods have capabilities that can't currently be exercised through the public interface? That smells of "Speculative Generality" - writing code because you think you might need it later. If that is the case the best answer might be to rip it out and wait until you need it. > > Now I can build arbitrary interfaces into my class just for testing this method but that sounds like a messy way to maintain a program. Additionally, I could make this method public, but that also seems like an unsatisfactory solution. > > The example isn't so important to my question, but I wanted to give some context before asking.. > > Is there a way to specifically target and unit test private methods > in a class via unittest without testing them through the class' public interface? Python's notion of privacy is pretty weak. I would have no problem with a unit test that called single-underscore methods in the class under test. Unit test purists object to this, saying a class should only be tested through its public interface, but "practicality beats purity" in my mind. Rereading your mail another possibility comes to mind. It sounds like extractTo() is a general-purpose function that is used for a specific purpose by the module you are testing. Why not extract extractTo to a utility module? Then you can test it as much as you like in the unit tests for the utility and you can reuse it in other code if the need arises. Almost all of my projects have 'util' packages containing collections of miscellaneous useful stuff. The utils have their own unit tests and get included as needed in other modules and projects. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest: looking for examples
Christian Meesters wrote: > - unittests for methods of classes getting all data from a file as a > classmethod Not sure what you mean by this, can you give a simple example? > - unittests for reading and saving files in a specific way (= sanity > tests for file handling) When I want to test a function that writes a file I usually have a collection of reference files and compare the actual results of running the function against the reference file. To test reading a file, again I have a reference file that is read, then I test the results of the read. Round-trip tests can be helpful too - read a file, write the data back out and compare with the original. > Point is that I want to test such methods directly, but also that I > cannot set up unittest in my case without getting some data from a file > (otherwise my testing module would get way too big). Not sure why that is a problem... HTH Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor