473,715 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating module skeleton from unit tests


Greetings, fellow Pythonistas!

I'm about to create three modules. As an avid TDD fan I'd like to create
typical 'use-cases' for each of these modules. One of them is rather large,
and I wondered if it would be easy enough to create a code skeleton out of
unit test module.

Consider the following, though contrived, unit test code snippet:

=============== =============== =============== =============== ==============

import player

class TestClass:

def setup_method(se lf, meth):

self.obj = player.Player(' Fred the Adventurer')

def test_name(self) :

assert self.obj.name == 'Fred the Adventurer'

def test_inventory( self):

# player always starts with a dagger
assert self.obj.invent ory == {'dagger': [(1, 4)]}

# dagger is an initial weapon
assert self.obj.weapon _type == 'dagger'

# add sword to player and wield it
self.obj.add_it em('sword', (1, 8))

# wield the first sword in the backbag
self.obj.wield( 'sword')

assert self.obj.weapon _type == 'sword'

assert self.obj.invent ory == {'dagger': [(1, 4)], 'sword': [(1, 8)] }

def test_level(self ):

cur_level = self.obj.level

self.obj.level_ up()

assert cur_level + 1 = self.obj.level

def test_hitpoints( self):

start_hp = 30
sword_damage = 6

assert self.obj.hitpoi nts == start_hp

self.obj.damage (sword_damage)

assert self.obj.hitpoi nts == start_hp - sword_damage

=============== =============== =============== =============== ==============

Now it would be nice if I could do

$ python test2skel.py test_player.py

$ cat player.py

class Player:

def __init__(self, str): # constructor was called with a string,
# so we create init with str arg

# self.weapon_typ e was compared to string and no parenthesis were
# used, so the best guess is it's an attribute

self.weapon_typ e = None

# ditto for inventory, name and hitpoints

self.inventory = None

self.name = None

self.hitpoints = None
def add_item(self, str, tpl):
# add_item() was called with a string arg and a tuple

pass

def damage(self, obj):
# damage() was called with an argument

def wield(self, obj):
# wield was called with an arg

def level_up(self):
# level_up() was called without args
Now I'm thinking of at least three possible ways to implement that, all of
which may not be very sensible, but what I could come up with:

1. Try to run the test case and capture exceptions. Trying to import player
and failing means there is no module player.py. The script could create a
file player.py. Running the tests again imply there's an attribute Player
which seems like a method call or class (both are 'called' in the same
way). Nothing is created, but an ambiguous state is set for Player: it's
either a class or module method. Later calls for Player instance remove the
ambiguity and then we know it's a class, and as such the class skeleton
is created. Proceeding this way a skeleton could probably be created by
catching Import/Attribute errors and so forth.

2. Parse the test cases module as Python code, and extract all possible
information therein. Probably the best-working method, but needs Python
parser and some serious semantic logic. Probably the most obvious but also
hardest(?) way to do it.

3. Parse the test case as a text file, and extract only necessary
information. Eg. creating needed module files is probably very easy: for
practical purposes, you could just grep "import <modlist>" and "from
<module> import <classes/method>" to find out what module files need to be
created. Hackish and not elegant but would probably work for custom
purposes well enough (especially if we restrict ourselves to only lines
starting with 'import module' statements in the test module). However,
eg. associating an instance method call with the class used in object
creation would be quite hard, if the parser is just a simple one.

4. Use a completely different approach, eg. create a module skeleton using a
custom markup (easily generated from many graphical design tools) and use
that for creating both the test skeleton and module itself. However, it
wouldn't be TDD because then you'd be designing the module the usual way

Also remember that the program wouldn't need to be very clever. A strict
coding standard can be assumed, and eg. the fact that all classes are in
CamelCase would help in deducing whether foo.Bar() is a method call or
Bar-class object instantiation (methods are always lower_case_with _underscore,
according to PEP 8 we try to follow).

What do you think? I know that probably the best way to go on is just do it
the old way (ie. code both the test and module by hand), or look for more
intelligent IDEs.

For what it's worth, I still use most recent XEmacs for coding because it is
just so handy in many areas - sometimes I miss Eclipse-like IDE and I have
even tried pydev for Eclipse (which is a good plugin, btw!), but to this day
I've went back to XEmacs every time because in the end I've always been
lacking something I couldn't find a decent substitute for.
Obligatory note: According to the XP folks, TDD is not as much about testing
as it is about design: "Test Driven *Development*" or maybe even "Test Driven
*Design*". The problem can be solved more easily if you design the module
skeleton first, then the tests and then the logic for the skeleton
- you would be creating tests before the code, but many people wouldn't regard
it as TDD then.

