1+ from unittest import TestCase
2+
3+ import code_tokenize as ctok
4+
5+ class PythonTokenizationTestCase (TestCase ):
6+
7+ def test_tokenize1 (self ):
8+ tokens = ctok .tokenize ("def my_func():\n bar()" , lang = "python" )
9+ expected = ["def" , "my_func" , "(" , ")" , ":" , "#INDENT#" , "bar" , "(" , ")" , "#NEWLINE#" , "#DEDENT#" ]
10+ self .assertEqual (expected , [str (t ) for t in tokens ])
11+
12+ def test_tokenize2 (self ):
13+ tokens = ctok .tokenize ("def my_func(x):\n x = x + 1\n return x" , lang = "python" )
14+ expected = ["def" , "my_func" , "(" , "x" , ")" , ":" , "#INDENT#" , "x" , "=" , "x" , "+" , "1" , "#NEWLINE#" , "return" , "x" , "#NEWLINE#" , "#DEDENT#" ]
15+ self .assertEqual (expected , [str (t ) for t in tokens ])
16+
17+ def test_error_handling (self ):
18+ self .assertRaises (SyntaxError , ctok .tokenize , "def my_func(x):\n x = x + 1 return x" , lang = "python" )
19+
20+ def test_error_handling2 (self ):
21+ tokens = ctok .tokenize ("def my_func(x):\n x = x + 1 return x" , lang = "python" , syntax_error = "ignore" )
22+ expected = ["def" , "my_func" , "(" , "x" , ")" , ":" , "x" , "=" , "x" , "+" , "1" , "#INDENT#" , "return" , "x" , "#NEWLINE#" , "#DEDENT#" ]
23+ self .assertEqual (expected , [str (t ) for t in tokens ])
24+
25+
26+
27+ class JavaTokenizationTestCase (TestCase ):
28+
29+ def test_tokenize1 (self ):
30+ tokens = ctok .tokenize ("public class Test {\n public void myFunc(){\n bar();\n }\n }" , lang = "java" )
31+ expected = ["public" , "class" , "Test" , "{" , "public" , "void" , "myFunc" , "(" , ")" , "{" , "bar" , "(" , ")" , ";" , "}" , "}" ]
32+ self .assertEqual (expected , [str (t ) for t in tokens ])
33+
34+ def test_tokenize2 (self ):
35+ tokens = ctok .tokenize ("public class Test {\n public int myFunc(int x){\n x = x + 1;\n return x;\n }\n }" , lang = "java" )
36+ expected = ["public" , "class" , "Test" , "{" , "public" , "int" , "myFunc" , "(" , "int" , "x" , ")" , "{" , "x" , "=" , "x" , "+" , "1" , ";" , "return" , "x" , ";" , "}" , "}" ]
37+ self .assertEqual (expected , [str (t ) for t in tokens ])
38+
39+ def test_error_handling (self ):
40+ self .assertRaises (SyntaxError , ctok .tokenize , "public int myFunc(int x){\n x = x + 1;\n return x;\n }" , lang = "java" )
41+
42+ def test_error_handling2 (self ):
43+ tokens = ctok .tokenize ("public int myFunc(int x){\n x = x + 1;\n return x;\n }" , lang = "java" , syntax_error = "ignore" )
44+ expected = ["public" , "int" , "myFunc" , "" , "(" , "int" , "x" , ")" , "{" , "x" , "=" , "x" , "+" , "1" , ";" , "return" , "x" , ";" , "}" ]
45+ self .assertEqual (expected , [str (t ) for t in tokens ])
0 commit comments