Monday, 23 March 2015

Testing your code!

When you write any code, simple or complex, it is important to test it for many cases so you, as a computer scientist, have a sense of if you code works with best/worst cases. If you don't do this you will have many problems when releasing your code to the public or submitting your code as an assignment for a class.

Unittests in python:

  • Python has a great built in framework called Unitest, which is used to test cases for your code. 
    Implementing Unittest:
  • in order to implement a unittest, create a class for your tests (name it some ting that start with "Test". this class is a subclass of unitest.Testcase, so make sure you implement that.
  • the next two methods are optional to include in the class:
  • one is setup(self), this method is called to prepare the test case. it is called at the start the test. in this method you are to initialize any variables to be used in the test cases.
  • the other method is teardown(). called after each test, but only be called if the setup() succeeds. this method will raise an error rather than test failure. thus you will have an exact knowledge of where your code has errors. 
Implementing errors:
  • inorder to test your code, you must begin with writing a test method in your unittest class. Every test method must begin with the word "test" in order for the unitttest framework to test the code.
  • in the method you may test your code, and if error use this implementation:
  • assert <<condition>>, <<raise error string>>.
  • the above is an assert code, where first the condition is tested, if the condition is false the raise error string will execute and tell you the error.
this will only test your code to see if your code runs with specific inputs or not. if not then you can change your code to make a better code.

No comments:

Post a Comment