Wednesday, 5 March 2014

Unit Testing, and programming test cases

Here I am going to talk about a fairly different aspect of programming, namely unit testing. The idea is that once you write a program or a piece of code, you can write another program that gives arbitrary inputs to your program to test it against bugs and issues. In other words, it is like you make a bot that tests your program against bugs (Instead of you tesing them on your own). There are various methods to do this, and there are various packages (e.g., JUnit for Java) that enable you to test your program. Here I am going to talk about a very simple one.

If your operating system is Unix, you can use Unix pipes for unit testing (If you do not already know, in short words a pipe is a method to give the output of a file or script to the input of another script). Similarly if you have windows you can do the same with windows pipes. Here is a very simple example from one of my old facebook posts:

with Unix pipes you can write test cases for your program. For example:
"$ echo 34 | ./main"
gives the integer "34" to executable file "main" as an input ('|' is the pipe operator).

For example I have an executable pw.cpp which gives the output "unlocked" if a certain password is given as input once the program is run (password is 'hello' in this case). As follows:

//================ START ===========
#include <iostream>
#include <string>
using namespace std;

int main(){
string x;
cout << "Enter password: ";
cin >> x;

if (x == "hello")
cout << "unlocked\n";
cout << "Wrong\n";

return 0;
//============== END ============

But in case I have no access to the actual source code, it seemed impossible for a normal human to run the above program many times and try all passwords ...

However, the following Python script reads a set of English words from a dictionary file containing most common English words ('dict_MC.txt' in below) and gives them as input to the above program, until the desired password is found (and as you can see it makes use of Unix pipes to give inputs to the above program):

#========== START ==========
import os, sys, subprocess

words = [lines.strip() for lines in open("dict_MC.txt")]

for x in words:
f = os.popen('echo "' + str(x) + '" | ./pw')
#print "input given: " + x
if ( != "Enter password: Wrong\n"):
print "password is " + str(x)
#=========== END ================

Of course if the password were more complicated it would take up to hours to find it.

No comments:

Post a Comment