Wiki source code of Docker-based Testing

Last modified by Vincent Massol on 2020/05/28 14:31

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 = Usage =
6
7 * Based on [[TestContainers>>https://www.testcontainers.org/]] and uses Docker to execute the tests under various Databases, Servlet Engines and Browsers.
8 ** [[Introductory talk about TestContainers and XWiki at Devoxx FR 2019>>https://youtu.be/0TvWv4L_IJM]] (In French)
9 * The only requirements for running these tests is to have Docker installed locally and to have the user under which you run your IDE and the Maven build be able to use the docker executable.
10 * Tests get injected ##XWikiWebDriver##, ##TestUtils##, ##TestInfo## and ##TestReference## instances as test method parameters.
11 * Test results is recording in a FLV file in the ##target## directory.
12 * A screenshot of the UI when the test is failing is also taken in the ##target## directory.
13 * When test execute it's possible to connect to the running VNC server and see the UI by using a VNC client and connect to the VNC URL printed in the console, e.g. ##vnc:~/~/vnc:[email protected]:32936##.
14 ** Note that if you want to debug and interact with the XWiki UI you should use a ##servletEngine## other than the default Jetty Standalone one since otherwise the debug point in your IDE will prevent the XWiki code from executing and you'll see a spinning wheel until you step forward in your debugger. You can use for example ##servletEngine = ServletEngine.TOMCAT##.
15 * The version for the platform dependencies is specified using the ##platform.version## property in the ##pom.xml## file executing the tests.
16 * The test configuration options can be accessed from tests by specifying a method parameter of type ##TestConfiguration## (see examples below).
17 ** You can get access to the IP address/port to use to connect to XWiki from the host machine: ##testConfiguration.getServletEngine().getIP()/getPort()##
18 ** You can get access to the IP address to use to connect to the host machine from inside XWiki: ##testConfiguration.getServletEngine().getHostIP()##
19 ** You can get access to the IP address/port used internally by XWiki (for example to generate URLs): ##testConfiguration.getServletEngine().getInternalIP()/getInternalPort()##
20
21 = Configurations options =
22
23 {{info}}
24 Note:
25 * When passing as Java annotation attributes, in functional tests, the format is ##@UITest(<Option Name> = <Value>)##
26 * When passing the options as System Properties, the format is ##-Dxwiki.test.ui.<Option Name>=<Value>##
27 ** Except for passing ##properties## where the format is ##-Dxwiki.test.ui.properties.<Property name>=<Property Value>##
28 ** Except for ##extraJARs##, ##sshPorts## & ##forbiddenServletEngines## which cannot be set from System Properties.
29 ** Except for passing ##databaseCommands## where the format is ##-Dxwiki.test.ui.database.commands.<Command name>=<Command Value>##
30 * System properties have priority over Java annotation attributes
31 * The ##xwiki.test.ui.dependencies## configuration value can only be passed as a system property.
32 {{/info}}
33
34 (% style="overflow-x: auto;" %)
35 (((
36 |=Option Name|=Default Value|=Valid Values|=Description
37 |##browser##|##firefox##|(((
38 * ##firefox## (##Browser.FIREFOX##)
39 * ##chrome## (##Browser.CHROME##)
40 )))|The browser used in the tests. Note that the version of the browser used is controlled by the version of Selenium that is defined in the ##pom.xml## of ##xwiki-platform-test-docker##.
41 |##database##|##hsqldb_embedded##|(((
42 * ##mysql## (##Database.MYSQL##)
43 * ##postgresql## (##Database.POSTGRESQL##)
44 * ##hsqldb_embedded## (##Database.HSQLDB_EMBEDDED##)
45 * ##oracle DB## (##Database.ORACLE##)
46 )))|The database used in the tests. Available tags are those listed on the Dockerhub page for the database image used. Note: for Oracle, we only have Oracle 11g Release 2.
47 |##servletEngine##|##jetty_standalone##|(((
48 * ##tomcat## (##ServletEngine.TOMCAT##)
49 * ##jetty## (##ServletEngine.JETTY##)
50 * ##jetty_standalone## (##ServletEngine.JETTY_STANDALONE##)
51 * ##external## (##ServletEngine.EXTERNAL##)
52 )))|The Servlet Engine used in the tests. Use ##external## to use your own started and alreayd provisioned XWiki instance.
53 |##verbose##|##false##|(((
54 * ##true##
55 * ##false##
56 )))|When active, displays more logs in the console (especially container startup logs)
57 |##debug##|##false##|(((
58 * ##true##
59 * ##false##
60 )))|When active, starts XWiki in debug mode when using the "Jetty Standalone" and Tomcat Servlet Engines (and starts it with suspend on, i.e. wait for the remote debugger to connect to it before progressing, to make it easy to debug XWiki's server side). You can then attach a remote debugger. Since Tomcat runs in a Docker container, you'll need to do a ##docker ps## to find the local mapped port corresponding to port 5005 and then use ##localhost## as the JVM host name.
61 |##saveDatabaseData##|##false##|(((
62 * ##true##
63 * ##false##
64 )))|By default, database data is not saved between test executions. {{warning}}Note that if you decide to save database data, they'll be saved under a ##docker## user by Docker and you need your local user to be able to remove them if you want to clean your Maven ##target## directory.{{/warning}}
65 |##offline##|##false##|(((
66 * ##true##
67 * ##false##
68 )))|When offline, the custom XWiki WAR generation and the XWiki provisioning are done solely from your local Maven repository. Otherwise, when artifacts are not present locally or newer SNAPSHOT versions are available, they'll be fetched from Maven remote repositories. Moreover no docker pull check is performed in offline mode.
69 |##databaseTag##|[[Latest supported version by XWiki>>Community.DatabaseSupportStrategy]]|Any Docker tag available from Dockerhub for the container image|Version of the database to use. Isn't supported for HSQLDB Embedded since it doesn't run in a Docker container.
70 |##servletEngineTag##|[[Latest supported version by XWiki>>Community.ServletContainerSupportStrategy.WebHome]]|Any Docker tag available from Dockerhub for the container image|Version of the Servlet Engine to use. Isn't supported for Jetty Standalone since it doesn't run in a Docker container.
71 |##jdbcDriverVersion##|Latest version validated by the XWiki dev team|Any version for the specified database that is available on Maven Central, e.g. for MySQL the groupId/artifactId is ##mysql##/##mysql-connector-java##.|
72 |##vnc##|##true##|(((
73 * ##true##
74 * ##false##
75 )))|When active a VNC container is started to record a video of the tests and more generally to allow connecting to the UI running the tests. Useful when debugging.
76 |##properties##|No default (empty)|Check the ##*.vm## files for the configuration files to see the list of possible values.|(% style="word-break: break-all;" %)Velocity properties that are applied when generating XWiki's configuration files: ##xwiki.cfg##, ##xwiki.properties## and ##hibernate.cfg.xml##. Example: Tell XWiki that minification is off: ##-Dxwiki.test.ui.properties.xwikiPropertiesAdditionalProperties=debug.minify=false## or ##@UITest(properties = { "xwikiPropertiesAdditionalProperties=debug.minify=false" })##. Note that the ##xwikiCfgPlugins## property will be merged with the default values unless you start the new property value with the ##^## character.
77 |##extraJARs##|No default (empty)|Comma-separated list of ##<groupId>:<artifactId>## or ##<groupId>:<artifactId>:<version>##|(% style="word-break: break-all;" %)There are cases where the module being tested cannot be fully deployed as an extension into a running XWiki and it needs to deploy one or several JARs into ##WEB-INF/lib##. One such example is when an extension includes a Hibernate HBM file, as right now only HBM files located in JARs in ##WEB-INF/lib## are supported. Note that when the version is not specified the current POM's version is used.
78 |##sshPorts##|No default (empty)|List of integers|The list of ports that should be SSH-forwarded when connecting from a Docker container to the host (i.e. when using the ##host.testcontainers.internal##. This is in addition to port ##8080## which is always added. For example if you need XWiki to send a mail to a SMTP server running on port 3025 on the host, you should add port 3025 to the list.
79 |##profiles##|No default (empty)|Comma-separated list of Maven profile ids|When specified the defined profiles are active when resolving dependencies from the current POM.
80 |##forbiddenServletEngines##|No default (empty)|List of ##ServletEngine##s enums|List of Servlet Engines for which the tests will be skipped (usually because they'd fail on them).
81 |##databaseProperties##|No default (empty)|See Docker documentation for the target image|List of database docker commands to use and that will override default commands (example of command ##character-set-server=utf8mb4## which will translate into ##~-~-character-set-server=utf8mb4## at runtime).
82 |##dependencies##|No default (empty)|Comma-separated list of Maven coordinates|List artifacts that will be provisioned in the running XWiki instance. When specified then current pom.xml dependencies are not used to find out what to provision. This can be used for example in cases when you don't want to use project dependencies in order to not draw older version of dependencies (such as when you need to run functional docker-based tests in a specific more recent vesion of XWiki than the one used to build the code). Accepted format is ##groupId:artifactId##, ##groupId:artifactId:version## and ##groupId:artifactId:type:version##. {{info}}Since 11.2RC1{{/info}}.
83 |##extensionOverrides##|No default (empty)|List Extension Manager overrides|See example below for the format. {{info}}Since 11.6RC1{{/info}}.
84
85 = Examples =
86
87 == Full Examples ==
88
89 * {{scm path="xwiki-platform-core/xwiki-platform-menu/xwiki-platform-menu-test/xwiki-platform-menu-test-docker/src/test/it/org/xwiki/menu/test/ui/MenuIT.java"}}MenuIT{{/scm}}
90 * {{scm path="xwiki-platform-core/xwiki-platform-mail/xwiki-platform-mail-test/xwiki-platform-mail-test-docker/src/test/it/org/xwiki/mail/test/ui/MailIT.java"}}MailIT{{/scm}}
91
92 == Example 1: Basic test ==
93
94 {{code language="java"}}
95 @UITest
96 public class SeleniumTest
97 {
98 @Test
99 public void test(XWikiWebDriver driver, TestUtils setup)
100 {
101 driver.get("http://xwiki.org");
102 assertThat(driver.getTitle(),
103 containsString("XWiki - The Advanced Open Source Enterprise and Application Wiki"));
104 driver.findElement(By.linkText("XWiki's concept")).click();
105 }
106 }
107 {{/code}}
108
109 == Example 2: Choosing Container + DB + Browser and versions ==
110
111 {{code language="java"}}
112 @UITest(database = Database.MYSQL, databaseTag = "5", servletEngine = ServletEngine.TOMCAT, servletEngineTag = "8",
113 browser = Browser.CHROME)
114 public class MenuIT
115 ...
116 {{/code}}
117
118 {{code language="java"}}
119 @UITest(database = Database.POSTGRESQL, databaseTag = "9", servletEngine = ServletEngine.JETTY,
120 servletEngineTag = "9", browser = Browser.CHROME)
121 public class MenuIT
122 ...
123 {{/code}}
124
125 {{code language="java"}}
126 @UITest(database = Database.HSQLDB_EMBEDDED, servletEngine = ServletEngine.JETTY_STANDALONE,
127 browser = Browser.FIREFOX)
128 public class MenuIT
129 ...
130 {{/code}}
131
132 == Example 3: Test using Greenmail + Hibernate HBM ==
133
134 {{code language="java"}}
135 @UITest(sshPorts = {
136 3025
137 },
138 properties = {
139 "xwikiDbHbmCommonExtraMappings=mailsender.hbm.xml",
140 // Pages created in the tests need to have PR since we ask for PR to send mails so we need to exclude them from
141 // the PR checker.
142 "xwikiPropertiesAdditionalProperties=test.prchecker.excludePattern=.*:MailIT\\..*"
143 },
144 extraJARs = {
145 "org.xwiki.platform:xwiki-platform-mail-send-storage"
146 }
147 )
148 public class MailIT
149 ...
150 {{/code}}
151
152 == Example 4: Passing Test Configuration ==
153
154 {{code language="java"}}
155 @Test
156 public void verifyMail(TestUtils setup, XWikiWebDriver webDriver, TestConfiguration testConfiguration)
157 throws Exception
158 {
159 ....
160 }
161 {{/code}}
162
163 == Example 5: Specifying explictly dependencies ==
164
165 Example of deploying a ##1.10-SNAPSHOT## version of ##org.xwiki.contrib.latex:latex-export## (and its dependencies) into a ##11.2-SNAPSHOT## version of XWiki. In this example the POM of ##org.xwiki.contrib.latex:latex-export## depends on XWiki 10.2. Thus this example demonstrates running the tests in a more recent version of XWiki than the code was built on.
166
167 {{code language="xml"}}
168 ...
169 <parent>
170 <groupId>org.xwiki.platform</groupId>
171 <artifactId>xwiki-platform</artifactId>
172 <version>11.2-SNAPSHOT</version>
173 </parent>
174 <groupId>org.xwiki.contrib.latex</groupId>
175 <artifactId>latex-test</artifactId>
176 <version>1.10-SNAPSHOT</version>
177 ...
178 <plugin>
179 <groupId>org.apache.maven.plugins</groupId>
180 <artifactId>maven-failsafe-plugin</artifactId>
181 <configuration>
182 <includes>
183 <include>**/AllIT.java</include>
184 </includes>
185 <systemProperties>
186 <xwiki.test.ui.dependencies>org.xwiki.contrib.latex:latex-export</xwiki.test.ui.dependencies>
187 </systemProperties>
188 </configuration>
189 </plugin>
190 {{/code}}
191
192 == Example 6: Passing extension overrides ==
193
194 The following tells the Extension Manager to use the existing core extension ##com.google.code.findbugs:annotations## whenever the extension ##com.google.code.findbugs:jsr305## is requested.
195
196 {{code language="java"}}
197 @UITest(extensionOverrides = {
198 @ExtensionOverride(
199 extensionId = "com.google.code.findbugs:jsr305",
200 overrides = {
201 "features=com.google.code.findbugs:annotations"
202 }
203 )
204 })
205 ...
206 {{/code}}
207
208 Note that in the XWikio build, these extension overrides are defined in the top level XWiki Platform POM and for this specific case it's defined as:
209
210 {{code language='xml'}}
211 ...
212 <extensionOverride>
213 <id>com.google.code.findbugs:jsr305</id>
214 <features>com.google.code.findbugs:annotations</features>
215 </extensionOverride>
216 ...
217 {{/code}}
218
219 Another example:
220
221 {{code language="java"}}
222 ...
223 extensionOverrides = {
224 @ExtensionOverride(
225 extensionId = "org.xwiki.platform:xwiki-platform-web",
226 overrides = {
227 // We set a default UI for the subwiki in the webapp, so that the Wiki Creation UI knows which extension
228 // to install on a subwiki by default (which is something we test)
229 // Otherwise the wiki creation form will display the flavor picker and the functional tests do not handle it.
230 "properties=xwiki.extension.distribution.wikiui=org.xwiki.platform:xwiki-platform-wiki-ui-wiki"
231 }
232 )
233 }
234 ...
235 {{/code}}
236
237 = Best Practices =
238
239 == Scenarios ==
240
241 Always use scenarios and use JUnit5's ##@Order(...)## annotation. For example:
242
243 {{code}}
244 @UITest
245 public class MenuIT
246 {
247 @Test
248 @Order(1)
249 public void verifyMenuInApplicationsIndex(TestUtils setup)
250 {
251 ...
252 }
253
254 @Test
255 @Order(2)
256 public void verifyMenuCreationInLeftPanelWithCurrentWikiVisibility(TestUtils setup)
257 {
258 ...
259 }
260
261 @Test
262 @Order(3)
263 public void verifyMenuIsAvailableInAdministration(TestUtils setup) throws Exception
264 {
265 ...
266 }
267 }
268 {{/code}}
269
270 == Suites ==
271
272 Use JUnit5's ##@Nested## annotation. For example:
273
274 {{code}}
275 @UITest(...)
276 public class AllIT
277 {
278 @Nested
279 @DisplayName("Office Import Tests")
280 class NestedOfficeImporterIT extends OfficeImporterIT
281 {
282 }
283
284 @Nested
285 @DisplayName("Office Export Tests")
286 class NestedOfficeExportIT extends OfficeExportIT
287 {
288 }
289 }
290 {{/code}}
291
292 == Test Reference ==
293
294 A lot of tests need to create a wiki page for testing. Example to do this:
295
296 {{code language="java"}}
297 @Test
298 public void showAndHideEditComments(TestUtils setup, TestReference reference) throws Exception
299 {
300 ViewPage vp = setup.gotoPage(reference);
301 ...
302 {{/code}}
303
304 More generic way (more verbose but can useful in some cases) using JUnit5's ##TestInfo## class:
305
306 {{code language="java"}}
307 public class MailIT
308 {
309 private String testClassName;
310
311 @BeforeEach
312 public void setUp(TestInfo info)
313 {
314 this.testClassName = info.getTestClass().get().getSimpleName();
315 }
316 ...
317 }
318 {{/code}}
319
320 == Docker out of Docker ==
321
322 The [[XWiki's CI>>https://ci.xwiki.org]] is using a [[Jenkins Agent Docker image>>https://github.com/xwiki/xwiki-jenkins-slave]] to execute the job builds. Thus, the Docker-based functional tests spawn Docker containers (using TestContainers) that execute inside Docker. This is the pattern called DOOD (Docker out of Docker). See [[TC's best practice>>https://www.testcontainers.org/supported_docker_environment/continuous_integration/dind_patterns/]] about this.
323
324 There are some consequences when writing tests for XWiki:
325 * Never use volume mapping or it won't execute fine. This is because that would require the Jenkins Agent Docker container to have that volume mapping defined too and the mapping would need to use the exact host path and container path. So, in short, it won't work. Instead copy files that you need to have in the container. Adn copy file out if need be. Here's an example from the LaTeX extension on how to achieve this:(((
326 {{code language="java"}}
327 try (GenericContainer container = new GenericContainer("blang/latex:ubuntu")) {
328 // Note: we copy files instead of mounting volumes so that this can work when using DOOD
329 // (Docker out of Docker).
330 MountableFile mountableDirectory = MountableFile.forHostPath("target/latex");
331 container.withCopyFileToContainer(mountableDirectory, "/data");
332
333 container.withCommand("/bin/sh", "-c", "sleep infinity");
334 container.withLogConsumer(new Slf4jLogConsumer(LOGGER));
335 container.start();
336 Container.ExecResult result = container.execInContainer("pdflatex", "-shell-escape", "index.tex");
337 String stdout = result.getStdout();
338 LOGGER.info(stdout);
339 assertTrue(stdout.contains("Output written on index.pdf"));
340
341 container.copyFileFromContainer("/data/index.pdf", "target/latex/index.pdf");
342 }
343 {{/code}}
344 )))
345
346 == Stdout/stderr validation errors ==
347
348 We have a [[check>>Community.Building.WebHome||anchor="HAutomaticChecks"]] that verifies if functional tests output some invalid content to stdout/stderr. If your test contains such errors it'll fail and then you have 3 options:
349 * It's a normal and expected output from the test (for ex the test verifies an error condition and it's expected it will raise a stack trace in the console). In this case add an expectation in the test. For example:(((
350 {{code language='java'}}
351 public void wrongTemplate(LogCaptureConfiguration logCaptureConfiguration)
352 {
353 ...
354 logCaptureConfiguration.registerExpected( "Possible break-in attempt!",
355 "Error getting resource [null]");
356 }
357 {{/code}}
358 )))
359 * It's a non-expected error. You then have 2 sub-choices:
360 ** Fix the problem (the best and recommended solution!)
361 ** Increase the technical debt by adding an exclude. For example:(((
362 {{code language='java'}}
363 logCaptureConfiguration.registerExcludes(
364 "java.lang.IllegalStateException: Response is committed");
365 {{/code}}
366 )))
367
368 = Test Resources =
369
370 You might need test resources to be used in interaction with the wiki (e.g. to upload an attachment). Any test resources placed in ##src/test/resources## is made automatically available to the browser container by mounting the dedicated volume mapped to ##target/test-classes##. Then, in your test, you can use the dedicated method to get access to the files located in ##target/test-classes##.
371
372 For example:
373
374 {{code language="java"}}
375 String resourceDirPath = testConfiguration.getBrowser().getTestResourcesPath();
376 File myResourceFile = new File(resourceDirPath, filename);
377 {{/code}}
378
379 = Test Coverage =
380
381 Activate support for Clover by setting the ##xwiki.test.ui.profiles## property in the ##clover## profile in the ##pom.xml## file for the test.
382
383 Example:
384
385 {{code language="xml"}}
386 <profiles>
387 <profile>
388 <id>clover</id>
389 <!-- Add the Clover JAR to the WAR so that it's available at runtime when XWiki executes.
390 It's needed because instrumented jars in the WAR will call Clover APIs at runtime when they execute. -->
391 <dependencies>
392 <dependency>
393 <groupId>org.openclover</groupId>
394 <artifactId>clover</artifactId>
395 </dependency>
396 </dependencies>
397 <build>
398 <plugins>
399 <plugin>
400 <groupId>org.apache.maven.plugins</groupId>
401 <artifactId>maven-failsafe-plugin</artifactId>
402 <configuration>
403 <systemProperties combine.children="append">
404 <!-- Tell the Docker-based test to activate the Clover profile so that the Clover JAR is added to
405 WEB-INF/lib -->
406 <property>
407 <name>xwiki.test.ui.profiles</name>
408 <value>clover</value>
409 </property>
410 </systemProperties>
411 </configuration>
412 </plugin>
413 ...
414 {{/code}}
415
416 = Existing XWiki instance =
417
418 If you want to avoid the Docker-based tests to start and stop XWiki every time you re-run the tests (for example when you're developping/debugging something), you can tell the Docker Test framework to not provision an XWiki instance and to use your XWiki instance instead.
419
420 This is achieved by specifying {{code}}@UITest(servletEngine = ServletEngine.EXTERNAL){{/code}} or passing the {{code}}xwiki.test.ui.servletEngine=external{{/code}} system property.
421
422 A common use case is to debug a failing test. Here's what you can do:
423
424 {{code language="none"}}
425 ## Run the test once to see if it fails and to generate the XWiki instance. This may take some time.
426 > mvn clean install -Dit.test=NavigationPanelIT
427 ## Open a new console, look for the generated XWiki instance inside the target folder and start it.
428 ../target/../jetty > start_xwiki.sh
429 ## Modify the test as needed then go back to the initial console and compile the tests.
430 ## Note that you may also need to build the page objects module if you change those too.
431 > mvn compiler:testCompile
432 ## Then run the test again to see the changes. This should be way faster than the initial test run.
433 > mvn surefire:test -Dxwiki.test.ui.servletEngine=external -Dtest=NavigationPanelIT
434 {{/code}}
435
436 = Architecture =
437
438 {{image reference="xwiki-testcontainers.png"/}}
439 //See [[Vincent's blog>>https://massol.myxwiki.org/xwiki/bin/view/Blog/EnvironmentTestingExperimentations#HExperimentation5:inJavaTestsusingTestContainers]] for more details//
440 )))
441
442 = CI Jobs =
443
444 There are 3 CI jobs executing Docker-based functional tests:
445
446 * [[Job 1>>https://ci.xwiki.org/view/Recommended%20Builds/job/xwiki-platform_docker/]]: run all tests on latest versions of supported configs.
447 * [[Job 2>>https://ci.xwiki.org/view/Recommended%20Builds/job/xwiki-platform_docker_all/]]: run smoke tests (ie a few tests only) on all supported configs.
448 * [[Job 3>>https://ci.xwiki.org/view/Recommended%20Builds/job/xwiki-platform_docker_unsupported/]]: run smoke tests on unsupported configs (MySQL 8.x, Tomcat 9.x, etc) that we want to support in the future.
449
450 Configuration definitions and job sources are all {{scm project="xwiki-jenkins-pipeline" path="src/org/xwiki/jenkins/DockerTests.groovy"}}here{{/scm}}.

Get Connected