-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
150 lines (117 loc) · 4.36 KB
/
Copy pathtest.py
File metadata and controls
150 lines (117 loc) · 4.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from lexer import Tokenizer, TokenType, LexerError
def test_tokenizer():
test_cases = [
("2 + 3", "Basic math"),
("2 + 3 * 4", "Operator test"),
("12.5 / 2.0", "decimals"),
("(2+3)", "Parentheses"),
("(2+3) * 4", "Para with oper"),
("((1+2)*3)", "Nested parantheses"),
("x", "simple identi"),
("my_var", "Identifer con underscore"),
("count123", "identi w numbers"),
("_priv", "Identi start w underscore"), ("if", "if keyword"),
("else", "else keyword"),
("def", "def keyword"),
("while", "while keyword"),
('"hello"', "Simple string"),
("'world'", "single quote str"),
('"hello world"', "string w spaces"),
('"hello\\nworld"', "string con esc seq"),
("x = 5", "simple var"),
('name = "Alice"', "String Assignment"),
("result = 2 + 3", "String with escape Sequence"),
("if x > 0:","If statement start"),
("def func()","Func def start"),
("while count < 10:","While loop start"),
("(X+y)*2","Complex Expression"),
('message = "hello, " + name',"String concat"),
]
passed = 0
failed = 0
for i, (code, description) in enumerate(test_cases, 1):
print(f"\n Test {i}: {description}")
print(f" Input: {code}")
try:
tokenizer = Tokenizer(code)
tokens = tokenizer.tokenize()
token_display = []
for token in tokens:
if token.type != TokenType.EOF:
token_display.append(f"{token.type.name}:'{token.value}")
print(f" Tokens: [{", ".join(token_display)}]")
print(" PASSED!")
passed += 1
except LexerError as e:
print(f" FAILED: {e}")
failed += 1
except Exception as e:
print(f" UNEXPECTED ERROR: {e}")
print()
print(f"Results: {passed} passed, {failed} failed")
if failed == 0:
print("Everything passed!")
else:
print("Oh no. Error.")
return failed == 0
def test_error_cases():
print(" Testing Error Handling")
print("=" * 30)
error_cases = [
("2.5.3", "Invalid number with multiple decimals"),
('"unterminated string', "Unterminated string literal"),
("123abc", "Invalid identifier starting with number"),
("@#$", "Invalid characters"),
("2 + ", "Incomplete expression"),
]
error = 0
success = 0
for code, description in error_cases:
print(f"\n Error Test: {description}")
print(f" Input: {code}")
try:
tokenizer = Tokenizer(code)
tokens = tokenizer.tokenize()
print(" Expected error but got tokens:",
[f"{t.type.name}:'{t.value}'" for t in tokens if t.type != TokenType.EOF])
error += 1
except LexerError as e:
print(f" Correctly caught error: {e}")
success += 1
except Exception as e:
print(f" Unexpected error type: {e}")
error += 1
print()
print(f"Results: {success} passed, {error} failed")
def interactive_test():
print("Enter Code to tokenize (or 'quit' to exit): ")
print("-"*40)
while True:
try:
user_input = input(">>> ").strip()
if user_input.lower() in ["quit", "exit", "q"]:
print("Exited the test")
break
if not user_input:
continue
tokenizer = Tokenizer(user_input)
tokens = tokenizer.tokenize()
print("Tokens:")
for token in tokens:
if token.type != TokenType.EOF:
print(f" {token.type.name}: '{token.value}' (line {token.line}, col {token.column})")
except LexerError as e:
print(f"LEXER ERROR: {e}")
except KeyboardInterrupt:
print("Exited the test")
break
except Exception as e:
print(f" UNEXPECTED ERROR: {e}")
if __name__ == "__main__":
success = test_tokenizer()
test_error_cases()
print("\n" + "-"*50)
response = input("Want to start interactive testing? (y/n):").lower()
if response.startswith("y"):
interactive_test()
print("SUCCESS" if success else "Failed.")