CSC148 - Lab 1

The purpose of this lab will be to help familiarize yourself with the CDF environment, and get some practice writing tests, exceptions and working with stacks.

Part 1

Make a folder called ~/lab1, and save the two files stack.py and test_stack.py in it. Open them in Wing-101.
Run test_stack.py by clicking on the green triangle in Wing. This will run a small number of tests. In particular, nose.runmodule() will look through the module and run all functions that begin with "test", and report the results back to you.
Each of the tests consists of doing some operations with the stack, and then testing a series of conditions using assert statements. An assert statement looks as follows:

assert condition, "error message"

This tests the condition, and throws an AssertionError exception if the condition does not hold.
Currently, all the tests pass. Modify one of them so that it will fail, and observe the output. Fix it, then with your partner brainstorm some other ways of testing the stack. Write 4-5 more tests.

Part 2

Add a new test to test_stack.py which tries to call peek() on an empty stack. What happens?
This is not the result of a bug in the stack code; the peek() operation is not defined on an empty stack. It would be better this action resulted in a new, more specific type of exception were raised.
A new exception class StackError, nested within the Stack class (refered to as Stack.StackError) is defined. Identify any other operations you think would be undefined and modify the code in stack.py so that it raises a Stack.StackError exception with an appropriate error message.
Now, go back to test_stack.py, and add tests for each of these cases. Remember that in this situation, a test should pass if and only if the Stack.StackError exception was raised.
Your test should look something like this:
# Some code to initialize the stack.
try:
    # Call to some stack operation which could throw an exception.
except Stack.StackException, e:
    # This is what we expect to be called.  pass does nothing; it is here because Python will return an error if there is an empty block of code.
    pass
except Exception, e:
    # Some exception other than Stack.StackException was called.
else:
    # No exceptions were called.
    
To cause a test to fail at a particular line, you can assert False, "error message" or raise a new exception.

Part 3

In lecture, we went over the balanced parentheses problem.
Create a new file multibracket.py, and write a function balanced(expression) which takes a string composed of the characters "()[]{}" and tests whether s is properly balanced with respect to these different kinds of brackets (")" only closes a "(", "]" only closes a "[", etc.). Your solution should make use of exactly one stack. Additionally, write ~10 test cases to make sure your function works.
When you're done, show the work to your TA.