Debian Codegraph @

ansible_collections/cisco/aci/docs/testing_aci_modules.md

raw
1 **Table of Contents**
2
3 * [Testing the Module](#testing-the-module)
4 * [Creating a Playbook to test the module](#creating-a-playbook-to-test-the-module)
5 1. [Initial cleanup](#initial-cleanup)
6 2. [Setup if required](#setup-if-required)
7 3. [Create with minimum configuration (check/normal/idempotent)](#create-with-minimum-configuration-checknormalidempotent)
8 4. [Update with full configuration (check/normal/idempotent)](#update-with-full-configuration-checknormalidempotent)
9 5. [Additional update cases](#additional-update-cases)
10 6. [Additional create cases also used for query all](#additional-create-cases-also-used-for-query-all)
11 7. [Queries](#queries)
12 8. [Errors](#errors)
13 9. [Delete (check/normal/idempotent)](#delete-checknormalidempotent)
14 10. [Final cleanup](#final-cleanup)
15 * [Integration Test](#integration-test)
16 * [Sanity Test](#sanity-test)
17 * [Additional Tests](#additional-tests)
18 * [Coverage Report](#coverage-report)
19
20
21 # Testing the Module
22 Modules should be tested to make sure that it works for all states: present, absent, and query. The following section shows a basic and practical approach to building a **test playbook** with the help of a template. This makes it easier to complete the test file without having to write everything from scratch.
23
24 ### Creating a Playbook to test the module
25
26 > Use the contents of test playbook from the template [ACI playbook template: docs/sample_module/aci_test_playbook_template.md](sample_module/aci_test_playbook_template.md) as reference.
27
28 1. The **tests** directory of our collection includes the **integration** directory. The **integration** directory consists of **targets**, which has directories for all the test files of modules that currently exist in our collection. We go to the **targets** directory and copy the `aci_l3out_logical_node` directory, then paste it in the same directory as `aci_l3out_static_routes`, which should be the same as the name of our module. Upon opening the directory, we find the `main.yml` file. We open this file and make the following changes.
29
30 2. The copyright section should be changed to APIC's credentials.
31
32 ```yaml
33 # Copyright: (c) <year>, <Name> (@<github id>)
34 ```
35
36 3. The following section verifies that the ACI APIC host, ACI username, and ACI password are defined in the inventory. These will be used in every task of the test file. The inventory file is located in the inventory directory. More information on this directory is given below, after the test file.
37
38 ```yaml
39 - name: Test that we have an ACI APIC host, ACI username and ACI password
40 fail:
41 msg: 'Please define the following variables: aci_hostname, aci_username and aci_password.'
42 when: aci_hostname is not defined or aci_username is not defined or aci_password is not defined
43 ```
44
45 4. The next section should remain as is. `set_fact` stores the values of variables such as `aci_hostname`, `aci_username`, etc. in `&aci_info`. This will be referenced in all tasks.
46
47 ```yaml
48 # GET Credentials from the inventory
49 - name: Set vars
50 set_fact:
51 aci_info: &aci_info
52 host: "{{ aci_hostname }}"
53 username: "{{ aci_username }}"
54 password: "{{ aci_password }}"
55 validate_certs: '{{ aci_validate_certs | default(false) }}'
56 use_ssl: '{{ aci_use_ssl | default(true) }}'
57 use_proxy: '{{ aci_use_proxy | default(true) }}'
58 output_level: "{{ aci_output_level | default('info') }}"
59 ```
60
61 The test cases for the ACI modules follow a consistent pattern across operations such as Create, Update, Query, Query all, and Delete. For Create, Update, and Delete operations, the tests includes:
62
63 * `Check mode`: The check mode task to simulate the operation without making changes.
64 * `Normal mode`: The normal_mode task to perform the actual operation.
65 * `Idempotent`: The normal mode tasks to verify idempotency, ensuring that running the operation again does not cause changes.
66 * `Assert`: The assert tasks are then used to validate this registered output of the CRUD tasks against the expected configuration or state. This ensures that the module behaves as intended and that the changes are correctly applied or reflected.
67
68 This structured approach ensures thorough testing of the modules' functionality and stability in different modes and repeated executions.
69
70 Here's the structured approach for the `main.yml` test file:
71
72 1. **Initial cleanup**
73 * This section ensures a clean slate before tests begin. Any existing objects that might interfere with the test run are removed.
74
75 ```yaml
76 - name: Remove the ansible_tenant (initial cleanup)
77 aci_tenant:
78 <<: *aci_info
79 tenant: ansible_tenant
80 state: absent
81 ```
82
83 > **Note**: A cleanup section is included before we start testing to remove any existing objects, ensuring a clean state.
84
85 2. **Setup if required**
86 * This includes creating any necessary parent objects or dependencies that ACI module's object relies on.
87
88 ```yaml
89 - name: Add a new tenant (setup)
90 aci_tenant:
91 <<: *aci_info
92 tenant: ansible_tenant
93 description: Ansible tenant
94 state: present
95
96 - name: Add a new parent object (setup)
97 aci_l3out:
98 <<: *aci_info
99 tenant: ansible_tenant
100 name: '<parent_object_name>' # Replace <parent_object_name> with the actual name of the parent object, e.g., ansible_l3out
101 description: Parent object description
102 state: present
103 ```
104
105 3. **Create with minimum configuration (check/normal/idempotent)**
106 * Tasks to add a new object using only the required parameters.
107 * Each task will `register` its output for subsequent assertion.
108
109 ```yaml
110 - name: Add new object with min config (check mode)
111 your_module_name:
112 <<: *aci_info
113 # ... min required parameters ...
114 state: present
115 check_mode: true
116 register: result_min_check
117
118 - name: Add new object with min config (normal mode)
119 your_module_name:
120 <<: *aci_info
121 # ... min required parameters ...
122 state: present
123 register: result_min_actual
124
125 - name: Add new object with min config (idempotency)
126 your_module_name:
127 <<: *aci_info
128 # ... min required parameters ...
129 state: present
130 register: result_min_idempotency
131
132 - name: Assert new object with min config # Example assertion
133 assert:
134 that:
135 - result_min_check is changed == false
136 - result_min_check.msg == "Would have created/modified object."
137 - result_min_actual is changed == true
138 - result_min_actual.current.name == "expected_name"
139 - result_min_idempotency is changed == false
140 ```
141
142 4. **Update with full configuration (check/normal/idempotent)**
143 * Tasks to add or update an object using all available parameters.
144
145 ```yaml
146 - name: Update object with full config (check mode)
147 your_module_name:
148 <<: *aci_info
149 # ... all parameters ...
150 state: present
151 check_mode: true
152 register: result_full_check
153
154 - name: Update object with full config (normal mode)
155 your_module_name:
156 <<: *aci_info
157 # ... all parameters ...
158 state: present
159 register: result_full_actual
160
161 - name: Update object with full config (idempotency)
162 your_module_name:
163 <<: *aci_info
164 # ... all parameters ...
165 state: present
166 register: result_full_idempotency
167
168 - name: Assert update object with full config (idempotency)
169 assert:
170 that:
171 - result_full_check is changed == true # Expect change if updating
172 - result_full_check.msg == "Would have created/modified object."
173 - result_full_actual is changed == true
174 - result_full_actual.current.property == "expected_value"
175 - result_full_idempotency is changed == false
176 ```
177
178 5. **Additional update cases**
179 * Include specific scenarios for updating parameters, especially edge cases or conditional updates.
180
181 6. **Additional create cases also used for query all**
182 * Add more objects if needed to thoroughly test the "query all" functionality.
183
184 7. **Queries**
185 * **Query one**: Task to query a specific object.
186 * **Query all**: Task to query all objects of the module's class.
187 * Assert tasks to verify the correct data is returned.
188
189 ```yaml
190 - name: Query a particular object
191 your_module_name:
192 <<: *aci_info
193 # ... parameters to identify a single object ...
194 state: query
195 register: query_single_result
196
197 - name: Query all objects
198 your_module_name:
199 <<: *aci_info
200 state: query
201 register: query_all_result
202
203 - name: Assert query all objects
204 assert:
205 that:
206 - query_single_result.current is defined
207 - query_single_result.current.name == "expected_name"
208 - query_all_result.current is defined
209 - query_all_result.current | length > 0 # At least one object found
210 - query_all_result.current | selectattr('name', 'equalto', 'expected_name') | list | length == 1 # Verify specific object is in list
211 ```
212
213 8. **Errors**
214 * Tasks designed to trigger expected error conditions (e.g., missing required parameters, invalid values) and assert that the module fails gracefully with the correct error message.
215
216 9. **Delete (check/normal/idempotent)**
217 * Tasks to remove objects created during testing.
218
219 ```yaml
220 - name: Remove an object (check mode)
221 your_module_name:
222 <<: *aci_info
223 # ... parameters to identify object to delete ...
224 state: absent
225 check_mode: true
226 register: result_delete_check
227
228 - name: Remove an object (normal mode)
229 your_module_name:
230 <<: *aci_info
231 # ... parameters to identify object to delete ...
232 state: absent
233 register: result_delete_actual
234
235 - name: Remove an object (idempotency)
236 your_module_name:
237 <<: *aci_info
238 # ... parameters to identify object to delete ...
239 state: absent
240 register: result_delete_idempotency
241
242 - name: Assert remove object (idempotency)
243 assert:
244 that:
245 - result_delete_check is changed == true
246 - result_delete_check.msg == "Would have removed object."
247 - result_delete_actual is changed == true
248 - result_delete_actual.current is not defined # Object should no longer exist
249 - result_delete_idempotency is changed == false
250 ```
251
252 10. **Final cleanup**
253 * This section removes all objects created during the test run to leave the environment in a clean state. Removing the highest parent object (e.g., the tenant in most cases) is often sufficient, as it will cascade delete its children.
254
255 ```yaml
256 - name: Remove the ansible_tenant (final cleanup)
257 aci_tenant:
258 <<: *aci_info
259 tenant: ansible_tenant
260 state: absent
261 ```
262
263
264 ## Integration Test
265
266 ACI integration tests are end-to-end tests performed to check that the code path functions of our collection are working as expected.
267
268 Steps required to perform tests:
269 1. The test playbook created in `tests/integration/targets` directory
270 2. Update the inventory file with the credentials of the APIC in `ansible-aci -> tests -> integration -> inventory.networking`. Ansible uses an inventory file to keep track of which hosts are part of the APIC, and how to reach them for running commands and playbooks using credentials for the APIC.
271
272 ```ini
273 [aci]
274 <apic-label-name> ansible_host=<apic-host> ansible_connection=local aci_hostname=<apic-host>
275 aci_username=<apic-username> aci_password= <apic-password>
276 ```
277
278 2. Go to **ansible-aci** in the terminal and test the new module with the test playbook using the following commands. To make it easier to run all the commands in one go, we store the commands in a script and run the script.
279
280 ```text
281 rm -rf cisco-aci-*
282 ansible-galaxy collection build --force
283 ansible-galaxy collection install cisco-aci-* --force
284 cd ~/.ansible/collections/ansible_collections/cisco/aci
285 ansible-test network-integration --docker --color --truncate 0 -vvv --coverage aci_<ACI module name>
286 ```
287
288 * `ansible-galaxy collection build --force` builds a collection artifact that can be stored in a central repository. By default, this command builds from the current working directory, which in our case is ansible-aci.
289
290 * `ansible-galaxy collection install cisco-aci-* --force` installs the built collection in our current working directory, ansible-aci.
291
292 * `cd ~/.ansible/collections/ansible_collections/cisco/aci` changes our directory to aci, where tests are performed.
293
294 * `ansible-test network-integration --docker --color --truncate 0 -vvv --coverage aci_<ACI module name>` is used to run integration tests inside Docker. We can either run the integration test on one module or all the modules by omitting the name altogether.
295
296 ## Sanity Test
297
298 Sanity tests are performed on our module to make sure that it adheres to Ansible coding standards. A few examples include verifying whether our module's documentation is supported on all Python versions, and checking YAML files for syntax and formatting issues, etc.
299
300 Add the below line in the script to run sanity test:
301
302 ```text
303 ansible-test sanity --docker --color --truncate 0 -vvv --coverage aci_<ACI module name>
304 ```
305
306 * `ansible-test sanity --docker --color --truncate 0 -vvv --coverage aci_<ACI module name>` is used to run sanity tests inside Docker, which already has all the dependencies.
307
308 * The sanity task runs on Ubuntu with multiple Ansible versions in parallel, installing Python, Ansible base, coverage tool, and the Cisco ACI collection. It then executes the sanity tests with coverage enabled inside a Docker environment, generates a coverage XML report grouped by command and version, and finally uploads the coverage report to codecov.io.
309 * The sanity report verifies that the core functionalities of the Cisco ACI Ansible collection work correctly across multiple supported Ansible versions in a consistent environment.
310 * On any test failures or coverage regressions, the root cause should be investigated promptly by reviewing logs and error messages.
311 * Issues should be fixed or escalated as appropriate, and the sanity tests re-run to confirm resolution before further development or deployment.
312
313 This approach ensures that the collection remains stable and reliable across supported Ansible versions, with visibility into test completeness and quality.
314
315 ## Additional Tests
316
317 Additional tests are added to verify the formatting of the code, such as checking for trailing spaces, tabs, and other formatting issues. These tests can be found in the **workflows** -> **ansible-test.yml** file.
318 * **galaxy-importer**: a tool used within Ansible Galaxy to import and validate collections of Ansible content.
319 * **black**: a Python code formatter that enforces a consistent style. It automatically formats Python code to conform to the PEP 8 style guide.
320 * run the below black command before testing sanity.
321
322 ```text
323 black <path_to_file/file_name.py> -l 159
324 ```
325
326 ## Coverage Report
327
328 Code coverage reports are generated in HTML format and make it easy for us to identify untested code for which more tests should be written.
329
330 Steps required to perform tests:
331
332 ```text
333 ansible-test coverage report
334 ansible-test coverage html
335 open ~/.ansible/collections/ansible_collections/cisco/aci/tests/output/reports/coverage/index.html
336 ```
337
338 * We add the `--coverage` option to any test command to collect code coverage data:
339 1. `ansible-test coverage report`
340 2. `ansible-test coverage html`
341 3. `open ~/.ansible/collections/ansible_collections/cisco/aci/tests/output/reports/coverage/index.html`
342
343 * In the Ansible test coverage report generated by commands like `ansible-test coverage report` and `ansible-test coverage html`, the colors green, yellow, and red indicate the extent of code coverage for ACI modules:
344
345 * **Green**: Represents well-covered code sections where tests have executed the code paths. This indicates good test coverage and confidence in the tested code.
346 * **Yellow**: Indicates partial coverage or code that is executed but not fully tested. This suggests areas where tests could be improved or expanded.
347 * **Red**: Marks code that is not covered by any tests. These are gaps in testing that could lead to undetected bugs or issues.
348
349 > [!NOTE]
350 > The main() function, when guarded by if __name__ == "__main__":, is often skipped during module imports for testing, leading to its code not being executed by test suites. Consequently, if its specific execution path isn't explicitly invoked by tests, it can appear as uncovered in coverage reports.
351
352 > [!TIP]
353 > A common best practice is to aim for 100% coverage to ensure sufficient testing. While high coverage is desirable, 100% coverage is often not achievable due to untestable corner cases or environment constraints. It is important to still strive for coverage higher than 95% and to document any known gaps in testing.