testing code

Cameron Simpson cs at cskk.id.au
Fri Jul 6 00:01:52 EDT 2018

On 05Jul2018 19:56, Sharan Basappa <sharan.basappa at gmail.com> wrote:
>I have implemented my first program in python that uses ML to do some 
>classification task. The whole code is in a single file currently.
>It contains executable code as well as functions.

I presume when you write "executable code" you mean some kind of "main program" 
that just runs when you run the .py file?

>At the end of the program, I have series of calls that is used to test my code.
>Now, I would like to re-structure this to separate test code from the program.
>As I have not done this in Python, I am a bit lost.
>Please let me know if the following understanding of mine is correct.
>I need to put the program code in a separate file and organize every executable code in some form of function. If any code exists outside of function then it is not executable by importing.

This is not quite right. Because Python is a dynamic language, importing a file 
actually runs it. That is how the functions etc get defined.

So what you need to do is arrange that your "series of calls that is used to 
test my code" live in their own function, and that that function only gets run 
if the file is directly run.

Fortunately, this is a very common, almost universal, requirement and there is 
a standard idom for arranging it.

Support you have your code in the file "foo.py" (because I need a concrete 
filename for the example). It might look like this at present:

  def func1(...):

  def func2(...):

  x = func1(...)
  y = func2(...)
  print(x + y)

i.e. some function definitions and then you testing code.

Now, you can write another file "foo_tests.py" which starts like this:

  import foo
  ... run some tests of foo.func1, foo.func2 etc ...

The issue is that as written, foo.py will run your test calls during the 
import.  Restructure foo.py like this:

  def main():
      x = func1(...)
      y = func2(...)
      print(x + y)

  def func1(...):

  def func2(...):

  if __name__ == '__main__':

This is very standard. When you run a python file directly the built in  
__name__ variable contains the string "__main__". This tells you that you're 
running it as a "main program" i.e. directly.

If you import the file instead, as from your planned testing file, the __name__ 
variable will contain the string "foo" because that is the name of the module.

So that "main" function and the "if" at the bottom is standard Python 
boilerplate code for what you're trying to do.

>Import this in my test program (file/module) and then initiate  calls present 
>in the program.
>If there is some simple example, it would help a lot.

Now you can do this part.

Cameron Simpson <cs at cskk.id.au>

More information about the Python-list mailing list