Parse Student Code
Check if student used _____ in their code.
Often you just want to make sure students successfully used a particular function/command/structure. The simplest way I have found to do this is just parse the student's code file and make sure what you are looking for is there.

Example 1 - Used ____ function ____ times

For example, maybe you want to make sure the student used the input function 4 times. We can parse the student's code file and count how many times "input(" is present in their code.
This test assumes the student's file name is example.py.
Grading Test:
1
import unittest
2
​
3
count = 0
4
​
5
class CodingRoomsUnitTests(unittest.TestCase):
6
​
7
def test_default_case(self):
8
global count
9
f = open("example.py", "r")
10
lines = f.readlines()
11
f.close()
12
13
for line in lines:
14
line = line.strip().split()
15
for words in line:
16
if words.find("input(") != -1:
17
count += 1
18
19
self.assertTrue(count == 4)
20
21
​
22
if __name__ == '__main__':
23
unittest.main()
Copied!
Notice that the test asserts that the count is equal to 4. Of course you can change this condition to anything you want. For example, if you want to make sure they have at least 1 input() you could use count >= 1.
Sample Solution:
example.py
1
name = input("What is your name?")
2
age = input("What is your age?")
3
hair = input("What color is your hair?")
4
place = input("Where do you live?")
Copied!

Example 2 - Used ____ thing ____ times

Sometimes if you are checking for a specific character/symbol it is better to use the .count() method so you do not miss an instance of the character/symbol.
This example checks that the student used the + addition at least 2 times.
Grading Test:
1
import unittest
2
​
3
count = 0
4
​
5
class CodingRoomsUnitTests(unittest.TestCase):
6
​
7
def test_default_case(self):
8
global count
9
f = open("example.py", "r")
10
lines = f.readlines()
11
f.close()
12
13
for line in lines:
14
line = line.strip().split()
15
for words in line:
16
if words.find("+") != -1:
17
count += words.count("+")
18
​
19
self.assertTrue(count >= 2)
20
​
21
if __name__ == '__main__':
22
unittest.main()
Copied!

Example 3 - Used ____ function with these exact arguments

Since spaces can be used between arguments, to check if a function is called with exact arguments, you want to check each line of the student's code and remove all spaces. Then find the function call you are looking for.
This example checks that there is at least 1 call of randint(501,1000) in the student's code.
Grading Test:
1
import unittest
2
​
3
count = 0
4
​
5
class CodingRoomsUnitTests(unittest.TestCase):
6
​
7
def test_default_case(self):
8
global count
9
f = open("example.py", "r")
10
lines = f.readlines()
11
f.close()
12
13
for line in lines:
14
line = line.strip().replace(" ", "")
15
if line.find("randint(501,1000)") != -1:
16
count += 1
17
18
self.assertTrue(count >= 1)
19
​
20
if __name__ == '__main__':
21
unittest.main()
Copied!
​
Last modified 2mo ago