frontend: Introduce `test_frontend` to easily test model related code
[nit.git] / src / frontend / test_frontend.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Testing Model with `nitunit`
16 #
17 # This module introduce useful tools if you want to test Model with nitunit.
18 # It provides an abstract test suite `TestModel` that can load a `Model` from
19 # Nit files.
20 #
21 # See `TestModel::test_src`.
22 module test_frontend is test
23
24 import frontend
25 import frontend::parse_examples
26
27 # An abstract NitUnit that loads a `Model` from Nit files.
28 #
29 # To define a custom test using `TestModel`:
30 #
31 # ~~~
32 # class MyTest
33 # super TestModel
34 # test
35 #
36 # redef var test_src = "path/to/files"
37 #
38 # fun my_test is test do
39 # assert test_model.mmodules.length == 10
40 # end
41 # end
42 # ~~~
43 abstract class TestModel
44
45 # Path this unit test is executed in
46 var test_path: String = "NIT_TESTING_PATH".environ.dirname is lazy
47
48 # Test program to compile
49 #
50 # Change this source in your test suite.
51 # Default is `$NIT_DIR/tests/test_prog`.
52 #
53 # You can use either a file or a directory.
54 var test_src: String = "NIT_DIR".environ / "tests/test_prog" is lazy
55
56 # ToolContext used for the ModelBuilder
57 var test_context = new ToolContext
58
59 # Model used for tests
60 var test_model = new Model
61
62 # ModelBuilder used for tests
63 var test_builder = new ModelBuilder(test_model, test_context)
64
65 # Mainmodule used for tests
66 var test_main: MModule is noinit
67
68 # Build the test environment
69 fun build_test_env is before do
70 var mmodules = test_builder.parse_full([test_src])
71 test_builder.run_phases
72 test_context.run_global_phases(mmodules)
73 var mainmodule = test_context.make_main_module(mmodules)
74 test_main = mainmodule
75 end
76 end