1 | # Unit Test Framework Package
|
---|
2 |
|
---|
3 | ## About
|
---|
4 |
|
---|
5 | This package provides unit test frameworks capable of building tests for multiple contexts including
|
---|
6 | the UEFI shell environment and host-based environments. It allows for unit test development to focus
|
---|
7 | on the tests and leave error logging, result formatting, context persistence, and test running to the framework.
|
---|
8 | The unit test framework works well for low level unit tests as well as system level tests and
|
---|
9 | fits easily in automation frameworks.
|
---|
10 |
|
---|
11 | ### Framework
|
---|
12 |
|
---|
13 | The first unit test framework is called **Framework** and is implemented as a set of EDK II libraries.
|
---|
14 | The Framework supports both host-based unit tests and target-based unit tests that share the same
|
---|
15 | source style, macros, and APIs. In some scenarios, the same unit test case sources can be built
|
---|
16 | for both host-based unit test execution and target-based unit test execution. Host-based unit tests
|
---|
17 | that require mocked interfaces can use the mocking infrastructure provided by
|
---|
18 | [cmocka](https://api.cmocka.org/) that is included in the UnitTestFrameworkPkg as a submodule.
|
---|
19 |
|
---|
20 | ### GoogleTest
|
---|
21 |
|
---|
22 | The second unit test framework supported by the UnitTestFrameworkPkg is
|
---|
23 | [GoogleTest](http://google.github.io/googletest/) and can be used to implement host-based unit tests.
|
---|
24 | [GoogleTest on GitHub](https://github.com/google/googletest) is included in the UnitTestFrameworkPkg
|
---|
25 | as a submodule. Use of GoogleTest for target-based unit tests of EDK II components is not supported.
|
---|
26 | Host-based unit tests that require mocked interfaces can use the mocking infrastructure included with
|
---|
27 | GoogleTest called [gMock](https://github.com/google/googletest/tree/main/googlemock). Note that the
|
---|
28 | gMock framework does not directly support mocking of free (C style) functions, so the FunctionMockLib
|
---|
29 | (containing a set of macros that wrap gMock's MOCK_METHOD macro) was created within the
|
---|
30 | UnitTestFrameworkPkg to enable this support. The details and usage of these macros in the
|
---|
31 | FunctionMockLib are described later.
|
---|
32 |
|
---|
33 | GoogleTest requires less overhead to register test suites and test cases compared to the Framework.
|
---|
34 | There are also a number of tools that layer on top of GoogleTest that improve developer productivity.
|
---|
35 | One example is the VS Code extension
|
---|
36 | [C++ TestMate](https://marketplace.visualstudio.com/items?itemName=matepek.vscode-catch2-test-adapter)
|
---|
37 | that may be used to implement, run, and debug unit tests implemented using GoogleTest.
|
---|
38 |
|
---|
39 | If a component can be tested with host-based unit tests, then GoogleTest is recommended. The MdePkg
|
---|
40 | contains a port of the BaseSafeIntLib unit tests in the GoogleTest style so the differences between
|
---|
41 | GoogleTest and Framework unit tests can be reviewed. The paths to the BaseSafeIntLib unit tests are:
|
---|
42 |
|
---|
43 | * `MdePkg/Test/UnitTest/Library/BaseSafeIntLib`
|
---|
44 | * `MdePkg/Test/GoogleTest/Library/BaseSafeIntLib`
|
---|
45 |
|
---|
46 | Furthermore, the SecurityPkg contains unit tests for the SecureBootVariableLib using mocks in both
|
---|
47 | the Framework/cmocka and GoogleTest/gMock style so the differences between cmocka and gMock can be
|
---|
48 | reviewed. The paths to the SecureBootVariableLib unit tests are:
|
---|
49 |
|
---|
50 | * `SecurityPkg/Library/SecureBootVariableLib/UnitTest`
|
---|
51 | * `SecurityPkg/Library/SecureBootVariableLib/GoogleTest`
|
---|
52 |
|
---|
53 | ## Framework and GoogleTest Feature Comparison
|
---|
54 |
|
---|
55 | | Feature | Framework | GoogleTest |
|
---|
56 | |:----------------------------|:---------:|:----------:|
|
---|
57 | | Host Based Unit Tests | YES | YES |
|
---|
58 | | Target Based Unit Tests | YES | NO |
|
---|
59 | | Unit Test Source Language | C | C++ |
|
---|
60 | | Register Test Suite | YES | Auto |
|
---|
61 | | Register Test Case | YES | Auto |
|
---|
62 | | Death/Expected Assert Tests | YES | YES |
|
---|
63 | | Setup/Teardown Hooks | YES | YES |
|
---|
64 | | Value-Parameterized Tests | NO | YES |
|
---|
65 | | Typed Tests | NO | YES |
|
---|
66 | | Type-Parameterized Tests | NO | YES |
|
---|
67 | | Timeout Support | NO | YES |
|
---|
68 | | Mocking Support | Cmocka | gMock |
|
---|
69 | | JUNIT XML Reports | YES | YES |
|
---|
70 | | Execute subset of tests | NO | YES |
|
---|
71 | | VS Code Extensions | NO | YES |
|
---|
72 |
|
---|
73 | ## Framework Libraries
|
---|
74 |
|
---|
75 | ### UnitTestLib
|
---|
76 |
|
---|
77 | The main "framework" library. The core of the framework is the Framework object, which can have any number
|
---|
78 | of test cases and test suites registered with it. The Framework object is also what drives test execution.
|
---|
79 |
|
---|
80 | The Framework also provides helper macros and functions for checking test conditions and
|
---|
81 | reporting errors. Status and error info will be logged into the test context. There are a number
|
---|
82 | of Assert macros that make the unit test code friendly to view and easy to understand.
|
---|
83 |
|
---|
84 | Finally, the Framework also supports logging strings during the test execution. This data is logged
|
---|
85 | to the test context and will be available in the test reporting phase. This should be used for
|
---|
86 | logging test details and helpful messages to resolve test failures.
|
---|
87 |
|
---|
88 | ### UnitTestPersistenceLib
|
---|
89 |
|
---|
90 | Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests
|
---|
91 | that require exiting the active process and then resuming state can be maintained. This is critical
|
---|
92 | in supporting a system reboot in the middle of a test run.
|
---|
93 |
|
---|
94 | ### UnitTestResultReportLib
|
---|
95 |
|
---|
96 | Library provides function to run at the end of a framework test run and handles formatting the report.
|
---|
97 | This is a common customization point and allows the unit test framework to fit its output reports into
|
---|
98 | other test infrastructure. In this package simple library instances have been supplied to output test
|
---|
99 | results to the console as plain text.
|
---|
100 |
|
---|
101 | ## Framework Samples
|
---|
102 |
|
---|
103 | There is a sample unit test provided as both an example of how to write a unit test and leverage
|
---|
104 | many of the features of the framework. This sample can be found in the `Test/UnitTest/Sample/SampleUnitTest`
|
---|
105 | directory.
|
---|
106 |
|
---|
107 | The sample is provided in PEI, SMM, DXE, and UEFI App flavors. It also has a flavor for the HOST_APPLICATION
|
---|
108 | build type, which can be run on a host system without needing a target.
|
---|
109 |
|
---|
110 | ## Framework Usage
|
---|
111 |
|
---|
112 | This section is built a lot like a "Getting Started". We'll go through some of the components that are needed
|
---|
113 | when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe
|
---|
114 | how to check for expected conditions in test cases and a bit of the logging characteristics.
|
---|
115 |
|
---|
116 | Most of these examples will refer to the `SampleUnitTestUefiShell` app found in this package.
|
---|
117 |
|
---|
118 | ### Framework Requirements - INF
|
---|
119 |
|
---|
120 | In our INF file, we'll need to bring in the `UnitTestLib` library. Conveniently, the interface
|
---|
121 | header for the `UnitTestLib` is located in `MdePkg`, so you shouldn't need to depend on any other
|
---|
122 | packages. As long as your DSC file knows where to find the lib implementation that you want to use,
|
---|
123 | you should be good to go.
|
---|
124 |
|
---|
125 | See this example in `SampleUnitTestUefiShell.inf`...
|
---|
126 |
|
---|
127 | ```
|
---|
128 | [Packages]
|
---|
129 | MdePkg/MdePkg.dec
|
---|
130 |
|
---|
131 | [LibraryClasses]
|
---|
132 | UefiApplicationEntryPoint
|
---|
133 | BaseLib
|
---|
134 | DebugLib
|
---|
135 | UnitTestLib
|
---|
136 | PrintLib
|
---|
137 | ```
|
---|
138 |
|
---|
139 | Also, if you want your test to automatically be picked up by the Test Runner plugin, you will need
|
---|
140 | to make sure that the module `BASE_NAME` contains the word `Test`...
|
---|
141 |
|
---|
142 | ```
|
---|
143 | [Defines]
|
---|
144 | BASE_NAME = SampleUnitTestUefiShell
|
---|
145 | ```
|
---|
146 |
|
---|
147 | ### Framework Requirements - DSC
|
---|
148 |
|
---|
149 | In our DSC file, we'll need to bring in the INF file that was just created into the `[Components]`
|
---|
150 | section so that the unit tests will be built.
|
---|
151 |
|
---|
152 | See this example in `UnitTestFrameworkPkg.dsc`...
|
---|
153 |
|
---|
154 | ```
|
---|
155 | [Components]
|
---|
156 | UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf
|
---|
157 | ```
|
---|
158 |
|
---|
159 | Also, based on the type of tests that are being created, the associated DSC include file from the
|
---|
160 | UnitTestFrameworkPkg for Host or Target based tests should also be included at the top of the DSC
|
---|
161 | file.
|
---|
162 |
|
---|
163 | ```
|
---|
164 | !include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc
|
---|
165 | ```
|
---|
166 |
|
---|
167 | Lastly, in the case that the test build has specific dependent libraries associated with it,
|
---|
168 | they should be added in the \<LibraryClasses\> sub-section for the INF file in the
|
---|
169 | `[Components]` section of the DSC file.
|
---|
170 |
|
---|
171 | See this example in `SecurityPkgHostTest.dsc`...
|
---|
172 |
|
---|
173 | ```
|
---|
174 | [Components]
|
---|
175 | SecurityPkg/Library/SecureBootVariableLib/UnitTest/SecureBootVariableLibUnitTest.inf {
|
---|
176 | <LibraryClasses>
|
---|
177 | SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf
|
---|
178 | UefiRuntimeServicesTableLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiRuntimeServicesTableLib.inf
|
---|
179 | PlatformPKProtectionLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockPlatformPKProtectionLib.inf
|
---|
180 | UefiLib|SecurityPkg/Library/SecureBootVariableLib/UnitTest/MockUefiLib.inf
|
---|
181 | }
|
---|
182 | ```
|
---|
183 |
|
---|
184 | ### Framework Requirements - Code
|
---|
185 |
|
---|
186 | Not to state the obvious, but let's make sure we have the following include before getting too far along...
|
---|
187 |
|
---|
188 | ```c
|
---|
189 | #include <Library/UnitTestLib.h>
|
---|
190 | ```
|
---|
191 |
|
---|
192 | Now that we've got that squared away, let's look at our 'Main()' routine (or DriverEntryPoint() or whatever).
|
---|
193 |
|
---|
194 | ### Framework Configuration
|
---|
195 |
|
---|
196 | Everything in the UnitTestFrameworkPkg framework is built around an object called -- conveniently -- the Framework.
|
---|
197 | This Framework object will contain all the information about our test, the test suites and test cases associated
|
---|
198 | with it, the current location within the test pass, and any results that have been recorded so far.
|
---|
199 |
|
---|
200 | To get started with a test, we must first create a Framework instance. The function for this is
|
---|
201 | `InitUnitTestFramework`. It takes in `CHAR8` strings for the long name, short name, and test version.
|
---|
202 | The long name and version strings are just for user presentation and relatively flexible. The short name
|
---|
203 | will be used to name any cache files and/or test results, so should be a name that makes sense in that context.
|
---|
204 | These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine.
|
---|
205 |
|
---|
206 | In the `SampleUnitTestUefiShell` app, the module name is used as the short name, so the initialization looks like this.
|
---|
207 |
|
---|
208 | ```c
|
---|
209 | DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION ));
|
---|
210 |
|
---|
211 | //
|
---|
212 | // Start setting up the test framework for running the tests.
|
---|
213 | //
|
---|
214 | Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION );
|
---|
215 | ```
|
---|
216 |
|
---|
217 | The `&Framework` returned here is the handle to the Framework. If it's successfully returned, we can start adding
|
---|
218 | test suites and test cases.
|
---|
219 |
|
---|
220 | Test suites exist purely to help organize test cases and to differentiate the results in reports. If you're writing
|
---|
221 | a small unit test, you can conceivably put all test cases into a single suite. However, if you end up with 20+ test
|
---|
222 | cases, it may be beneficial to organize them according to purpose. You _must_ have at least one test suite, even if
|
---|
223 | it's just a catch-all. The function to create a test suite is `CreateUnitTestSuite`. It takes in a handle to
|
---|
224 | the Framework object, a `CHAR8` string for the suite title and package name, and optional function pointers for
|
---|
225 | a setup function and a teardown function.
|
---|
226 |
|
---|
227 | The suite title is for user presentation. The package name is for xUnit type reporting and uses a '.'-separated
|
---|
228 | hierarchical format (see 'SampleUnitTestApp' for example). If provided, the setup and teardown functions will be
|
---|
229 | called once at the start of the suite (before _any_ tests have run) and once at the end of the suite (after _all_
|
---|
230 | tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are
|
---|
231 | `UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`.
|
---|
232 |
|
---|
233 | Looking at `SampleUnitTestUefiShell` app, you can see that the first test suite is created as below...
|
---|
234 |
|
---|
235 | ```c
|
---|
236 | //
|
---|
237 | // Populate the SimpleMathTests Unit Test Suite.
|
---|
238 | //
|
---|
239 | Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL );
|
---|
240 | ```
|
---|
241 |
|
---|
242 | This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and
|
---|
243 | will be used when adding test cases.
|
---|
244 |
|
---|
245 | Great! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test
|
---|
246 | to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle;
|
---|
247 | a `CHAR8` string for the description and class name; a function pointer for the test case itself; additional, optional
|
---|
248 | function pointers for prerequisite check and cleanup routines; and an optional pointer to a context structure.
|
---|
249 |
|
---|
250 | Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in
|
---|
251 | usage to the suite title and package name strings in the test suites. The former is for user presentation and the
|
---|
252 | latter is for xUnit parsing. The test case function pointer is what is executed as the "test" and the
|
---|
253 | prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining.
|
---|
254 |
|
---|
255 | The prerequisite check function has a prototype of `UNIT_TEST_PREREQUISITE` and -- if provided -- will be called
|
---|
256 | immediately before the test case. If this function returns any error, the test case will not be run and will be
|
---|
257 | recorded as `UNIT_TEST_ERROR_PREREQUISITE_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called
|
---|
258 | immediately after the test case to provide an opportunity to reset any global state that may have been changed in the
|
---|
259 | test case. In the event of a prerequisite failure, the cleanup function will also be skipped. If either of these
|
---|
260 | functions is not needed, pass `NULL`.
|
---|
261 |
|
---|
262 | The context pointer is entirely case-specific. It will be passed to the test case upon execution. One of the purposes
|
---|
263 | of the context pointer is to allow test case reuse with different input data. (Another use is for testing that wraps
|
---|
264 | around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context
|
---|
265 | pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`.
|
---|
266 |
|
---|
267 | In `SampleUnitTestUefiShell` app, the first test case is added using the code below...
|
---|
268 |
|
---|
269 | ```c
|
---|
270 | AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL );
|
---|
271 | ```
|
---|
272 |
|
---|
273 | This test case calls the function `OnePlusOneShouldEqualTwo` and has no prerequisite, cleanup, or context.
|
---|
274 |
|
---|
275 | Once all the suites and cases are added, it's time to run the Framework.
|
---|
276 |
|
---|
277 | ```c
|
---|
278 | //
|
---|
279 | // Execute the tests.
|
---|
280 | //
|
---|
281 | Status = RunAllTestSuites( Framework );
|
---|
282 | ```
|
---|
283 |
|
---|
284 | ### Framework - A Simple Test Case
|
---|
285 |
|
---|
286 | We'll take a look at the below test case from 'SampleUnitTestApp'...
|
---|
287 |
|
---|
288 | ```c
|
---|
289 | UNIT_TEST_STATUS
|
---|
290 | EFIAPI
|
---|
291 | OnePlusOneShouldEqualTwo (
|
---|
292 | IN UNIT_TEST_FRAMEWORK_HANDLE Framework,
|
---|
293 | IN UNIT_TEST_CONTEXT Context
|
---|
294 | )
|
---|
295 | {
|
---|
296 | UINTN A, B, C;
|
---|
297 |
|
---|
298 | A = 1;
|
---|
299 | B = 1;
|
---|
300 | C = A + B;
|
---|
301 |
|
---|
302 | UT_ASSERT_EQUAL(C, 2);
|
---|
303 | return UNIT_TEST_PASSED;
|
---|
304 | } // OnePlusOneShouldEqualTwo()
|
---|
305 | ```
|
---|
306 |
|
---|
307 | The prototype for this function matches the `UNIT_TEST_FUNCTION` prototype. It takes in a handle to the Framework
|
---|
308 | itself and the context pointer. The context pointer could be cast and interpreted as anything within this test case,
|
---|
309 | which is why it's important to configure contexts carefully. The test case returns a value of `UNIT_TEST_STATUS`, which
|
---|
310 | will be recorded in the Framework and reported at the end of all suites.
|
---|
311 |
|
---|
312 | In this test case, the `UT_ASSERT_EQUAL` assertion is being used to establish that the business logic has functioned
|
---|
313 | correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your
|
---|
314 | intended test criterium as possible, because the logging is specific to the macro and more specific macros have more
|
---|
315 | detailed logs. When in doubt, there are always `UT_ASSERT_TRUE` and `UT_ASSERT_FALSE`. Assertion macros that fail their
|
---|
316 | test criterium will immediately return from the test case with `UNIT_TEST_ERROR_TEST_FAILED` and log an error string.
|
---|
317 | _Note_ that this early return can have implications for memory leakage.
|
---|
318 |
|
---|
319 | At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`.
|
---|
320 |
|
---|
321 | ### Framework - More Complex Cases
|
---|
322 |
|
---|
323 | To write more advanced tests, first look at all the Assertion and Logging macros provided in the framework.
|
---|
324 |
|
---|
325 | Beyond that, if you're writing host-based tests and want to take a dependency on the UnitTestFrameworkPkg, you can
|
---|
326 | leverage the `cmocka.h` interface and write tests with all the features of the Cmocka framework.
|
---|
327 |
|
---|
328 | Documentation for Cmocka can be found here:
|
---|
329 | https://api.cmocka.org/
|
---|
330 |
|
---|
331 | ## GoogleTest Libraries
|
---|
332 |
|
---|
333 | ### GoogleTestLib
|
---|
334 |
|
---|
335 | GoogleTestLib is the core library used for GoogleTest in EDK II. This library is mainly a wrapper
|
---|
336 | around the GoogleTest and gMock header and source files. So all the standard
|
---|
337 | [GoogleTest](http://google.github.io/googletest/) and
|
---|
338 | [gMock](https://github.com/google/googletest/tree/main/googlemock) documentation for writing tests
|
---|
339 | and using mocks applies.
|
---|
340 |
|
---|
341 | Additionally, to support the use of some primitive types that are not directly supported by
|
---|
342 | GoogleTest and gMock (but are needed to allow gMock to be used in EDK II), some custom gMock
|
---|
343 | actions and matchers were added to GoogleTestLib. These customizations are briefly described in
|
---|
344 | the following tables.
|
---|
345 |
|
---|
346 | #### Custom Actions
|
---|
347 |
|
---|
348 | | Action Name | Similar gMock Generic Action | Usage |
|
---|
349 | |:--- |:--- |:--- |
|
---|
350 | | `SetArgBuffer()` | `SetArgPointee()` | Used to set a buffer output argument (such as UINT8*, VOID*, a structure pointer, etc.) with data in an expect call. Can be used in an `EXPECT_CALL()` |
|
---|
351 |
|
---|
352 | #### Custom Matchers
|
---|
353 |
|
---|
354 | | Matcher Name | Similar gMock Generic Matcher | Usage |
|
---|
355 | |:--- |:--- |:--- |
|
---|
356 | | `BufferEq()` | `Pointee(Eq())` | Used to compare two buffer pointer types (such as UINT8*, VOID*, a structure pointer, etc.). Can be used in an `EXPECT_CALL()`, `EXPECT_THAT()`, or anywhere else a matcher to compare two buffers is needed. |
|
---|
357 | | `Char16StrEq()` | `Pointee(Eq())` | Used to compare two CHAR16* strings. Can be used in an `EXPECT_CALL()`, `EXPECT_THAT()`, or anywhere else a matcher to compare two CHAR16* strings is needed. |
|
---|
358 |
|
---|
359 | ### FunctionMockLib
|
---|
360 |
|
---|
361 | FunctionMockLib is the library that allows gMock to be used with free (C style) functions. This
|
---|
362 | library contains a set of macros that wrap gMock's MOCK_METHOD macro to enable the standard gMock
|
---|
363 | capabilities to be used with free functions. The details of how this is implemented is outside the
|
---|
364 | scope of this document, but a brief description of each of the public macros in FunctionMockLib is
|
---|
365 | described below. A full example of how to use these macros to create a mock is described in a
|
---|
366 | later section.
|
---|
367 |
|
---|
368 | In total there are six public macros in FunctionMockLib. Four of the macros are related to creating
|
---|
369 | the mock functions, and the other two macros are related to creating an interface that is necessary
|
---|
370 | to contain the mock functions and connect them into the gMock framework.
|
---|
371 |
|
---|
372 | The macros used to create the interface are...
|
---|
373 | 1. `MOCK_INTERFACE_DECLARATION(MOCK)`
|
---|
374 | 2. `MOCK_INTERFACE_DEFINITION(MOCK)`
|
---|
375 |
|
---|
376 | These macros both take one argument which is the name of the interface for the mock. The
|
---|
377 | `MOCK_INTERFACE_DECLARATION` macro is used to declare the interface in the `.h` file and the
|
---|
378 | `MOCK_INTERFACE_DEFINITION` macro is used to define the interface in the `.cpp` file. For
|
---|
379 | example, to create a mock for the `UefiLib`, a `MockUefiLib.h` file would be created and the
|
---|
380 | below code would be added to it.
|
---|
381 |
|
---|
382 | ```cpp
|
---|
383 | struct MockUefiLib {
|
---|
384 | MOCK_INTERFACE_DECLARATION(MockUefiLib);
|
---|
385 | };
|
---|
386 | ```
|
---|
387 |
|
---|
388 | Additionally, the below code would be written into a `MockUefiLib.cpp` file.
|
---|
389 |
|
---|
390 | ```cpp
|
---|
391 | MOCK_INTERFACE_DEFINITION(MockUefiLib);
|
---|
392 | ```
|
---|
393 |
|
---|
394 | The macros used to create the mock functions are...
|
---|
395 | 1. `MOCK_FUNCTION_DECLARATION(RET_TYPE, FUNC, ARGS)`
|
---|
396 | 2. `MOCK_FUNCTION_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE)`
|
---|
397 | 3. `MOCK_FUNCTION_INTERNAL_DECLARATION(RET_TYPE, FUNC, ARGS)`
|
---|
398 | 4. `MOCK_FUNCTION_INTERNAL_DEFINITION(MOCK, FUNC, NUM_ARGS, CALL_TYPE)`
|
---|
399 |
|
---|
400 | You will notice that there are two sets of macros: one to mock external functions and
|
---|
401 | another to mock internal functions. Each set of macros has the exact same arguments, but
|
---|
402 | they are used for slightly different use cases. The details of these different use cases
|
---|
403 | is described in detail in a later section. For now, we will focus on the usage of the macro
|
---|
404 | arguments since that is common between them.
|
---|
405 |
|
---|
406 | The `MOCK_FUNCTION_DECLARATION` macro is used to declare the mock function in the `.h` file,
|
---|
407 | and it takes three arguments: return type, function name, and argument list. The
|
---|
408 | `MOCK_FUNCTION_DEFINITION` macro is used to define the mock function in the `.cpp` file,
|
---|
409 | and it takes four arguments: name of the interface for the mock, function name, number of
|
---|
410 | arguments the function takes, and calling convention type of the function. For example, to
|
---|
411 | continue with the `UefiLib` mock example above, the `GetVariable2` and `GetEfiGlobalVariable2`
|
---|
412 | functions are declared in `UefiLib.h` as shown below.
|
---|
413 |
|
---|
414 | ```cpp
|
---|
415 | EFI_STATUS
|
---|
416 | EFIAPI
|
---|
417 | GetVariable2 (
|
---|
418 | IN CONST CHAR16 *Name,
|
---|
419 | IN CONST EFI_GUID *Guid,
|
---|
420 | OUT VOID **Value,
|
---|
421 | OUT UINTN *Size OPTIONAL
|
---|
422 | );
|
---|
423 |
|
---|
424 | EFI_STATUS
|
---|
425 | EFIAPI
|
---|
426 | GetEfiGlobalVariable2 (
|
---|
427 | IN CONST CHAR16 *Name,
|
---|
428 | OUT VOID **Value,
|
---|
429 | OUT UINTN *Size OPTIONAL
|
---|
430 | );
|
---|
431 | ```
|
---|
432 |
|
---|
433 | To declare mocks for these functions within the previously created `MockUefiLib` interface,
|
---|
434 | the below code would be added to the `MockUefiLib.h` file. Note that the previously added
|
---|
435 | interface declaration is also included in the code below for context.
|
---|
436 |
|
---|
437 | ```cpp
|
---|
438 | struct MockUefiLib {
|
---|
439 | MOCK_INTERFACE_DECLARATION (MockUefiLib);
|
---|
440 |
|
---|
441 | MOCK_FUNCTION_DECLARATION (
|
---|
442 | EFI_STATUS,
|
---|
443 | GetVariable2,
|
---|
444 | (IN CONST CHAR16 *Name,
|
---|
445 | IN CONST EFI_GUID *Guid,
|
---|
446 | OUT VOID **Value,
|
---|
447 | OUT UINTN *Size OPTIONAL)
|
---|
448 | );
|
---|
449 |
|
---|
450 | MOCK_FUNCTION_DECLARATION (
|
---|
451 | EFI_STATUS,
|
---|
452 | GetEfiGlobalVariable2,
|
---|
453 | (IN CONST CHAR16 *Name,
|
---|
454 | OUT VOID **Value,
|
---|
455 | OUT UINTN *Size OPTIONAL)
|
---|
456 | );
|
---|
457 | };
|
---|
458 | ```
|
---|
459 |
|
---|
460 | Additionally, the below code would be added into the `MockUefiLib.cpp` file to provide
|
---|
461 | the definitions for these mock functions. Again, the previously added interface
|
---|
462 | definition is also included in the code below for context.
|
---|
463 |
|
---|
464 | ```cpp
|
---|
465 | MOCK_INTERFACE_DEFINITION(MockUefiLib);
|
---|
466 |
|
---|
467 | MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, EFIAPI);
|
---|
468 | MOCK_FUNCTION_DEFINITION(MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI);
|
---|
469 | ```
|
---|
470 |
|
---|
471 | That concludes the basic overview on how to use the macros, but a more detailed
|
---|
472 | description on how to name the mocks, where to put the files, how to build the
|
---|
473 | mocks, and how to use the mocks is described in detail later.
|
---|
474 |
|
---|
475 | ### SubhookLib
|
---|
476 |
|
---|
477 | SubhookLib is the library used by FunctionMockLib to implement the macros to
|
---|
478 | mock internal functions: `MOCK_FUNCTION_INTERNAL_DECLARATION` and
|
---|
479 | `MOCK_FUNCTION_INTERNAL_DEFINITION`. These macros require the additional
|
---|
480 | functionality provided by SubhookLib because they create mock functions
|
---|
481 | for functions that are already defined and compiled within the module being
|
---|
482 | tested. More detail on this is provided in a later section, but for now it is
|
---|
483 | sufficient to know that the SubhookLib allows a second definition of the
|
---|
484 | function to be compiled into the test application and then hooked to during a
|
---|
485 | test.
|
---|
486 |
|
---|
487 | This library is mainly a wrapper around the
|
---|
488 | [subhook](https://github.com/Zeex/subhook) header and source files. It is
|
---|
489 | important to note that the use of the mock function macros and the creation
|
---|
490 | of mock functions requires no knowledge about the SubhookLib. The SubhookLib
|
---|
491 | library is entirely hidden and encapsulated within FunctionMockLib, and it
|
---|
492 | is only mentioned here to provide a complete explanation on all the libraries
|
---|
493 | used in the implementation.
|
---|
494 |
|
---|
495 | ## FunctionMockLib Mocks
|
---|
496 |
|
---|
497 | This section describes the details on how to use the mock function macros in
|
---|
498 | FunctionMockLib to create mock functions, name them, organize their files,
|
---|
499 | and build them so that they can be used within GoogleTest tests. The usage
|
---|
500 | of the mock functions is detailed in a later section while this section
|
---|
501 | simply details how to create them, build them, and where to put them.
|
---|
502 |
|
---|
503 | ### FunctionMockLib Mocks - External vs. Internal
|
---|
504 |
|
---|
505 | The first question to ask when creating a mock function is if the function being
|
---|
506 | mocked is external or internal to the module being tested. This is very important
|
---|
507 | because the macros in FunctionMockLib used to create the mock function are named
|
---|
508 | differently for these two use cases. Fortunately, the arguments to these macros
|
---|
509 | and the usage of the mock functions within the tests are exactly the same.
|
---|
510 | However, because of the different underlying implementations, two different sets
|
---|
511 | of macros are used.
|
---|
512 |
|
---|
513 | A more detailed description of when to use the external vs. internal mock function
|
---|
514 | macros is in the following sections, but the quick summary is as follows.
|
---|
515 |
|
---|
516 | * External mock function macros are used to mock functions that are outside the
|
---|
517 | module being tested and use link-time replacement.
|
---|
518 | * Internal mock function macros are used to mock functions that are inside the
|
---|
519 | module being tested and use run-time replacement.
|
---|
520 |
|
---|
521 | The below table shows which macros to use in these two use cases. However, note that
|
---|
522 | for the creation of the interface, the same macros are used in both cases.
|
---|
523 |
|
---|
524 | | Mock Function Use Case | Mock Interface Macros | Mock Function Macros |
|
---|
525 | |:--- |:--- |:--- |
|
---|
526 | | External mock functions | `MOCK_INTERFACE_DECLARATION`</br>`MOCK_INTERFACE_DEFINITION` | `MOCK_FUNCTION_DECLARATION`</br>`MOCK_FUNCTION_DEFINITION` |
|
---|
527 | | Internal mock functions | `MOCK_INTERFACE_DECLARATION`</br>`MOCK_INTERFACE_DEFINITION` | `MOCK_FUNCTION_INTERNAL_DECLARATION`</br>`MOCK_FUNCTION_INTERNAL_DEFINITION` |
|
---|
528 |
|
---|
529 | #### FunctionMockLib Mocks - External mock function
|
---|
530 |
|
---|
531 | The external mock function macros are used to create mock function definitions
|
---|
532 | for a library, global service, or protocol that is defined outside of the module
|
---|
533 | being tested. These mock function definitions are linked into the test application
|
---|
534 | instead of linking in the design function definitions. In other words, the
|
---|
535 | external mock function macros use link-time replacement of the design functions.
|
---|
536 |
|
---|
537 | The `.h/.cpp` files for these mock functions are created within the package
|
---|
538 | directory where the library, global table, or protocol that is being mocked is
|
---|
539 | declared. These files are compiled into their own separate library (using
|
---|
540 | an INF file) that can be shared and linked into many test applications, but more
|
---|
541 | on that later.
|
---|
542 |
|
---|
543 | #### FunctionMockLib Mocks - Internal mock function
|
---|
544 |
|
---|
545 | The internal mock function macros are used to create mock function definitions
|
---|
546 | for functions that are defined within the module being tested. These mock
|
---|
547 | function definitions are compiled into the test application along with the design
|
---|
548 | function definitions. This is possible because the mock functions are given a
|
---|
549 | slightly different name during compilation. Then during test execution, the
|
---|
550 | design function is hooked and replaced with the mock function. In other words,
|
---|
551 | the internal mock function macros use run-time replacement of the design
|
---|
552 | functions.
|
---|
553 |
|
---|
554 | The `.h/.cpp` files for these mock functions are created within the GoogleTest
|
---|
555 | directory containing the specific tests that are using them. These files are
|
---|
556 | compiled directly in the GoogleTest INF file that builds the test application,
|
---|
557 | and they are not shared outside of that GoogleTest directory, but more on that
|
---|
558 | later.
|
---|
559 |
|
---|
560 | ### FunctionMockLib Mocks - Declaration
|
---|
561 |
|
---|
562 | The declaration of mock functions using the FunctionMockLib macros are done
|
---|
563 | in header files. The name of the header file is determined by the interface
|
---|
564 | (such as a library or a protocol) that is being created for the mock functions.
|
---|
565 | The rules for naming the file are shown in the table below.
|
---|
566 |
|
---|
567 | | Interface Type | Header File Name |
|
---|
568 | | :--- | :--- |
|
---|
569 | | Library | Mock\<LibraryName\>Lib.h |
|
---|
570 | | Global Table (e.g. gRT, gBS, etc.) | Mock\<GlobalTableLibraryName\>Lib.h |
|
---|
571 | | Protocol | Mock\<ProtocolName\>Protocol.h |
|
---|
572 |
|
---|
573 | The below table shows examples for file names with each of the above cases.
|
---|
574 |
|
---|
575 | | Interface Type | Interface Name | Header File Name |
|
---|
576 | | :--- | :--- | :--- |
|
---|
577 | | Library | UefiLib | MockUefiLib.h |
|
---|
578 | | Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MockUefiRuntimeServicesTableLib.h |
|
---|
579 | | Protocol | EFI_USB_IO_PROTOCOL | MockEfiUsbIoProtocol.h |
|
---|
580 |
|
---|
581 | Once the header file name is known, the file needs to be created in the proper
|
---|
582 | location. For internal mock functions, the location is simply the same
|
---|
583 | GoogleTest directory that contains the INF file that builds the test application.
|
---|
584 | For external mock functions, the location is within the `Test` directory under the
|
---|
585 | package where the library, global table, or protocol that is being mocked is
|
---|
586 | declared. The exact location depends on the interface type and is shown in the
|
---|
587 | below table.
|
---|
588 |
|
---|
589 | | Interface Type | Header File Location |
|
---|
590 | | :--- | :--- |
|
---|
591 | | Library | \<PackageName\>/Test/Mock/Include/GoogleTest/Library |
|
---|
592 | | Global Table (e.g. gRT, gBS, etc.) | \<PackageName\>/Test/Mock/Include/GoogleTest/Library |
|
---|
593 | | Protocol | \<PackageName\>/Test/Mock/Include/GoogleTest/Protocol |
|
---|
594 |
|
---|
595 | The below table shows examples for file locations with each of the above cases.
|
---|
596 |
|
---|
597 | | Interface Type | Interface Name | Header File Location |
|
---|
598 | | :--- | :--- | :--- |
|
---|
599 | | Library | UefiLib | MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiLib.h |
|
---|
600 | | Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MdePkg/Test/Mock/Include/GoogleTest/Library/MockUefiRuntimeServicesTableLib.h |
|
---|
601 | | Protocol | EFI_USB_IO_PROTOCOL | MdePkg/Test/Mock/Include/GoogleTest/Protocol/MockEfiUsbIoProtocol.h |
|
---|
602 |
|
---|
603 | Now that the file location is known, the contents can be added to it. After the
|
---|
604 | standard `#ifndef` for a header file is added at the top of the file, the
|
---|
605 | `GoogleTestLib.h` and `FunctionMockLib.h` files are always added. Following these
|
---|
606 | includes other EDK II related include files are added and must be wrapped in
|
---|
607 | `extern "C" {}` because they are C include files. Failure to do this will cause
|
---|
608 | link errors to occur. Note that a `#include` of the interface being mocked must
|
---|
609 | also be added. This causes the declarations of the functions being mocked to be
|
---|
610 | included in the compilation and allows the compilation to verify that the function
|
---|
611 | signatures of the mock and design functions are identical.
|
---|
612 |
|
---|
613 | After all the needed includes have been added in the file , a `struct` is declared
|
---|
614 | using the same name as the header file (which was determined using the rules
|
---|
615 | above). Within this structure declaration a `MOCK_INTERFACE_DECLARATION` is
|
---|
616 | added along with a `MOCK_FUNCTION_DECLARATION` (or a
|
---|
617 | `MOCK_FUNCTION_INTERNAL_DECLARATION` if this interface is for internal mock
|
---|
618 | functions) for each function in the interface. To build on the examples above,
|
---|
619 | the complete `MockUefiLib.h` file would be as shown below. Note that for brevity
|
---|
620 | only the `GetVariable2` and `GetEfiGlobalVariable2` declarations are included in
|
---|
621 | the example.
|
---|
622 |
|
---|
623 | ```cpp
|
---|
624 | #ifndef MOCK_UEFI_LIB_H_
|
---|
625 | #define MOCK_UEFI_LIB_H_
|
---|
626 |
|
---|
627 | #include <Library/GoogleTestLib.h>
|
---|
628 | #include <Library/FunctionMockLib.h>
|
---|
629 | extern "C" {
|
---|
630 | #include <Uefi.h>
|
---|
631 | #include <Library/UefiLib.h>
|
---|
632 | }
|
---|
633 |
|
---|
634 | struct MockUefiLib {
|
---|
635 | MOCK_INTERFACE_DECLARATION (MockUefiLib);
|
---|
636 |
|
---|
637 | MOCK_FUNCTION_DECLARATION (
|
---|
638 | EFI_STATUS,
|
---|
639 | GetVariable2,
|
---|
640 | (IN CONST CHAR16 *Name,
|
---|
641 | IN CONST EFI_GUID *Guid,
|
---|
642 | OUT VOID **Value,
|
---|
643 | OUT UINTN *Size OPTIONAL)
|
---|
644 | );
|
---|
645 |
|
---|
646 | MOCK_FUNCTION_DECLARATION (
|
---|
647 | EFI_STATUS,
|
---|
648 | GetEfiGlobalVariable2,
|
---|
649 | (IN CONST CHAR16 *Name,
|
---|
650 | OUT VOID **Value,
|
---|
651 | OUT UINTN *Size OPTIONAL)
|
---|
652 | );
|
---|
653 | };
|
---|
654 |
|
---|
655 | #endif
|
---|
656 | ```
|
---|
657 |
|
---|
658 | In the case of libraries, the function names in the mock declarations
|
---|
659 | align exactly with the function names in the design. However, in the
|
---|
660 | case of global tables and protocols, to eliminate possible function
|
---|
661 | name collisions, the names are adjusted slightly in the mock
|
---|
662 | declarations as shown in the below table.
|
---|
663 |
|
---|
664 | | Mock Function Use Case | Design Function Name | Mock Function Name |
|
---|
665 | | :--- | :--- | :--- |
|
---|
666 | | Library | GetVariable2 | GetVariable2 |
|
---|
667 | | Global Table (e.g. gRT, gBS, etc.) | gRT->GetVariable | gRT_GetVariable |
|
---|
668 | | Protocol | UsbIoProtocol->UsbPortReset | UsbIoProtocol_UsbPortReset |
|
---|
669 |
|
---|
670 | Lastly, when creating mock functions, there are two limitations to be
|
---|
671 | aware of in gMock that extend into FunctionMockLib.
|
---|
672 |
|
---|
673 | 1. gMock does not support mocking functions that have more than 15 arguments.
|
---|
674 | 2. gMock does not support mocking variadic functions.
|
---|
675 |
|
---|
676 | With those limitations in mind, that completes the mock function
|
---|
677 | declarations, and now the mock function definitions for those declarations
|
---|
678 | can be created.
|
---|
679 |
|
---|
680 | ### FunctionMockLib Mocks - Definition
|
---|
681 |
|
---|
682 | The definition of mock functions using the FunctionMockLib macros are done
|
---|
683 | in source files. The name of the source file is determined by the interface
|
---|
684 | (such as a library or a protocol) that is being created for the mock functions.
|
---|
685 | The rules for naming the file align with the naming of the file for declarations
|
---|
686 | and are shown in the table below.
|
---|
687 |
|
---|
688 | | Interface Type | Source File Name |
|
---|
689 | | :--- | :--- |
|
---|
690 | | Library | Mock\<LibraryName\>Lib.cpp |
|
---|
691 | | Global Table (e.g. gRT, gBS, etc.) | Mock\<GlobalTableLibraryName\>Lib.cpp |
|
---|
692 | | Protocol | Mock\<ProtocolName\>Protocol.cpp |
|
---|
693 |
|
---|
694 | The below table shows examples for file names with each of the above cases.
|
---|
695 |
|
---|
696 | | Interface Type | Interface Name | Source File Name |
|
---|
697 | | :--- | :--- | :--- |
|
---|
698 | | Library | UefiLib | MockUefiLib.cpp |
|
---|
699 | | Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MockUefiRuntimeServicesTableLib.cpp |
|
---|
700 | | Protocol | EFI_USB_IO_PROTOCOL | MockEfiUsbIoProtocol.cpp |
|
---|
701 |
|
---|
702 | Once the source file name is known, the file needs to be created in the proper
|
---|
703 | location. The location of the source file is aligned with the location for the
|
---|
704 | header file. For internal mock functions, the location is simply the same
|
---|
705 | GoogleTest directory that contains the INF file that builds the test application.
|
---|
706 | For external mock functions, the location is within the `Test` directory under the
|
---|
707 | package where the library, global table, or protocol that is being mocked is
|
---|
708 | declared. The exact location depends on the interface type and is shown in the
|
---|
709 | below table.
|
---|
710 |
|
---|
711 | | Interface Type | Source File Location |
|
---|
712 | | :--- | :--- |
|
---|
713 | | Library | \<PackageName\>/Test/Mock/Library/GoogleTest/Mock\<LibraryName\>Lib |
|
---|
714 | | Global Table (e.g. gRT, gBS, etc.) | \<PackageName\>/Test/Mock/Library/GoogleTest/Mock\<GlobalTableLibraryName\>Lib |
|
---|
715 | | Protocol | \<PackageName\>/Test/Mock/Library/GoogleTest/Mock\<ProtocolName\>Protocol |
|
---|
716 |
|
---|
717 | The below table shows examples for file locations with each of the above cases.
|
---|
718 |
|
---|
719 | | Interface Type | Interface Name | Source File Location |
|
---|
720 | | :--- | :--- | :--- |
|
---|
721 | | Library | UefiLib | MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.cpp |
|
---|
722 | | Global Table (e.g. gRT, gBS, etc.) | UefiRuntimeServicesTableLib | MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.cpp |
|
---|
723 | | Protocol | EFI_USB_IO_PROTOCOL | MdePkg/Test/Mock/Library/GoogleTest/MockEfiUsbIoProtocol/MockEfiUsbIoProtocol.cpp |
|
---|
724 |
|
---|
725 | Now that the file location is known, the contents can be added to it. At the top
|
---|
726 | of the file, the header file containing the mock function declarations is always
|
---|
727 | added. After this `#include`, the interface definition is created using
|
---|
728 | `MOCK_INTERFACE_DEFINITION` with the interface name that was used in the mock
|
---|
729 | function declaration header file. A `MOCK_FUNCTION_DEFINITION` is then added (or
|
---|
730 | a `MOCK_FUNCTION_INTERNAL_DEFINITION` if this interface is for internal mock
|
---|
731 | functions) for each function that was declared in the interface. To build on the
|
---|
732 | prior declaration examples, the complete `MockUefiLib.cpp` file would be as shown
|
---|
733 | below. Note that for brevity only the `GetVariable2` and `GetEfiGlobalVariable2`
|
---|
734 | definitions are included in the example.
|
---|
735 |
|
---|
736 | ```cpp
|
---|
737 | #include <GoogleTest/Library/MockUefiLib.h>
|
---|
738 |
|
---|
739 | MOCK_INTERFACE_DEFINITION(MockUefiLib);
|
---|
740 |
|
---|
741 | MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, EFIAPI);
|
---|
742 | MOCK_FUNCTION_DEFINITION(MockUefiLib, GetEfiGlobalVariable2, 3, EFIAPI);
|
---|
743 | ```
|
---|
744 |
|
---|
745 | When creating the defintions, there are a few things to keep in mind.
|
---|
746 |
|
---|
747 | First, when using `MOCK_FUNCTION_DEFINITION`, some functions being mocked do
|
---|
748 | not specify a calling convention. In this case, it is fine to leave the last
|
---|
749 | argument of `MOCK_FUNCTION_DEFINITION` empty. For example, if `GetVariable2`
|
---|
750 | did not specify the `EFIAPI` calling convention in its declaration, then the
|
---|
751 | below code would be used for the mock function definition.
|
---|
752 |
|
---|
753 | ```cpp
|
---|
754 | MOCK_FUNCTION_DEFINITION(MockUefiLib, GetVariable2, 4, );
|
---|
755 | ```
|
---|
756 |
|
---|
757 | Second, the function name used in `MOCK_FUNCTION_DEFINITION` must align with
|
---|
758 | the function name used in the associated `MOCK_FUNCTION_DECLARATION` in the
|
---|
759 | header file.
|
---|
760 |
|
---|
761 | Last, if the interface is mocking a global table or protocol, then the structure
|
---|
762 | of function pointers for that interface must also be defined within the source
|
---|
763 | file as a `static` structure with the mock function definitions being assigned
|
---|
764 | to the associated entries in the structure. The address of this `static`
|
---|
765 | structure is then assigned to the global table or protocol pointer. Note that
|
---|
766 | this pointer must be wrapped in `extern "C" {}` because it needs C style
|
---|
767 | linkage. Failure to do this will cause link errors to occur. For example, when
|
---|
768 | creating the definition of the mock for the global runtime services table, the
|
---|
769 | complete `MockUefiRuntimeServicesTableLib.cpp` file would be as shown below.
|
---|
770 | Note that for brevity only the `GetVariable` and `SetVariable` definitions are
|
---|
771 | included in the example.
|
---|
772 |
|
---|
773 | ```cpp
|
---|
774 | #include <GoogleTest/Library/MockUefiRuntimeServicesTableLib.h>
|
---|
775 |
|
---|
776 | MOCK_INTERFACE_DEFINITION(MockUefiRuntimeServicesTableLib);
|
---|
777 |
|
---|
778 | MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_GetVariable, 5, EFIAPI);
|
---|
779 | MOCK_FUNCTION_DEFINITION(MockUefiRuntimeServicesTableLib, gRT_SetVariable, 5, EFIAPI);
|
---|
780 |
|
---|
781 | static EFI_RUNTIME_SERVICES localRt = {
|
---|
782 | {0}, // EFI_TABLE_HEADER
|
---|
783 |
|
---|
784 | NULL, // EFI_GET_TIME
|
---|
785 | NULL, // EFI_SET_TIME
|
---|
786 | NULL, // EFI_GET_WAKEUP_TIME
|
---|
787 | NULL, // EFI_SET_WAKEUP_TIME
|
---|
788 |
|
---|
789 | NULL, // EFI_SET_VIRTUAL_ADDRESS_MAP
|
---|
790 | NULL, // EFI_CONVERT_POINTER
|
---|
791 |
|
---|
792 | gRT_GetVariable, // EFI_GET_VARIABLE
|
---|
793 | NULL, // EFI_GET_NEXT_VARIABLE_NAME
|
---|
794 | gRT_SetVariable, // EFI_SET_VARIABLE
|
---|
795 |
|
---|
796 | NULL, // EFI_GET_NEXT_HIGH_MONO_COUNT
|
---|
797 | NULL, // EFI_RESET_SYSTEM
|
---|
798 |
|
---|
799 | NULL, // EFI_UPDATE_CAPSULE
|
---|
800 | NULL, // EFI_QUERY_CAPSULE_CAPABILITIES
|
---|
801 |
|
---|
802 | NULL, // EFI_QUERY_VARIABLE_INFO
|
---|
803 | };
|
---|
804 |
|
---|
805 | extern "C" {
|
---|
806 | EFI_RUNTIME_SERVICES* gRT = &localRt;
|
---|
807 | }
|
---|
808 | ```
|
---|
809 |
|
---|
810 | That completes the mock function definitions. So now these mock function
|
---|
811 | definitions can be compiled.
|
---|
812 |
|
---|
813 | ### FunctionMockLib Mocks - Build
|
---|
814 |
|
---|
815 | The building of mock functions using FunctionMockLib is done slightly
|
---|
816 | differently for external and internal function mocks. External mock
|
---|
817 | functions are built using their own separate INF file and internal mock
|
---|
818 | functions are built as source files directly referenced in the GoogleTest
|
---|
819 | INF file that builds the test application.
|
---|
820 |
|
---|
821 | #### FunctionMockLib Mocks - Build External Mock Functions
|
---|
822 |
|
---|
823 | The building of external mock functions is done using their own separate INF
|
---|
824 | file which is placed in the same location as the associated source file
|
---|
825 | containing the mock function definitions. The name of the INF file is exactly
|
---|
826 | the same as the mock function definitions file, but uses the `.inf` extension
|
---|
827 | rather than `.cpp`.
|
---|
828 |
|
---|
829 | Within the `.inf` file the `BASE_NAME` should be set to the same name as the
|
---|
830 | file (minus the extension), the `MODULE_TYPE` should be set to
|
---|
831 | `HOST_APPLICATION`, and the `LIBRARY_CLASS` should be the same as the
|
---|
832 | `BASE_NAME` but without the `Mock` prefix.
|
---|
833 |
|
---|
834 | The `[Sources]` section will contain the single mock function definition
|
---|
835 | source file, the `[Packages]` section will contain all the necessary DEC
|
---|
836 | files to compile the mock functions (which at a minimum will include the
|
---|
837 | `UnitTestFrameworkPkg.dec` file), the `[LibraryClasses]` section will contain
|
---|
838 | the `GoogleTestLib`, and the `[BuildOptions]` will need to append the `/EHsc`
|
---|
839 | compilation flag to all MSFT builds to enable proper use of the C++ exception
|
---|
840 | handler. Below is the complete `MockUefiLib.inf` as an example.
|
---|
841 |
|
---|
842 | ```
|
---|
843 | [Defines]
|
---|
844 | INF_VERSION = 0x00010005
|
---|
845 | BASE_NAME = MockUefiLib
|
---|
846 | FILE_GUID = 47211F7A-6D90-4DFB-BDF9-610B69197C2E
|
---|
847 | MODULE_TYPE = HOST_APPLICATION
|
---|
848 | VERSION_STRING = 1.0
|
---|
849 | LIBRARY_CLASS = UefiLib
|
---|
850 |
|
---|
851 | #
|
---|
852 | # The following information is for reference only and not required by the build tools.
|
---|
853 | #
|
---|
854 | # VALID_ARCHITECTURES = IA32 X64
|
---|
855 | #
|
---|
856 |
|
---|
857 | [Sources]
|
---|
858 | MockUefiLib.cpp
|
---|
859 |
|
---|
860 | [Packages]
|
---|
861 | MdePkg/MdePkg.dec
|
---|
862 | UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec
|
---|
863 |
|
---|
864 | [LibraryClasses]
|
---|
865 | GoogleTestLib
|
---|
866 |
|
---|
867 | [BuildOptions]
|
---|
868 | MSFT:*_*_*_CC_FLAGS = /EHsc
|
---|
869 | ```
|
---|
870 |
|
---|
871 | To ensure that this specific set of mock functions are always buildable even
|
---|
872 | if no test uses it yet, this created INF file needs to be added into the
|
---|
873 | `[Components]` section of the associated `Test` DSC file for the package in
|
---|
874 | which this INF file resides. For example, the above `MockUefiLib.inf` would
|
---|
875 | need to be added to the `MdePkg/Test/MdePkgHostTest.dsc` file as shown below.
|
---|
876 |
|
---|
877 | ```
|
---|
878 | [Components]
|
---|
879 | MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf
|
---|
880 | ```
|
---|
881 |
|
---|
882 | This created INF file will also be referenced within the necessary `Test` DSC
|
---|
883 | files in order to include the mock function definitions in the test
|
---|
884 | applications which use this set of mock functions, but more on that later.
|
---|
885 |
|
---|
886 | One small additional requirement is that if this INF file is added into a
|
---|
887 | package that does not yet have any other external mock functions in it, then
|
---|
888 | that package's DEC file will need to have the mock include directory (more
|
---|
889 | specifically the `Test/Mock/Include` directory) added to its `[Includes]`
|
---|
890 | section so that test files who want to use the mock functions will be able to
|
---|
891 | locate the mock function header file. For example, if `MockUefiLib.inf` were
|
---|
892 | the first mock added to the `MdePkg`, then the below snippet would need to be
|
---|
893 | added to the `MdePkg.dec` file.
|
---|
894 |
|
---|
895 | ```
|
---|
896 | [Includes]
|
---|
897 | Test/Mock/Include
|
---|
898 | ```
|
---|
899 |
|
---|
900 | #### FunctionMockLib Mocks - Build Internal Mock Functions
|
---|
901 |
|
---|
902 | The building of internal mock functions is done using the GoogleTest INF file
|
---|
903 | that already needs to exist to build the test application. This is easy to
|
---|
904 | manage since the source and header files for the internal mock functions are
|
---|
905 | also located in the same GoogleTest directory as the GoogleTest INF file that
|
---|
906 | will reference them.
|
---|
907 |
|
---|
908 | The only additions that are required to the GoogleTest INF file are that the
|
---|
909 | mock function definitions file be added to the `[Sources]` section, the
|
---|
910 | `UnitTestFrameworkPkg.dec` file be added to the `[Packages]` section, and the
|
---|
911 | `GoogleTestLib` and `SubhookLib` be added to the `[LibraryClasses]` section.
|
---|
912 | Below is a minimal contrived example for a `MyModuleGoogleTest.inf` that uses a
|
---|
913 | `MockMyModuleInternalFunctions.cpp` source file for its internal mock functions.
|
---|
914 |
|
---|
915 | ```
|
---|
916 | [Defines]
|
---|
917 | INF_VERSION = 0x00010017
|
---|
918 | BASE_NAME = MyModuleGoogleTest
|
---|
919 | FILE_GUID = 814B09B9-2D51-4786-8A77-2E10CD1C55F3
|
---|
920 | VERSION_STRING = 1.0
|
---|
921 | MODULE_TYPE = HOST_APPLICATION
|
---|
922 |
|
---|
923 | #
|
---|
924 | # The following information is for reference only and not required by the build tools.
|
---|
925 | #
|
---|
926 | # VALID_ARCHITECTURES = IA32 X64
|
---|
927 | #
|
---|
928 |
|
---|
929 | [Sources]
|
---|
930 | MyModuleGoogleTest.cpp
|
---|
931 | MockMyModuleInternalFunctions.cpp
|
---|
932 |
|
---|
933 | [Packages]
|
---|
934 | MdePkg/MdePkg.dec
|
---|
935 | UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec
|
---|
936 |
|
---|
937 | [LibraryClasses]
|
---|
938 | GoogleTestLib
|
---|
939 | SubhookLib
|
---|
940 | ```
|
---|
941 |
|
---|
942 | ## GoogleTest Samples
|
---|
943 |
|
---|
944 | There is a sample unit test provided as both an example of how to write a unit test and leverage
|
---|
945 | many of the GoogleTest features. This sample can be found in the `Test/GoogleTest/Sample/SampleGoogleTest`
|
---|
946 | directory.
|
---|
947 |
|
---|
948 | The sample is provided for the HOST_APPLICATION build type, which can be run on a host system without
|
---|
949 | needing a target.
|
---|
950 |
|
---|
951 | There is also a sample unit test provided as both an example of how to write a unit test with
|
---|
952 | mock functions and leverage some of the gMock features. This sample can be found in the
|
---|
953 | `SecurityPkg/Library/SecureBootVariableLib/GoogleTest` directory.
|
---|
954 |
|
---|
955 | It too is provided for the HOST_APPLICATION build type, which can be run on a host system without
|
---|
956 | needing a target.
|
---|
957 |
|
---|
958 | ## GoogleTest Usage
|
---|
959 |
|
---|
960 | This section is built a lot like a "Getting Started". We'll go through some of the components that are needed
|
---|
961 | when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe
|
---|
962 | how to check for expected conditions in test cases and a bit of the logging characteristics.
|
---|
963 |
|
---|
964 | Most of these examples will refer to the `SampleGoogleTestHost` app found in this package, but
|
---|
965 | the examples related to mock functions will refer to the `SecureBootVariableLibGoogleTest` app
|
---|
966 | found in the `SecurityPkg`.
|
---|
967 |
|
---|
968 | ### GoogleTest Requirements - INF
|
---|
969 |
|
---|
970 | In our INF file, we'll need to bring in the `GoogleTestLib` library. Conveniently, the interface
|
---|
971 | header for the `GoogleTestLib` is in `UnitTestFrameworkPkg`, so you shouldn't need to depend on any other
|
---|
972 | packages. As long as your DSC file knows where to find the lib implementation that you want to use,
|
---|
973 | you should be good to go.
|
---|
974 |
|
---|
975 | See this example in `SampleGoogleTestHost.inf`...
|
---|
976 |
|
---|
977 | ```
|
---|
978 | [Packages]
|
---|
979 | MdePkg/MdePkg.dec
|
---|
980 | UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec
|
---|
981 |
|
---|
982 | [LibraryClasses]
|
---|
983 | GoogleTestLib
|
---|
984 | BaseLib
|
---|
985 | DebugLib
|
---|
986 | ```
|
---|
987 |
|
---|
988 | Also, if you want your test to automatically be picked up by the Test Runner plugin, you will need
|
---|
989 | to make sure that the module `BASE_NAME` contains the word `Test`...
|
---|
990 |
|
---|
991 | ```
|
---|
992 | [Defines]
|
---|
993 | BASE_NAME = SampleGoogleTestHost
|
---|
994 | ```
|
---|
995 |
|
---|
996 | ### GoogleTest Requirements - DSC
|
---|
997 |
|
---|
998 | In our DSC file, we'll need to bring in the INF file that was just created into the `[Components]`
|
---|
999 | section so that the unit tests will be built.
|
---|
1000 |
|
---|
1001 | See this example in `UnitTestFrameworkPkgHostTest.dsc`...
|
---|
1002 |
|
---|
1003 | ```
|
---|
1004 | [Components]
|
---|
1005 | UnitTestFrameworkPkg/Test/GoogleTest/Sample/SampleGoogleTest/SampleGoogleTestHost.inf
|
---|
1006 | ```
|
---|
1007 |
|
---|
1008 | Also, based on the type of tests that are being created, the associated DSC include file from the
|
---|
1009 | UnitTestFrameworkPkg for Host or Target based tests should also be included at the top of the DSC
|
---|
1010 | file.
|
---|
1011 |
|
---|
1012 | ```
|
---|
1013 | !include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc
|
---|
1014 | ```
|
---|
1015 |
|
---|
1016 | Lastly, in the case that the test build has specific dependent libraries associated with it,
|
---|
1017 | they should be added in the \<LibraryClasses\> sub-section for the INF file in the
|
---|
1018 | `[Components]` section of the DSC file. Note that it is within this sub-section where you can
|
---|
1019 | control whether the design or mock version of a component is linked into the test exectuable.
|
---|
1020 |
|
---|
1021 | See this example in `SecurityPkgHostTest.dsc` where the `SecureBootVariableLib` design is
|
---|
1022 | being tested using mock versions of `UefiRuntimeServicesTableLib`, `PlatformPKProtectionLib`,
|
---|
1023 | and `UefiLib`...
|
---|
1024 |
|
---|
1025 | ```
|
---|
1026 | [Components]
|
---|
1027 | SecurityPkg/Library/SecureBootVariableLib/GoogleTest/SecureBootVariableLibGoogleTest.inf {
|
---|
1028 | <LibraryClasses>
|
---|
1029 | SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf
|
---|
1030 | UefiRuntimeServicesTableLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiRuntimeServicesTableLib/MockUefiRuntimeServicesTableLib.inf
|
---|
1031 | PlatformPKProtectionLib|SecurityPkg/Test/Mock/Library/GoogleTest/MockPlatformPKProtectionLib/MockPlatformPKProtectionLib.inf
|
---|
1032 | UefiLib|MdePkg/Test/Mock/Library/GoogleTest/MockUefiLib/MockUefiLib.inf
|
---|
1033 | }
|
---|
1034 | ```
|
---|
1035 |
|
---|
1036 | ### GoogleTest Requirements - Code
|
---|
1037 |
|
---|
1038 | GoogleTest applications are implemented in C++, so make sure that your test file has
|
---|
1039 | a `.cpp` extension. With that behind us, not to state the obvious, but let's make sure
|
---|
1040 | we have the following includes before getting too far along in the file...
|
---|
1041 |
|
---|
1042 | ```cpp
|
---|
1043 | #include <Library/GoogleTestLib.h>
|
---|
1044 | extern "C" {
|
---|
1045 | #include <Uefi.h>
|
---|
1046 | #include <Library/BaseLib.h>
|
---|
1047 | #include <Library/DebugLib.h>
|
---|
1048 | }
|
---|
1049 | ```
|
---|
1050 |
|
---|
1051 | The first include brings in the GoogleTest definitions. Other EDK II related include
|
---|
1052 | files must be wrapped in `extern "C" {}` because they are C include files. Link
|
---|
1053 | failures will occur if this is not done.
|
---|
1054 |
|
---|
1055 | Also, when using GoogleTest it is helpful to add a `using` declaration for its
|
---|
1056 | `testing` namespace. This `using` statement greatly reduces the amount of code you
|
---|
1057 | need to write in the tests when referencing the utilities within the `testing`
|
---|
1058 | namespace. For example, instead of writing `::testing::Return` or `::testing::Test`,
|
---|
1059 | you can just write `Return` or `Test` respectively, and these types of references
|
---|
1060 | occur numerous times within the tests.
|
---|
1061 |
|
---|
1062 | Lastly, in the case that tests within a GoogleTest application require the usage of
|
---|
1063 | mock functions, it is also necessary to include the header files for those interfaces
|
---|
1064 | as well. As an example, the `SecureBootVariableLibGoogleTest` uses the mock versions
|
---|
1065 | of `UefiLib` and `UefiRuntimeServicesTableLib`. So its test file contains the below
|
---|
1066 | includes. Note that the `using` declaration mentioned above is also shown in the code
|
---|
1067 | below for completeness of the example.
|
---|
1068 |
|
---|
1069 | ```cpp
|
---|
1070 | #include <Library/GoogleTestLib.h>
|
---|
1071 | #include <GoogleTest/Library/MockUefiLib.h>
|
---|
1072 | #include <GoogleTest/Library/MockUefiRuntimeServicesTableLib.h>
|
---|
1073 |
|
---|
1074 | extern "C" {
|
---|
1075 | #include <Uefi.h>
|
---|
1076 | ...
|
---|
1077 | }
|
---|
1078 |
|
---|
1079 | using namespace testing;
|
---|
1080 | ```
|
---|
1081 |
|
---|
1082 | Now that we've got that squared away, let's look at our 'Main()' routine (or DriverEntryPoint() or whatever).
|
---|
1083 |
|
---|
1084 | ### GoogleTest Configuration
|
---|
1085 |
|
---|
1086 | Unlike the Framework, GoogleTest does not require test suites or test cases to
|
---|
1087 | be registered. Instead, the test cases declare the test suite name and test
|
---|
1088 | case name as part of their implementation. The only requirement for GoogleTest
|
---|
1089 | is to have a `main()` function that initializes the GoogleTest infrastructure
|
---|
1090 | and calls the service `RUN_ALL_TESTS()` to run all the unit tests.
|
---|
1091 |
|
---|
1092 | ```cpp
|
---|
1093 | int main(int argc, char* argv[]) {
|
---|
1094 | testing::InitGoogleTest(&argc, argv);
|
---|
1095 | return RUN_ALL_TESTS();
|
---|
1096 | }
|
---|
1097 | ```
|
---|
1098 |
|
---|
1099 | However, while GoogleTest does not require test suites or test cases to be
|
---|
1100 | registered, there is still one rule within EDK II that currently needs to be
|
---|
1101 | followed. This rule is that all tests for a given GoogleTest application must
|
---|
1102 | be contained within the same source file that contains the `main()` function
|
---|
1103 | shown above. These tests can be written directly in the file or a `#include`
|
---|
1104 | can be used to add them into the file indirectly.
|
---|
1105 |
|
---|
1106 | The reason for this is due to EDK II taking the host application INF file and
|
---|
1107 | first compiling all of its source files into a static library. This static
|
---|
1108 | library is then linked into the final host application. The problem with this
|
---|
1109 | method is that only the tests in the object file containing the `main()`
|
---|
1110 | function are linked into the final host application. This is because the other
|
---|
1111 | tests are contained in their own object files within the static library and
|
---|
1112 | they have no symbols in them that the final host application depends on, so
|
---|
1113 | those object files are not linked into the final host application.
|
---|
1114 |
|
---|
1115 | ### GoogleTest - A Simple Test Case
|
---|
1116 |
|
---|
1117 | Below is a sample test case from `SampleGoogleTestHost`.
|
---|
1118 |
|
---|
1119 | ```cpp
|
---|
1120 | TEST(SimpleMathTests, OnePlusOneShouldEqualTwo) {
|
---|
1121 | UINTN A;
|
---|
1122 | UINTN B;
|
---|
1123 | UINTN C;
|
---|
1124 |
|
---|
1125 | A = 1;
|
---|
1126 | B = 1;
|
---|
1127 | C = A + B;
|
---|
1128 |
|
---|
1129 | ASSERT_EQ (C, 2);
|
---|
1130 | }
|
---|
1131 | ```
|
---|
1132 |
|
---|
1133 | This uses the simplest form of a GoogleTest unit test using `TEST()` that
|
---|
1134 | declares the test suite name and the unit test name within that test suite.
|
---|
1135 | The unit test performs actions and typically makes calls to the code under test
|
---|
1136 | and contains test assertions to verify that the code under test behaves as
|
---|
1137 | expected for the given inputs.
|
---|
1138 |
|
---|
1139 | In this test case, the `ASSERT_EQ` assertion is being used to establish that the business logic has functioned
|
---|
1140 | correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your
|
---|
1141 | intended test criterium as possible, because the logging is specific to the macro and more specific macros have more
|
---|
1142 | detailed logs. When in doubt, there are always `ASSERT_TRUE` and `ASSERT_FALSE`. Assertion macros that fail their
|
---|
1143 | test criterium will immediately return from the test case with a failed status and log an error string.
|
---|
1144 | _Note_ that this early return can have implications for memory leakage.
|
---|
1145 |
|
---|
1146 | For most `ASSERT` macros in GoogleTest there is also an equivalent `EXPECT` macro. Both macro versions
|
---|
1147 | will ultimately cause the `TEST` to fail if the check fails. However, the difference between the two
|
---|
1148 | macro versions is that when the check fails, the `ASSERT` version immediately returns from the `TEST`
|
---|
1149 | while the `EXPECT` version continues running the `TEST`.
|
---|
1150 |
|
---|
1151 | There is no return status from a GooglTest unit test. If no assertions (or expectations) are
|
---|
1152 | triggered then the unit test has a passing status.
|
---|
1153 |
|
---|
1154 | ### GoogleTest - A gMock Test Case
|
---|
1155 |
|
---|
1156 | Below is a sample test case from `SecureBootVariableLibGoogleTest`. Although
|
---|
1157 | actually, the test case is not written exactly like this in the test file, but
|
---|
1158 | more on that in a bit.
|
---|
1159 |
|
---|
1160 | ```cpp
|
---|
1161 | TEST(SetSecureBootModeTest, SetVarError) {
|
---|
1162 | MockUefiRuntimeServicesTableLib RtServicesMock;
|
---|
1163 | UINT8 SecureBootMode;
|
---|
1164 | EFI_STATUS Status;
|
---|
1165 |
|
---|
1166 | // Any random magic number can be used for these tests
|
---|
1167 | SecureBootMode = 0xAB;
|
---|
1168 |
|
---|
1169 | EXPECT_CALL(RtServicesMock, gRT_SetVariable)
|
---|
1170 | .WillOnce(Return(EFI_INVALID_PARAMETER));
|
---|
1171 |
|
---|
1172 | Status = SetSecureBootMode(SecureBootMode);
|
---|
1173 | EXPECT_EQ(Status, EFI_INVALID_PARAMETER);
|
---|
1174 | }
|
---|
1175 | ```
|
---|
1176 |
|
---|
1177 | Keep in mind that this test is written to verify that `SetSecureBootMode()` will
|
---|
1178 | return `EFI_INVALID_PARAMETER` when the call to `gRT->SetVariable()` within the
|
---|
1179 | implementation of `SetSecureBootMode()` returns `EFI_INVALID_PARAMETER`. With that
|
---|
1180 | in mind, let's discuss how a mock function is used to accomplish this in the test.
|
---|
1181 |
|
---|
1182 | In this test case, the `MockUefiRuntimeServicesTableLib` interface is instantiated as
|
---|
1183 | `RtServicesMock` which enables its associated mock functions. These interface
|
---|
1184 | instantiations that contain the mock functions are very important for mock function
|
---|
1185 | based unit tests because without these instantiations, the mock functions within that
|
---|
1186 | interface will not exist and can not be used.
|
---|
1187 |
|
---|
1188 | The next line of interest is the `EXPECT_CALL`, which is a standard part of the gMock
|
---|
1189 | framework. This macro is telling the test that a call is expected to occur to a
|
---|
1190 | specific function on a specific interface. The first argument is the name of the
|
---|
1191 | interface object that was instantiated in this test, and the second argument is the
|
---|
1192 | name of the mock function within that interface that is expected to be called. The
|
---|
1193 | `WillOnce(Return(EFI_INVALID_PARAMETER))` associated with this `EXPECT_CALL` states
|
---|
1194 | that the `gRT_SetVariable()` function (remember from earlier in this documentation
|
---|
1195 | that this refers to the `gRT->SetVariable()` function) will be called once during
|
---|
1196 | this test, and when it does get called, we want it to return `EFI_INVALID_PARAMETER`.
|
---|
1197 |
|
---|
1198 | Once this `EXPECT_CALL` has been setup, the call to `SetSecureBootMode()` occurs in
|
---|
1199 | the test, and its return value is saved in `Status` so that it can be tested. Based
|
---|
1200 | on the `EXPECT_CALL` that was setup earlier, when `SetSecureBootMode()` internally
|
---|
1201 | calls `gRT->SetVariable()`, it returns `EFI_INVALID_PARAMETER`. This value should
|
---|
1202 | then be returned by `SetSecureBootMode()`, and the
|
---|
1203 | `EXPECT_EQ(Status, EFI_INVALID_PARAMETER)` verifies this is the case.
|
---|
1204 |
|
---|
1205 | There is much more that can be done with `EXPECT_CALL` and mock functions, but we
|
---|
1206 | will leave those details to be explained in the gMock documentation.
|
---|
1207 |
|
---|
1208 | Now it was mentioned earlier that this test case is not written exactly like this
|
---|
1209 | in the test file, and the next section describes how this test is slightly
|
---|
1210 | refactored to reduce the total amount of code in the entire test suite.
|
---|
1211 |
|
---|
1212 | ### GoogleTest - A gMock Test Case (refactored)
|
---|
1213 |
|
---|
1214 | The sample test case from `SecureBootVariableLibGoogleTest` in the prior section is
|
---|
1215 | actually written as shown below.
|
---|
1216 |
|
---|
1217 | ```cpp
|
---|
1218 | class SetSecureBootModeTest : public Test {
|
---|
1219 | protected:
|
---|
1220 | MockUefiRuntimeServicesTableLib RtServicesMock;
|
---|
1221 | UINT8 SecureBootMode;
|
---|
1222 | EFI_STATUS Status;
|
---|
1223 |
|
---|
1224 | void SetUp() override {
|
---|
1225 | // Any random magic number can be used for these tests
|
---|
1226 | SecureBootMode = 0xAB;
|
---|
1227 | }
|
---|
1228 | };
|
---|
1229 |
|
---|
1230 | TEST_F(SetSecureBootModeTest, SetVarError) {
|
---|
1231 | EXPECT_CALL(RtServicesMock, gRT_SetVariable)
|
---|
1232 | .WillOnce(Return(EFI_INVALID_PARAMETER));
|
---|
1233 |
|
---|
1234 | Status = SetSecureBootMode(SecureBootMode);
|
---|
1235 | EXPECT_EQ(Status, EFI_INVALID_PARAMETER);
|
---|
1236 | }
|
---|
1237 | ```
|
---|
1238 |
|
---|
1239 | This code may at first seem more complicated, but you will notice that the code
|
---|
1240 | with in it is still the same. There is still a `MockUefiRuntimeServicesTableLib`
|
---|
1241 | instantiation, there is still a `SecureBootMode` and `Status` variable defined,
|
---|
1242 | there is still an `EXPECT_CALL`, and etc. However, the benefit of constructing
|
---|
1243 | the test this way is that the new `TEST_F()` requires less code than the prior
|
---|
1244 | `TEST()`.
|
---|
1245 |
|
---|
1246 | This is made possible by the usage of what GoogleTest calls a _test fixture_.
|
---|
1247 | This concept of a test fixture allows multiple tests to use (or more specifically
|
---|
1248 | inherit from a base class) a common set of variables and initial conditions.
|
---|
1249 | Notice that using `TEST_F()` requires the first argument to be a name that aligns
|
---|
1250 | with a test fixture (in this case `SetSecureBootModeTest`), and the second
|
---|
1251 | argument is the name of the test (just like in the `TEST()` macro).
|
---|
1252 |
|
---|
1253 | All `TEST_F()` tests that use a specific test fixture can be thought of as having
|
---|
1254 | all of that test fixture's variables automatically defined in the test as well as
|
---|
1255 | having that text fixture's `SetUp()` function called before entering the test.
|
---|
1256 |
|
---|
1257 | This means that another `TEST_F()` can be written without needing to worry about
|
---|
1258 | defining a bunch of variables or instantiating a bunch of interfaces for mock
|
---|
1259 | functions. For example, the below test (also in `SecureBootVariableLibGoogleTest`)
|
---|
1260 | uses the same test fixture and makes use of its `RtServicesMock`, `Status`, and
|
---|
1261 | `SecureBootMode` variables.
|
---|
1262 |
|
---|
1263 | ```cpp
|
---|
1264 | TEST_F(SetSecureBootModeTest, PropogateModeToSetVar) {
|
---|
1265 | EXPECT_CALL(RtServicesMock,
|
---|
1266 | gRT_SetVariable(
|
---|
1267 | Char16StrEq(EFI_CUSTOM_MODE_NAME),
|
---|
1268 | BufferEq(&gEfiCustomModeEnableGuid, sizeof(EFI_GUID)),
|
---|
1269 | EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS,
|
---|
1270 | sizeof(SecureBootMode),
|
---|
1271 | BufferEq(&SecureBootMode, sizeof(SecureBootMode))))
|
---|
1272 | .WillOnce(Return(EFI_SUCCESS));
|
---|
1273 |
|
---|
1274 | Status = SetSecureBootMode(SecureBootMode);
|
---|
1275 | EXPECT_EQ(Status, EFI_SUCCESS);
|
---|
1276 | }
|
---|
1277 | ```
|
---|
1278 |
|
---|
1279 | The biggest benefit is that the `TEST_F()` code can now focus on what is being
|
---|
1280 | tested and not worry about any repetitive setup. There is more that can be done
|
---|
1281 | with test fixtures, but we will leave those details to be explained in the
|
---|
1282 | gMock documentation.
|
---|
1283 |
|
---|
1284 | Now, as for what is in the above test, it is slightly more complicated than the
|
---|
1285 | first test. So let's explain this added complexity and what it is actually
|
---|
1286 | testing. In this test, there is still an `EXPECT_CALL` for the
|
---|
1287 | `gRT_SetVariable()` function. However, in this test we are stating that we
|
---|
1288 | expect the input arguments passed to `gRT_SetVariable()` be specific values.
|
---|
1289 | The order they are provided in the `EXPECT_CALL` align with the order of the
|
---|
1290 | arguments in the `gRT_SetVariable()` function. In this case the order of the
|
---|
1291 | `gRT_SetVariable()` arguments is as shown below.
|
---|
1292 |
|
---|
1293 | ```cpp
|
---|
1294 | IN CHAR16 *VariableName,
|
---|
1295 | IN EFI_GUID *VendorGuid,
|
---|
1296 | IN UINT32 Attributes,
|
---|
1297 | IN UINTN DataSize,
|
---|
1298 | IN VOID *Data
|
---|
1299 | ```
|
---|
1300 |
|
---|
1301 | So in the `EXPECT_CALL` we are stating that the call to `gRT_SetVariable()`
|
---|
1302 | will be made with the below input argument values.
|
---|
1303 |
|
---|
1304 | 1. `VariableName` is equal to the `EFI_CUSTOM_MODE_NAME` string
|
---|
1305 | 2. `VendorGuid` is equal to the `gEfiCustomModeEnableGuid` GUID (which has a byte length of `sizeof(EFI_GUID)`)
|
---|
1306 | 3. `Attributes` is equal to `EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS`
|
---|
1307 | 4. `DataSize` is equal to `sizeof(SecureBootMode)`
|
---|
1308 | 5. `Data` is equal to `SecureBootMode` (which has a byte length of `sizeof(SecureBootMode)`)
|
---|
1309 |
|
---|
1310 | If any one of these input arguments does not match in the actual call to
|
---|
1311 | `gRT_SetVariable()` in the design, then the test will fail. There is much more
|
---|
1312 | that can be done with `EXPECT_CALL` and mock functions, but again we will
|
---|
1313 | leave those details to be explained in the gMock documentation.
|
---|
1314 |
|
---|
1315 | ### GoogleTest - More Complex Cases
|
---|
1316 |
|
---|
1317 | To write more advanced tests, take a look at the
|
---|
1318 | [GoogleTest User's Guide](http://google.github.io/googletest/).
|
---|
1319 |
|
---|
1320 | ## Development
|
---|
1321 |
|
---|
1322 | ### Iterating on a Single Test
|
---|
1323 |
|
---|
1324 | When using the EDK2 Pytools for CI testing, the host-based unit tests will be built and run on any build that includes
|
---|
1325 | the `NOOPT` build target.
|
---|
1326 |
|
---|
1327 | If you are trying to iterate on a single test, a convenient pattern is to build only that test module. For example,
|
---|
1328 | the following command will build only the SafeIntLib host-based test from the MdePkg...
|
---|
1329 |
|
---|
1330 | ```bash
|
---|
1331 | stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf
|
---|
1332 | ```
|
---|
1333 |
|
---|
1334 | ### Hooking BaseLib
|
---|
1335 |
|
---|
1336 | Most unit test mocking can be performed by the functions provided in the UnitTestFrameworkPkg libraries, but since
|
---|
1337 | BaseLib is consumed by the Framework itself, it requires different techniques to substitute parts of the
|
---|
1338 | functionality.
|
---|
1339 |
|
---|
1340 | To solve some of this, the UnitTestFrameworkPkg consumes a special implementation of BaseLib for host-based tests.
|
---|
1341 | This implementation contains a [hook table](https://github.com/tianocore/edk2/blob/e188ecc8b4aed8fdd26b731d43883861f5e5e7b4/MdePkg/Test/UnitTest/Include/Library/UnitTestHostBaseLib.h#L507)
|
---|
1342 | that can be used to substitute test functionality for any of the BaseLib functions. By default, this implementation
|
---|
1343 | will use the underlying BaseLib implementation, so the unit test writer only has to supply minimal code to test a
|
---|
1344 | particular case.
|
---|
1345 |
|
---|
1346 | ### Debugging the Framework Itself
|
---|
1347 |
|
---|
1348 | While most of the tests that are produced by the UnitTestFrameworkPkg are easy to step through in a debugger, the Framework
|
---|
1349 | itself consumes code (mostly Cmocka) that sets its own build flags. These flags cause parts of the Framework to not
|
---|
1350 | export symbols and captures exceptions, and as such are harder to debug. We have provided a Stuart parameter to force
|
---|
1351 | symbolic debugging to be enabled.
|
---|
1352 |
|
---|
1353 | You can run a build by adding the `BLD_*_UNIT_TESTING_DEBUG=TRUE` parameter to enable this build option.
|
---|
1354 |
|
---|
1355 | ```bash
|
---|
1356 | stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2019 -p MdePkg -t NOOPT BLD_*_UNIT_TESTING_DEBUG=TRUE
|
---|
1357 | ```
|
---|
1358 |
|
---|
1359 | ## Building and Running Host-Based Tests
|
---|
1360 |
|
---|
1361 | The EDK2 CI infrastructure provides a convenient way to run all host-based tests -- in the the entire tree or just
|
---|
1362 | selected packages -- and aggregate all the reports, including highlighting any failures. This functionality is
|
---|
1363 | provided through the Stuart build system (published by EDK2-PyTools) and the `NOOPT` build target. The sections that
|
---|
1364 | follow use Framework examples. Unit tests based on GoogleTest are built and run the same way. The text output and
|
---|
1365 | JUNIT XML output format have small differences.
|
---|
1366 |
|
---|
1367 | ### Building Locally
|
---|
1368 |
|
---|
1369 | First, to make sure you're working with the latest PyTools, run the following command:
|
---|
1370 |
|
---|
1371 | ```bash
|
---|
1372 | # Would recommend running this in a Python venv, but that's out of scope for this doc.
|
---|
1373 | python -m pip install --upgrade -r ./pip-requirements.txt
|
---|
1374 | ```
|
---|
1375 |
|
---|
1376 | After that, the following commands will set up the build and run the host-based tests.
|
---|
1377 |
|
---|
1378 | ```bash
|
---|
1379 | # Setup repo for building
|
---|
1380 | # stuart_setup -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=<GCC5, VS2019, etc.>
|
---|
1381 | stuart_setup -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=VS2019
|
---|
1382 |
|
---|
1383 | # Update all binary dependencies
|
---|
1384 | # stuart_update -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=<GCC5, VS2019, etc.>
|
---|
1385 | stuart_update -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=VS2019
|
---|
1386 |
|
---|
1387 | # Build and run the tests
|
---|
1388 | # stuart_ci_build -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=<GCC5, VS2019, etc.> -t NOOPT [-p <Package Name>]
|
---|
1389 | stuart_ci_build -c ./.pytool/CISettings.py TOOL_CHAIN_TAG=VS2019 -t NOOPT -p MdePkg
|
---|
1390 | ```
|
---|
1391 |
|
---|
1392 | ### Evaluating the Results
|
---|
1393 |
|
---|
1394 | In your immediate output, any build failures will be highlighted. You can see these below as "WARNING" and "ERROR" messages.
|
---|
1395 |
|
---|
1396 | ```text
|
---|
1397 | (edk_env) PS C:\_uefi\edk2> stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2019 -t NOOPT -p MdePkg
|
---|
1398 |
|
---|
1399 | SECTION - Init SDE
|
---|
1400 | SECTION - Loading Plugins
|
---|
1401 | SECTION - Start Invocable Tool
|
---|
1402 | SECTION - Getting Environment
|
---|
1403 | SECTION - Loading plugins
|
---|
1404 | SECTION - Building MdePkg Package
|
---|
1405 | PROGRESS - --Running MdePkg: Host Unit Test Compiler Plugin NOOPT --
|
---|
1406 | WARNING - Allowing Override for key TARGET_ARCH
|
---|
1407 | PROGRESS - Start time: 2020-07-27 17:18:08.521672
|
---|
1408 | PROGRESS - Setting up the Environment
|
---|
1409 | PROGRESS - Running Pre Build
|
---|
1410 | PROGRESS - Running Build NOOPT
|
---|
1411 | PROGRESS - Running Post Build
|
---|
1412 | SECTION - Run Host based Unit Tests
|
---|
1413 | SUBSECTION - Testing for architecture: X64
|
---|
1414 | WARNING - TestBaseSafeIntLibHost.exe Test Failed
|
---|
1415 | WARNING - Test SafeInt8ToUint8 - UT_ASSERT_EQUAL(0x5b:5b, Result:5c)
|
---|
1416 | c:\_uefi\edk2\MdePkg\Test\UnitTest\Library\BaseSafeIntLib\TestBaseSafeIntLib.c:35: error: Failure!
|
---|
1417 | ERROR - Plugin Failed: Host-Based Unit Test Runner returned 1
|
---|
1418 | CRITICAL - Post Build failed
|
---|
1419 | PROGRESS - End time: 2020-07-27 17:18:19.792313 Total time Elapsed: 0:00:11
|
---|
1420 | ERROR - --->Test Failed: Host Unit Test Compiler Plugin NOOPT returned 1
|
---|
1421 | ERROR - Overall Build Status: Error
|
---|
1422 | PROGRESS - There were 1 failures out of 1 attempts
|
---|
1423 | SECTION - Summary
|
---|
1424 | ERROR - Error
|
---|
1425 |
|
---|
1426 | (edk_env) PS C:\_uefi\edk2>
|
---|
1427 | ```
|
---|
1428 |
|
---|
1429 | If a test fails, you can run it manually to get more details...
|
---|
1430 |
|
---|
1431 | ```text
|
---|
1432 | (edk_env) PS C:\_uefi\edk2> .\Build\MdePkg\HostTest\NOOPT_VS2019\X64\TestBaseSafeIntLibHost.exe
|
---|
1433 |
|
---|
1434 | Int Safe Lib Unit Test Application v0.1
|
---|
1435 | ---------------------------------------------------------
|
---|
1436 | ------------ RUNNING ALL TEST SUITES --------------
|
---|
1437 | ---------------------------------------------------------
|
---|
1438 | ---------------------------------------------------------
|
---|
1439 | RUNNING TEST SUITE: Int Safe Conversions Test Suite
|
---|
1440 | ---------------------------------------------------------
|
---|
1441 | [==========] Running 71 test(s).
|
---|
1442 | [ RUN ] Test SafeInt8ToUint8
|
---|
1443 | [ ERROR ] --- UT_ASSERT_EQUAL(0x5b:5b, Result:5c)
|
---|
1444 | [ LINE ] --- c:\_uefi\edk2\MdePkg\Test\UnitTest\Library\BaseSafeIntLib\TestBaseSafeIntLib.c:35: error: Failure!
|
---|
1445 | [ FAILED ] Test SafeInt8ToUint8
|
---|
1446 | [ RUN ] Test SafeInt8ToUint16
|
---|
1447 | [ OK ] Test SafeInt8ToUint16
|
---|
1448 | [ RUN ] Test SafeInt8ToUint32
|
---|
1449 | [ OK ] Test SafeInt8ToUint32
|
---|
1450 | [ RUN ] Test SafeInt8ToUintn
|
---|
1451 | [ OK ] Test SafeInt8ToUintn
|
---|
1452 | ...
|
---|
1453 | ```
|
---|
1454 |
|
---|
1455 | You can also, if you are so inclined, read the output from the exact instance of the test that was run during
|
---|
1456 | `stuart_ci_build`. The output file can be found on a path that looks like:
|
---|
1457 |
|
---|
1458 | `Build/<Package>/HostTest/<Arch>/<TestName>.<TestSuiteName>.<Arch>.result.xml`
|
---|
1459 |
|
---|
1460 | A sample of this output looks like:
|
---|
1461 |
|
---|
1462 | ```xml
|
---|
1463 | <!--
|
---|
1464 | Excerpt taken from:
|
---|
1465 | Build\MdePkg\HostTest\NOOPT_VS2019\X64\TestBaseSafeIntLibHost.exe.Int Safe Conversions Test Suite.X64.result.xml
|
---|
1466 | -->
|
---|
1467 | <?xml version="1.0" encoding="UTF-8" ?>
|
---|
1468 | <testsuites>
|
---|
1469 | <testsuite name="Int Safe Conversions Test Suite" time="0.000" tests="71" failures="1" errors="0" skipped="0" >
|
---|
1470 | <testcase name="Test SafeInt8ToUint8" time="0.000" >
|
---|
1471 | <failure><![CDATA[UT_ASSERT_EQUAL(0x5c:5c, Result:5b)
|
---|
1472 | c:\_uefi\MdePkg\Test\UnitTest\Library\BaseSafeIntLib\TestBaseSafeIntLib.c:35: error: Failure!]]></failure>
|
---|
1473 | </testcase>
|
---|
1474 | <testcase name="Test SafeInt8ToUint16" time="0.000" >
|
---|
1475 | </testcase>
|
---|
1476 | <testcase name="Test SafeInt8ToUint32" time="0.000" >
|
---|
1477 | </testcase>
|
---|
1478 | <testcase name="Test SafeInt8ToUintn" time="0.000" >
|
---|
1479 | </testcase>
|
---|
1480 | ```
|
---|
1481 |
|
---|
1482 | ### XML Reporting Mode
|
---|
1483 |
|
---|
1484 | Unit test applications using Framework are built using Cmocka that requires the
|
---|
1485 | following environment variables to be set to generate structured XML output
|
---|
1486 | rather than text:
|
---|
1487 |
|
---|
1488 | ```
|
---|
1489 | CMOCKA_MESSAGE_OUTPUT=xml
|
---|
1490 | CMOCKA_XML_FILE=<absolute or relative path to output file>
|
---|
1491 | ```
|
---|
1492 |
|
---|
1493 | Unit test applications using GoogleTest require the following environment
|
---|
1494 | variable to be set to generate structured XML output rather than text:
|
---|
1495 |
|
---|
1496 | ```
|
---|
1497 | GTEST_OUTPUT=xml:<absolute or relative path to output file>
|
---|
1498 | ```
|
---|
1499 |
|
---|
1500 | This mode is used by the test running plugin to aggregate the results for CI test status reporting in the web view.
|
---|
1501 |
|
---|
1502 | ### Code Coverage
|
---|
1503 |
|
---|
1504 | Host based Unit Tests will automatically enable coverage data.
|
---|
1505 |
|
---|
1506 | For Windows, this is primarily leveraged for pipeline builds, but this can be leveraged locally using the
|
---|
1507 | OpenCppCoverage windows tool to parse coverage data to cobertura xml format.
|
---|
1508 |
|
---|
1509 | - Windows Prerequisite
|
---|
1510 | ```bash
|
---|
1511 | Download and install https://github.com/OpenCppCoverage/OpenCppCoverage/releases
|
---|
1512 | python -m pip install --upgrade -r ./pip-requirements.txt
|
---|
1513 | stuart_ci_build -c .pytool/CISettings.py -t NOOPT TOOL_CHAIN_TAG=VS2019 -p MdeModulePkg
|
---|
1514 | Open Build/coverage.xml
|
---|
1515 | ```
|
---|
1516 |
|
---|
1517 | - How to see code coverage data on IDE Visual Studio
|
---|
1518 | ```
|
---|
1519 | Open Visual Studio VS2019 or above version
|
---|
1520 | Click "Tools" -> "OpenCppCoverage Settings"
|
---|
1521 | Fill your execute file into "Program to run:"
|
---|
1522 | Click "Tools" -> "Run OpenCppCoverage"
|
---|
1523 | ```
|
---|
1524 |
|
---|
1525 |
|
---|
1526 | For Linux, this is primarily leveraged for pipeline builds, but this can be leveraged locally using the
|
---|
1527 | lcov linux tool, and parsed using the lcov_cobertura python tool to parse it to cobertura xml format.
|
---|
1528 |
|
---|
1529 | - Linux Prerequisite
|
---|
1530 | ```bash
|
---|
1531 | sudo apt-get install -y lcov
|
---|
1532 | python -m pip install --upgrade -r ./pip-requirements.txt
|
---|
1533 | stuart_ci_build -c .pytool/CISettings.py -t NOOPT TOOL_CHAIN_TAG=GCC5 -p MdeModulePkg
|
---|
1534 | Open Build/coverage.xml
|
---|
1535 | ```
|
---|
1536 | - How to see code coverage data on IDE Visual Studio Code
|
---|
1537 | ```
|
---|
1538 | Download plugin "Coverage Gutters"
|
---|
1539 | Press Hot Key "Ctrl + Shift + P" and click option "Coverage Gutters: Display Coverage"
|
---|
1540 | ```
|
---|
1541 |
|
---|
1542 |
|
---|
1543 | ### Important Note
|
---|
1544 |
|
---|
1545 | This works on both Windows and Linux but is currently limited to x64 architectures. Working on getting others, but we
|
---|
1546 | also welcome contributions.
|
---|
1547 |
|
---|
1548 | ## Framework Known Limitations
|
---|
1549 |
|
---|
1550 | ### PEI, DXE, SMM
|
---|
1551 |
|
---|
1552 | While sample tests have been provided for these execution environments, only cursory build validation
|
---|
1553 | has been performed. Care has been taken while designing the frameworks to allow for execution during
|
---|
1554 | boot phases, but only UEFI Shell and host-based tests have been thoroughly evaluated. Full support for
|
---|
1555 | PEI, DXE, and SMM is forthcoming, but should be considered beta/staging for now.
|
---|
1556 |
|
---|
1557 | ### Host-Based Support vs Other Tests
|
---|
1558 |
|
---|
1559 | The host-based test framework is powered internally by the Cmocka framework. As such, it has abilities
|
---|
1560 | that the target-based tests don't (yet). It would be awesome if this meant that it was a super set of
|
---|
1561 | the target-based tests, and it worked just like the target-based tests but with more features. Unfortunately,
|
---|
1562 | this is not the case. While care has been taken to keep them as close as possible, there are a few known
|
---|
1563 | inconsistencies that we're still ironing out. For example, the logging messages in the target-based tests
|
---|
1564 | are cached internally and associated with the running test case. They can be saved later as part of the
|
---|
1565 | reporting lib. This isn't currently possible with host-based. Only the assertion failures are logged.
|
---|
1566 |
|
---|
1567 | We will continue trying to make these as similar as possible.
|
---|
1568 |
|
---|
1569 | ## Unit Test Location/Layout Rules
|
---|
1570 |
|
---|
1571 | Code/Test | Location
|
---|
1572 | --------- | --------
|
---|
1573 | Host-Based Unit Tests for a Library/Protocol/PPI/GUID Interface | If what's being tested is an interface (e.g. a library with a public header file, like DebugLib) and the test is agnostic to a specific implementation, then the test should be scoped to the parent package.<br/>Example: `MdePkg/Test/UnitTest/[Library/Protocol/Ppi/Guid]/`<br/><br/>A real-world example of this is the BaseSafeIntLib test in MdePkg.<br/>`MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf`
|
---|
1574 | Host-Based Unit Tests for a Library/Driver (PEI/DXE/SMM) implementation | If what's being tested is a specific implementation (e.g. BaseDebugLibSerialPort for DebugLib), then the test should be scoped to the implementation directory itself, in a UnitTest (or GoogleTest) subdirectory.<br/><br/>Module Example: `MdeModulePkg/Universal/EsrtFmpDxe/UnitTest/`<br/>Library Example: `MdePkg/Library/BaseMemoryLib/UnitTest/`<br/>Library Example (GoogleTest): `SecurityPkg/Library/SecureBootVariableLib/GoogleTest/`
|
---|
1575 | Host-Based Tests for a Functionality or Feature | If you're writing a functional test that operates at the module level (i.e. if it's more than a single file or library), the test should be located in the package-level Tests directory under the HostFuncTest subdirectory.<br/>For example, if you were writing a test for the entire FMP Device Framework, you might put your test in:<br/>`FmpDevicePkg/Test/HostFuncTest/FmpDeviceFramework`<br/><br/>If the feature spans multiple packages, it's location should be determined by the package owners related to the feature.
|
---|
1576 | Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a Functionality or Feature | Similar to Host-Based, if the feature is in one package, should be located in the `*Pkg/Test/[Shell/Dxe/Smm/Pei]Test` directory.<br/><br/>If the feature spans multiple packages, it's location should be determined by the package owners related to the feature.<br/><br/>USAGE EXAMPLES<br/>PEI Example: MP_SERVICE_PPI. Or check MTRR configuration in a notification function.<br/> SMM Example: a test in a protocol callback function. (It is different with the solution that SmmAgent+ShellApp)<br/>DXE Example: a test in a UEFI event call back to check SPI/SMRAM status. <br/> Shell Example: the SMM handler audit test has a shell-based app that interacts with an SMM handler to get information. The SMM paging audit test gathers information about both DXE and SMM. And the SMM paging functional test actually forces errors into SMM via a DXE driver.
|
---|
1577 |
|
---|
1578 | ### Example Directory Tree
|
---|
1579 |
|
---|
1580 | ```text
|
---|
1581 | <PackageName>Pkg/
|
---|
1582 | ComponentY/
|
---|
1583 | ComponentY.inf
|
---|
1584 | ComponentY.c
|
---|
1585 | GoogleTest/
|
---|
1586 | ComponentYHostGoogleTest.inf # Host-Based Test for Driver Module
|
---|
1587 | ComponentYGoogleTest.cpp
|
---|
1588 | UnitTest/
|
---|
1589 | ComponentYHostUnitTest.inf # Host-Based Test for Driver Module
|
---|
1590 | ComponentYUnitTest.c
|
---|
1591 |
|
---|
1592 | Library/
|
---|
1593 | GeneralPurposeLibBase/
|
---|
1594 | ...
|
---|
1595 |
|
---|
1596 | GeneralPurposeLibSerial/
|
---|
1597 | ...
|
---|
1598 |
|
---|
1599 | SpecificLibDxe/
|
---|
1600 | SpecificLibDxe.c
|
---|
1601 | SpecificLibDxe.inf
|
---|
1602 | GoogleTest/ # Host-Based Test for Specific Library Implementation
|
---|
1603 | SpecificLibDxeHostGoogleTest.cpp
|
---|
1604 | SpecificLibDxeHostGoogleTest.inf
|
---|
1605 | UnitTest/ # Host-Based Test for Specific Library Implementation
|
---|
1606 | SpecificLibDxeHostUnitTest.c
|
---|
1607 | SpecificLibDxeHostUnitTest.inf
|
---|
1608 | Test/
|
---|
1609 | <Package>HostTest.dsc # Host-Based Test Apps
|
---|
1610 | GoogleTest/
|
---|
1611 | InterfaceX
|
---|
1612 | InterfaceXHostGoogleTest.inf # Host-Based App (should be in Test/<Package>HostTest.dsc)
|
---|
1613 | InterfaceXUnitTest.cpp # Test Logic
|
---|
1614 |
|
---|
1615 | GeneralPurposeLib/ # Host-Based Test for any implementation of GeneralPurposeLib
|
---|
1616 | GeneralPurposeLibTest.cpp
|
---|
1617 | GeneralPurposeLibHostUnitTest.inf
|
---|
1618 |
|
---|
1619 | UnitTest/
|
---|
1620 | InterfaceX
|
---|
1621 | InterfaceXHostUnitTest.inf # Host-Based App (should be in Test/<Package>HostTest.dsc)
|
---|
1622 | InterfaceXPeiUnitTest.inf # PEIM Target-Based Test (if applicable)
|
---|
1623 | InterfaceXDxeUnitTest.inf # DXE Target-Based Test (if applicable)
|
---|
1624 | InterfaceXSmmUnitTest.inf # SMM Target-Based Test (if applicable)
|
---|
1625 | InterfaceXShellUnitTest.inf # Shell App Target-Based Test (if applicable)
|
---|
1626 | InterfaceXUnitTest.c # Test Logic
|
---|
1627 |
|
---|
1628 | GeneralPurposeLib/ # Host-Based Test for any implementation of GeneralPurposeLib
|
---|
1629 | GeneralPurposeLibTest.c
|
---|
1630 | GeneralPurposeLibHostUnitTest.inf
|
---|
1631 |
|
---|
1632 | Mock/
|
---|
1633 | Include/
|
---|
1634 | GoogleTest/
|
---|
1635 | Library/
|
---|
1636 | MockGeneralPurposeLib.h
|
---|
1637 |
|
---|
1638 | Library/
|
---|
1639 | GoogleTest/
|
---|
1640 | MockGeneralPurposeLib/
|
---|
1641 | MockGeneralPurposeLib.cpp
|
---|
1642 | MockGeneralPurposeLib.inf
|
---|
1643 |
|
---|
1644 | <Package>Pkg.dsc # Standard Modules and any Target-Based Test Apps (including in Test/)
|
---|
1645 | ```
|
---|
1646 |
|
---|
1647 | ### Future Locations in Consideration
|
---|
1648 |
|
---|
1649 | We don't know if these types will exist or be applicable yet, but if you write a support library or module that matches the following, please make sure they live in the correct place.
|
---|
1650 |
|
---|
1651 | Code/Test | Location
|
---|
1652 | --------- | --------
|
---|
1653 | Host-Based Library Implementations | Host-Based Implementations of common libraries (eg. MemoryAllocationLibHost) should live in the same package that declares the library interface in its .DEC file in the `*Pkg/HostLibrary` directory. Should have 'Host' in the name.
|
---|
1654 | Host-Based Mocks and Stubs | Mock and Stub libraries should live in the `UefiTestFrameworkPkg/StubLibrary` with either 'Mock' or 'Stub' in the library name.
|
---|
1655 |
|
---|
1656 | ### If still in doubt...
|
---|
1657 |
|
---|
1658 | Hop on GitHub and ask @corthon, @mdkinney, or @spbrogan. ;)
|
---|
1659 |
|
---|
1660 | ## Copyright
|
---|
1661 |
|
---|
1662 | Copyright (c) Microsoft Corporation.
|
---|
1663 | SPDX-License-Identifier: BSD-2-Clause-Patent
|
---|