1# Copyright 2022 The Pigweed Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may not 4# use this file except in compliance with the License. You may obtain a copy of 5# the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations under 13# the License. 14"""Tests for the negative compilation test generator.""" 15 16from pathlib import Path 17import re 18import tempfile 19import unittest 20 21from pw_compilation_testing.generator import ( 22 Compiler, 23 Expectation, 24 ParseError, 25 TestCase, 26 enumerate_tests, 27) 28 29SOURCE = r''' 30#if PW_NC_TEST(FirstTest) 31PW_NC_EXPECT("abcdef"); 32 33SomeSourceCode(); 34 35#endif // PW_NC_TEST 36 37#if PW_NC_TEST(SecondTest) 38PW_NC_EXPECT("\"\"abc123" // Include " and other escapes in the string 39 "def'456\"" 40 // Goodbye 41 "ghi\n\t789" // ??? 42); // abc 43 44#endif // PW_NC_TEST 45''' 46 47ILLEGAL_COMMENT = ''' 48#if PW_NC_TEST(FirstTest) 49PW_NC_EXPECT("abcdef" /* illegal comment */); 50 51#endif // PW_NC_TEST 52''' 53 54UNTERMINATED_EXPECTATION = '#if PW_NC_TEST(FirstTest)\nPW_NC_EXPECT("abcdef"\n' 55 56 57def _write_to_temp_file(contents: str) -> Path: 58 file = tempfile.NamedTemporaryFile('w', delete=False) 59 file.write(contents) 60 file.close() 61 return Path(file.name) 62 63 64# pylint: disable=missing-function-docstring 65 66 67class ParserTest(unittest.TestCase): 68 """Tests parsing negative compilation tests from a file.""" 69 70 def test_successful(self) -> None: 71 try: 72 path = _write_to_temp_file(SOURCE) 73 74 self.assertEqual( 75 [ 76 TestCase( 77 'TestSuite', 78 'FirstTest', 79 (Expectation(Compiler.ANY, re.compile('abcdef'), 3),), 80 path, 81 2, 82 ), 83 TestCase( 84 'TestSuite', 85 'SecondTest', 86 ( 87 Expectation( 88 Compiler.ANY, 89 re.compile('""abc123def\'456"ghi\\n\\t789'), 90 10, 91 ), 92 ), 93 path, 94 9, 95 ), 96 ], 97 list(enumerate_tests('TestSuite', [path])), 98 ) 99 finally: 100 path.unlink() 101 102 def test_illegal_comment(self) -> None: 103 try: 104 path = _write_to_temp_file(ILLEGAL_COMMENT) 105 with self.assertRaises(ParseError): 106 list(enumerate_tests('TestSuite', [path])) 107 finally: 108 path.unlink() 109 110 def test_unterminated_expectation(self) -> None: 111 try: 112 path = _write_to_temp_file(UNTERMINATED_EXPECTATION) 113 with self.assertRaises(ParseError) as err: 114 list(enumerate_tests('TestSuite', [path])) 115 finally: 116 path.unlink() 117 118 self.assertIn('Unterminated', str(err.exception)) 119 120 121if __name__ == '__main__': 122 unittest.main() 123