--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!

$_ = '45647661726420 4d616a616b61726 92c206120436872 69737469616e20' ; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60 281449,'es'),2, 4),"\n";
Jul 18 '05 #1
4 2757
Edvard Majakari schrieb:
Greetings, fellow Pythonistas!

I'm about to create three modules. As an avid TDD fan I'd like to create
typical 'use-cases' for each of these modules. One of them is rather large,
and I wondered if it would be easy enough to create a code skeleton out of
unit test module.
I think this is too difficult, because there are many ways to write
code (even skeletons) for a use case. An easier approach would
be to write the skeleton manually, embed the test cases in the doc
strings and generate the test code from the doc strings. If I
remember correctly IBM has published something to generate unit
tests from code. Python has a doctest module to support testing
derived from doc strings. This can be combined with unit tests.
The problem can be solved more easily if you design the module
skeleton first, then the tests and then the logic for the skeleton
- you would be creating tests before the code, but many people
wouldn't regard it as TDD then.


You shouldn't care if your approach works for you.

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0 BtcGx1c3IuZGU=\ n'.decode('base 64')
-------------------------------------------------------------------
Jul 18 '05 #2
I think that the best approach I saw to this was in the Eclipse java
ide... You can basically go on the declaration of

self.obj = player.Player(' Fred the Adventurer')

press Ctrl+1 and it adds a suggestion to create the class Player.

Then go to

assert self.obj.name == 'Fred the Adventurer'

press Ctrl+1 and it adds suggestion: Declare field name in class
Player... and so on for methods... (true, you still have to go and
press some Ctrl+1s, but that should be fairly easy, especially if you
had some hints on what is missing... Python has a very dynamic nature,
but most of it can still be done...

I think that most Python IDEs are still not in the same level, but some
day they might get there...
Being the maintaner of PyDev (http://pydev.sf.net), I think it will get
there someday, true, lots of work to make it happen, right now only few
things in Ctrl+1 are available like that (still, some already are)...
and that's the way things work... nothing's always perfect (but at least
they evolve).

Regards,

Fabio
Peter Maas wrote:
Edvard Majakari schrieb:
Greetings, fellow Pythonistas!

I'm about to create three modules. As an avid TDD fan I'd like to create
typical 'use-cases' for each of these modules. One of them is rather
large,
and I wondered if it would be easy enough to create a code skeleton
out of
unit test module.

I think this is too difficult, because there are many ways to write
code (even skeletons) for a use case. An easier approach would
be to write the skeleton manually, embed the test cases in the doc
strings and generate the test code from the doc strings. If I
remember correctly IBM has published something to generate unit
tests from code. Python has a doctest module to support testing
derived from doc strings. This can be combined with unit tests.
The problem can be solved more easily if you design the module

skeleton first, then the tests and then the logic for the skeleton
- you would be creating tests before the code, but many people

wouldn't regard it as TDD then.


You shouldn't care if your approach works for you.

--
Fabio Zadrozny
------------------------------------------------------
Software Developer
ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

Jul 18 '05 #3
Peter Maas <pe***@somewher e.com> writes:
I think this is too difficult, because there are many ways to write
code (even skeletons) for a use case. An easier approach would
be to write the skeleton manually, embed the test cases in the doc
strings and generate the test code from the doc strings. If I
remember correctly IBM has published something to generate unit
tests from code. Python has a doctest module to support testing
derived from doc strings. This can be combined with unit tests.
Yes - actually I channged my mind in somewhere in the article - I actually
don't want to create typical use-cases in the test bed, rather create a
skeleton which covers each method at least somehow (no code inside skeleton
would be needed).
> The problem can be solved more easily if you design the module
skeleton first, then the tests and then the logic for the skeleton
- you would be creating tests before the code, but many people
> wouldn't regard it as TDD then.

You shouldn't care if your approach works for you.


Yes, you are right. I didn't select my words very well - I just meant that it
wouldn't be TDD then. Of course it might work, but I'd like to to it the TDD
way for now.

But thanks for the tip, I could see what IBM has done and then forget about
doing it automatically :)

--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!

$_ = '45647661726420 4d616a616b61726 92c206120436872 69737469616e20' ; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60 281449,'es'),2, 4),"\n";
Jul 18 '05 #4
Fabio Zadrozny <fa****@esss.co m.br> writes:
I think that the best approach I saw to this was in the Eclipse java
ide... You can basically go on the declaration of

