1#!/usr/bin/env python 2# 3# Copyright (C) 2022 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import unittest 18 19from io import StringIO 20 21from ninja_writer import Writer 22from ninja_syntax import Variable, Rule, BuildAction 23 24 25class TestWriter(unittest.TestCase): 26 def test_simple_writer(self): 27 with StringIO() as f: 28 writer = Writer(f) 29 writer.add_variable(Variable(name="cflags", value="-Wall")) 30 writer.add_newline() 31 32 cc = Rule(name="cc") 33 cc.add_variable(name="command", value="gcc $cflags -c $in -o $out") 34 writer.add_rule(cc) 35 # Add the same rule twice. 36 ld = Rule(name="ld", variables=(("command", "ld $ldflags -o $out $in"),)) 37 writer.add_rule(ld) 38 ld2 = Rule("ld", (("command", "ld $ldflags -o $out $in"),)) 39 writer.add_rule(ld2) 40 writer.add_newline() 41 42 writer.add_phony("system", ("foo.o",)) 43 writer.add_phony("system", ["foo.o"]) 44 build_action = BuildAction(output="foo.o", 45 rule="cc", 46 inputs=["foo.c"]) 47 writer.add_build_action(build_action) 48 writer.write() 49 self.assertEqual( 50 '''cflags = -Wall 51 52rule cc 53 command = gcc $cflags -c $in -o $out 54rule ld 55 command = ld $ldflags -o $out $in 56 57build system: phony foo.o 58build foo.o: cc foo.c 59''', f.getvalue()) 60 61 def test_comment(self): 62 with StringIO() as f: 63 writer = Writer(f) 64 writer.add_comment("This is a comment in a ninja file") 65 writer.write() 66 self.assertEqual("# This is a comment in a ninja file\n", 67 f.getvalue()) 68 69 70if __name__ == "__main__": 71 unittest.main() 72