self.obj = player.Player(' Fred the Adventurer')

press Ctrl+1 and it adds a suggestion to create the class Player.

Then go to

assert self.obj.name == 'Fred the Adventurer'

press Ctrl+1 and it adds suggestion: Declare field name in class
Player... and so on for methods... (true, you still have to go and press
some Ctrl+1s, but that should be fairly easy, especially if you had some
hints on what is missing... Python has a very dynamic nature, but most of it
can still be done...
Yes, I know. Eclipse is an excellent Java IDE - I've already seen ''quick
assist'' at work and I envy those Eclipse users for having such a nice tool :)

PyDev for eclipse seems /very/ promising, though.
I think that most Python IDEs are still not in the same level, but some day
they might get there... Being the maintaner of PyDev (http://pydev.sf.net),
I think it will get there someday, true, lots of work to make it happen,
right now only few things in Ctrl+1 are available like that (still, some
already are)... and that's the way things work... nothing's always perfect
(but at least they evolve).


Thanks for the comments - and for your pydev plugin, too.

--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!

"Debugging is twice as hard as writing the code in the firstplace. Therefore,
if you write the code as cleverly as possible, you are, by definition,
not smart enough to debug it." -- Brian W. Kernighan
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2746
by: | last post by:
Hi! I'm looking for unit-testing tools for .NET. Somthing like Java has --> http://www.junit.org regards, gicio
72
5253
by: Jacob | last post by:
I have compiled a set og unit testing recommendations based on my own experience on the concept. Feedback and suggestions for improvements are appreciated: http://geosoft.no/development/unittesting.html Thanks.
10
3762
by: Ben Finney | last post by:
Howdy all, Question: I have Python modules named without '.py' as the extension, and I'd like to be able to import them. How can I do that? Background: On Unix, I write programs intended to be run as commands to a file with no extension. This allows other programs to use the command as an interface, and I can re-write the program in some other language
6
2077
by: Michael Bray | last post by:
I've just inherited a fairly large project with multiple classes. The developer also wrote a huge number of unit tests (using NUnit) to validate that the classes work correctly. However, I don't think that the class itself should include unit tests, especially since it has to reference nunit.framework in order to compile/work, and I don't want to have to distribute the nunit.framework.dll with this class. So I created a new project,...
10
1674
by: Tom Plunket | last post by:
I've got a bunch of code that runs under a bunch of unit tests. It'd be really handy if when testing I could supply replacement functionality to verify that the right things get called without those things actually getting called, since frequently those calls take a long time to execute and do things that, well, I don't really want to do. E.g. imagine you've got a routine which takes a filespec, generates a list of files, and copies...
5
6524
by: shuisheng | last post by:
Dear All, I was told that unit test is a powerful tool for progamming. If I am writing a GUI code, is it possible to still using unit test? I have a little experience in using unittest++. But I can not work out a way to use it to test GUI code. Thanks a lot!
6
3470
by: Silfheed | last post by:
Heyas So we have the following situation: we have a testee.py that we want to automatically test out and verifiy that it is worthy of being deployed. We want our tester.py to test the code for testee.py without changing the code for testee.py. testee.py has a module in it that we want to mock in some tests and in others use the real module. /foo.py: (real module) class bar:
6
1283
by: Joel Hedlund | last post by:
Hi! I write, use and reuse a lot of small python programs for variuos purposes in my work. These use a growing number of utility modules that I'm continuously developing and adding to as new functionality is needed. Sometimes I discover earlier design mistakes in these modules, and rather than keeping old garbage I often rewrite the parts that are unsatisfactory. This often breaks backwards compatibility, and since I don't feel like updating...
3
1622
by: =?ISO-8859-15?Q?Arne_Vajh=F8j?= | last post by:
Alain Boss wrote: Believe it or not, but I have actually seen getters and setters being wrong after too much copy paste (it was not C# but that does not really matter). As a consequence I am paranoid enough to even make unit tests for that type of class. Arne
0
8821
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9196
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9103
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5967
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4477
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.