TESTING.asciidoc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. [[TestingFrameworkCheatsheet]]
  2. = Testing
  3. [partintro]
  4. Elasticsearch uses JUnit for testing. It also generated random inputs into
  5. tests, either using a random seed, or one that is set via a system
  6. property. The following is a cheatsheet of options for running the
  7. Elasticsearch tests.
  8. == Creating packages
  9. To build a distribution for your local OS and print its output location upon completion, run:
  10. -----------------------------
  11. ./gradlew localDistro
  12. -----------------------------
  13. To create a platform-specific build, use the following depending on your
  14. operating system:
  15. -----------------------------
  16. ./gradlew :distribution:archives:linux-tar:assemble
  17. ./gradlew :distribution:archives:darwin(-aarch64)-tar:assemble
  18. ./gradlew :distribution:archives:windows-zip:assemble
  19. -----------------------------
  20. You can build a Docker image with:
  21. -----------------------------
  22. ./gradlew build(Aarch64)DockerImage
  23. -----------------------------
  24. Note: you almost certainly don't want to run `./gradlew assemble` as this
  25. will attempt build every single Elasticsearch distribtion.
  26. === Running Elasticsearch from a checkout
  27. In order to run Elasticsearch from source without building a package, you can
  28. run it using Gradle:
  29. -------------------------------------
  30. ./gradlew run
  31. -------------------------------------
  32. ==== Launching and debugging from an IDE
  33. If you want to run Elasticsearch from your IDE, the `./gradlew run` task
  34. supports a remote debugging option:
  35. ---------------------------------------------------------------------------
  36. ./gradlew run --debug-jvm
  37. ---------------------------------------------------------------------------
  38. This will instruct all JVMs (including any that run cli tools such as creating the keyring or adding users)
  39. to suspend and initiate a debug connection on port incrementing from `5005`.
  40. As such the IDE needs to be instructed to listen for connections on this port.
  41. Since we might run multiple JVMs as part of configuring and starting the cluster it's
  42. recommended to configure the IDE to initiate multiple listening attempts. In case of IntelliJ, this option
  43. is called "Auto restart" and needs to be checked. In case of Eclipse, "Connection limit" setting
  44. needs to be configured with a greater value (ie 10 or more).
  45. NOTE: If you have imported the project into IntelliJ according to the instructions in
  46. link:/CONTRIBUTING.md#importing-the-project-into-intellij-idea[CONTRIBUTING.md] then a debug run configuration
  47. named "Debug Elasticsearch" will be created for you and configured appropriately.
  48. ==== Disabling assertions
  49. When running Elasticsearch with `./gradlew run`, assertions are enabled by
  50. default. To disable them, add the following command line option:
  51. -------------------------
  52. -Dtests.jvm.argline="-da"
  53. -------------------------
  54. ==== Distribution
  55. By default a node is started with the zip distribution.
  56. In order to start with a different distribution use the `-Drun.distribution` argument.
  57. To for example start the open source distribution:
  58. -------------------------------------
  59. ./gradlew run -Drun.distribution=oss
  60. -------------------------------------
  61. ==== License type
  62. By default a node is started with the `basic` license type.
  63. In order to start with a different license type use the `-Drun.license_type` argument.
  64. In order to start a node with a trial license execute the following command:
  65. -------------------------------------
  66. ./gradlew run -Drun.license_type=trial
  67. -------------------------------------
  68. This enables security and other paid features and adds a superuser with the username: `elastic-admin` and
  69. password: `elastic-password`.
  70. ==== Other useful arguments
  71. - In order to start a node with a different max heap space add: `-Dtests.heap.size=4G`
  72. - In order to use a custom data directory: `--data-dir=/tmp/foo`
  73. - In order to preserve data in between executions: `--preserve-data`
  74. - In order to remotely attach a debugger to the process: `--debug-jvm`
  75. - In order to set a different keystore password: `--keystore-password`
  76. - In order to set an Elasticsearch setting, provide a setting with the following prefix: `-Dtests.es.`
  77. - In order to pass a JVM seting, e.g. to disable assertions: `-Dtests.jvm.argline="-da"`
  78. === Test case filtering.
  79. You can run a single test, provided that you specify the Gradle project. See the documentation on
  80. https://docs.gradle.org/current/userguide/userguide_single.html#simple_name_pattern[simple name pattern filtering].
  81. Run a single test case in the `server` project:
  82. ----------------------------------------------------------
  83. ./gradlew :server:test --tests org.elasticsearch.package.ClassName
  84. ----------------------------------------------------------
  85. Run all tests in a package and its sub-packages:
  86. ----------------------------------------------------
  87. ./gradlew :server:test --tests 'org.elasticsearch.package.*'
  88. ----------------------------------------------------
  89. Run all tests that are waiting for a bugfix (disabled by default)
  90. ------------------------------------------------
  91. ./gradlew test -Dtests.filter=@awaitsfix
  92. ------------------------------------------------
  93. === Seed and repetitions.
  94. Run with a given seed (seed is a hex-encoded long).
  95. ------------------------------
  96. ./gradlew test -Dtests.seed=DEADBEEF
  97. ------------------------------
  98. === Repeats _all_ tests of ClassName N times.
  99. Every test repetition will have a different method seed
  100. (derived from a single random master seed).
  101. --------------------------------------------------
  102. ./gradlew :server:test -Dtests.iters=N --tests org.elasticsearch.package.ClassName
  103. --------------------------------------------------
  104. === Repeats _all_ tests of ClassName N times.
  105. Every test repetition will have exactly the same master (0xdead) and
  106. method-level (0xbeef) seed.
  107. ------------------------------------------------------------------------
  108. ./gradlew :server:test -Dtests.iters=N -Dtests.seed=DEAD:BEEF --tests org.elasticsearch.package.ClassName
  109. ------------------------------------------------------------------------
  110. === Repeats a given test N times
  111. (note the filters - individual test repetitions are given suffixes,
  112. ie: testFoo[0], testFoo[1], etc... so using testmethod or tests.method
  113. ending in a glob is necessary to ensure iterations are run).
  114. -------------------------------------------------------------------------
  115. ./gradlew :server:test -Dtests.iters=N --tests org.elasticsearch.package.ClassName.methodName
  116. -------------------------------------------------------------------------
  117. Repeats N times but skips any tests after the first failure or M initial failures.
  118. -------------------------------------------------------------
  119. ./gradlew test -Dtests.iters=N -Dtests.failfast=true ...
  120. ./gradlew test -Dtests.iters=N -Dtests.maxfailures=M ...
  121. -------------------------------------------------------------
  122. === Test groups.
  123. Test groups can be enabled or disabled (true/false).
  124. Default value provided below in [brackets].
  125. ------------------------------------------------------------------
  126. ./gradlew test -Dtests.awaitsfix=[false] - known issue (@AwaitsFix)
  127. ------------------------------------------------------------------
  128. === Load balancing and caches.
  129. By default the tests run on multiple processes using all the available cores on all
  130. available CPUs. Not including hyper-threading.
  131. If you want to explicitly specify the number of JVMs you can do so on the command
  132. line:
  133. ----------------------------
  134. ./gradlew test -Dtests.jvms=8
  135. ----------------------------
  136. Or in `~/.gradle/gradle.properties`:
  137. ----------------------------
  138. systemProp.tests.jvms=8
  139. ----------------------------
  140. Its difficult to pick the "right" number here. Hypercores don't count for CPU
  141. intensive tests and you should leave some slack for JVM-internal threads like
  142. the garbage collector. And you have to have enough RAM to handle each JVM.
  143. === Test compatibility.
  144. It is possible to provide a version that allows to adapt the tests behaviour
  145. to older features or bugs that have been changed or fixed in the meantime.
  146. -----------------------------------------
  147. ./gradlew test -Dtests.compatibility=1.0.0
  148. -----------------------------------------
  149. === Miscellaneous.
  150. Run all tests without stopping on errors (inspect log files).
  151. -----------------------------------------
  152. ./gradlew test -Dtests.haltonfailure=false
  153. -----------------------------------------
  154. Run more verbose output (slave JVM parameters, etc.).
  155. ----------------------
  156. ./gradlew test -verbose
  157. ----------------------
  158. Change the default suite timeout to 5 seconds for all
  159. tests (note the exclamation mark).
  160. ---------------------------------------
  161. ./gradlew test -Dtests.timeoutSuite=5000! ...
  162. ---------------------------------------
  163. Change the logging level of ES (not Gradle)
  164. --------------------------------
  165. ./gradlew test -Dtests.es.logger.level=DEBUG
  166. --------------------------------
  167. Print all the logging output from the test runs to the commandline
  168. even if tests are passing.
  169. ------------------------------
  170. ./gradlew test -Dtests.output=always
  171. ------------------------------
  172. Configure the heap size.
  173. ------------------------------
  174. ./gradlew test -Dtests.heap.size=512m
  175. ------------------------------
  176. Pass arbitrary jvm arguments.
  177. ------------------------------
  178. # specify heap dump path
  179. ./gradlew test -Dtests.jvm.argline="-XX:HeapDumpPath=/path/to/heapdumps"
  180. # enable gc logging
  181. ./gradlew test -Dtests.jvm.argline="-verbose:gc"
  182. # enable security debugging
  183. ./gradlew test -Dtests.jvm.argline="-Djava.security.debug=access,failure"
  184. ------------------------------
  185. Pass build arguments.
  186. ------------------------------
  187. # Run tests against a release build. License key must be provided, but usually can be anything.
  188. ./gradlew test -Dbuild.snapshot=false -Dlicense.key="x-pack/license-tools/src/test/resources/public.key"
  189. ------------------------------
  190. == Running verification tasks
  191. To run all verification tasks, including static checks, unit tests, and integration tests:
  192. ---------------------------------------------------------------------------
  193. ./gradlew check
  194. ---------------------------------------------------------------------------
  195. Note that this will also run the unit tests and precommit tasks first. If you want to just
  196. run the in memory cluster integration tests (because you are debugging them):
  197. ---------------------------------------------------------------------------
  198. ./gradlew internalClusterTest
  199. ---------------------------------------------------------------------------
  200. If you want to just run the precommit checks:
  201. ---------------------------------------------------------------------------
  202. ./gradlew precommit
  203. ---------------------------------------------------------------------------
  204. Some of these checks will require `docker-compose` installed for bringing up
  205. test fixtures. If it's not present those checks will be skipped automatically.
  206. The host running Docker (or VM if you're using Docker Desktop) needs 4GB of
  207. memory or some of the containers will fail to start. You can tell that you
  208. are short of memory if containers are exiting quickly after starting with
  209. code 137 (128 + 9, where 9 means SIGKILL).
  210. == Debugging tests
  211. If you would like to debug your tests themselves, simply pass the `--debug-jvm`
  212. flag to the testing task and connect a debugger on the default port of `5005`.
  213. ---------------------------------------------------------------------------
  214. ./gradlew :server:test --debug-jvm
  215. ---------------------------------------------------------------------------
  216. For REST tests, if you'd like to debug the Elasticsearch server itself, and
  217. not your test code, use the `--debug-server-jvm` flag and use the
  218. "Debug Elasticsearch" run configuration in IntelliJ to listen on the default
  219. port of `5007`.
  220. ---------------------------------------------------------------------------
  221. ./gradlew :rest-api-spec:yamlRestTest --debug-server-jvm
  222. ---------------------------------------------------------------------------
  223. NOTE: In the case of test clusters using multiple nodes, multiple debuggers
  224. will need to be attached on incrementing ports. For example, for a 3 node
  225. cluster ports `5007`, `5008`, and `5009` will attempt to attach to a listening
  226. debugger.
  227. You can also use a combination of both flags to debug both tests and server.
  228. This is only applicable to Java REST tests.
  229. ---------------------------------------------------------------------------
  230. ./gradlew :modules:kibana:javaRestTest --debug-jvm --debug-server-jvm
  231. ---------------------------------------------------------------------------
  232. == Testing the REST layer
  233. The REST layer is tested through specific tests that are executed against
  234. a cluster that is configured and initialized via Gradle. The tests
  235. themselves can be written in either Java or with a YAML based DSL.
  236. YAML based REST tests should be preferred since these are shared between all
  237. the elasticsearch official clients. The YAML based tests describe the
  238. operations to be executed and the obtained results that need to be tested.
  239. The YAML tests support various operators defined in the link:/rest-api-spec/src/yamlRestTest/resources/rest-api-spec/test/README.asciidoc[rest-api-spec] and adhere to the link:/rest-api-spec/README.markdown[Elasticsearch REST API JSON specification]
  240. In order to run the YAML tests, the relevant API specification needs
  241. to be on the test classpath. Any gradle project that has support for REST
  242. tests will get the primary API on it's class path. However, to better support
  243. Gradle incremental builds, it is recommended to explicitly declare which
  244. parts of the API the tests depend upon.
  245. For example:
  246. ---------------------------------------------------------------------------
  247. restResources {
  248. restApi {
  249. includeCore '_common', 'indices', 'index', 'cluster', 'nodes', 'get', 'ingest'
  250. }
  251. }
  252. ---------------------------------------------------------------------------
  253. YAML REST tests that include x-pack specific APIs need to explicitly declare
  254. which APIs are required through a similar `includeXpack` configuration.
  255. The REST tests are run automatically when executing the "./gradlew check" command. To run only the
  256. YAML REST tests use the following command (modules and plugins may also include YAML REST tests):
  257. ---------------------------------------------------------------------------
  258. ./gradlew :rest-api-spec:yamlRestTest
  259. ---------------------------------------------------------------------------
  260. A specific test case can be run with the following command:
  261. ---------------------------------------------------------------------------
  262. ./gradlew ':rest-api-spec:yamlRestTest' \
  263. --tests "org.elasticsearch.test.rest.ClientYamlTestSuiteIT" \
  264. -Dtests.method="test {yaml=cat.segments/10_basic/Help}"
  265. ---------------------------------------------------------------------------
  266. The YAML REST tests support all the options provided by the randomized runner, plus the following:
  267. * `tests.rest.suite`: comma separated paths of the test suites to be run
  268. (by default loaded from /rest-api-spec/test). It is possible to run only a subset
  269. of the tests providing a sub-folder or even a single yaml file (the default
  270. /rest-api-spec/test prefix is optional when files are loaded from classpath)
  271. e.g. -Dtests.rest.suite=index,get,create/10_with_id
  272. * `tests.rest.blacklist`: comma separated globs that identify tests that are
  273. blacklisted and need to be skipped
  274. e.g. -Dtests.rest.blacklist=index/*/Index document,get/10_basic/*
  275. Java REST tests can be run with the "javaRestTest" task.
  276. For example :
  277. ---------------------------------------------------------------------------
  278. ./gradlew :modules:mapper-extras:javaRestTest
  279. ---------------------------------------------------------------------------
  280. A specific test case can be run with the following syntax (fqn.test {params}):
  281. ---------------------------------------------------------------------------
  282. ./gradlew ':modules:mapper-extras:javaRestTest' \
  283. --tests "org.elasticsearch.index.mapper.TokenCountFieldMapperIntegrationIT.testSearchByTokenCount {storeCountedFields=true loadCountedFields=false}"
  284. ---------------------------------------------------------------------------
  285. yamlRestTest's and javaRestTest's are easy to identify, since they are found in a
  286. respective source directory. However, there are some more specialized REST tests
  287. that use custom task names. These are usually found in "qa" projects commonly
  288. use the "integTest" task.
  289. If in doubt about which command to use, simply run <gradle path>:check
  290. == Testing packaging
  291. The packaging tests use Vagrant virtual machines or cloud instances to verify
  292. that installing and running Elasticsearch distributions works correctly on
  293. supported operating systems. These tests should really only be run on ephemeral
  294. systems because they're destructive; that is, these tests install and remove
  295. packages and freely modify system settings, so you will probably regret it if
  296. you execute them on your development machine.
  297. When you run a packaging test, Gradle will set up the target VM and mount your
  298. repository directory in the VM. Once this is done, a Gradle task will issue a
  299. Vagrant command to run a *nested* Gradle task on the VM. This nested Gradle
  300. runs the actual "destructive" test classes.
  301. . Install Virtual Box and Vagrant.
  302. +
  303. . (Optional) Install https://github.com/fgrehm/vagrant-cachier[vagrant-cachier] to squeeze
  304. a bit more performance out of the process:
  305. +
  306. --------------------------------------
  307. vagrant plugin install vagrant-cachier
  308. --------------------------------------
  309. +
  310. . You can run all of the OS packaging tests with `./gradlew packagingTest`.
  311. This task includes our legacy `bats` tests. To run only the OS tests that are
  312. written in Java, run `.gradlew distroTest`, will cause Gradle to build the tar,
  313. zip, and deb packages and all the plugins. It will then run the tests on every
  314. available system. This will take a very long time.
  315. +
  316. Fortunately, the various systems under test have their own Gradle tasks under
  317. `qa/os`. To find the systems tested, do a listing of the `qa/os` directory.
  318. To find out what packaging combinations can be tested on a system, run
  319. the `tasks` task. For example:
  320. +
  321. ----------------------------------
  322. ./gradlew :qa:os:ubuntu-1804:tasks
  323. ----------------------------------
  324. +
  325. If you want a quick test of the tarball and RPM packagings for Centos 7, you
  326. would run:
  327. +
  328. -------------------------------------------------------------------------------------------------
  329. ./gradlew :qa:os:centos-7:distroTest.default-rpm :qa:os:centos-7:distroTest.default-linux-archive
  330. -------------------------------------------------------------------------------------------------
  331. Note that if you interrupt Gradle in the middle of running these tasks, any boxes started
  332. will remain running and you'll have to stop them manually with `./gradlew --stop` or
  333. `vagrant halt`.
  334. All the regular vagrant commands should just work so you can get a shell in a
  335. VM running trusty by running
  336. `vagrant up ubuntu-1804 --provider virtualbox && vagrant ssh ubuntu-1804`.
  337. === Testing packaging on Windows
  338. The packaging tests also support Windows Server 2012R2 and Windows Server 2016.
  339. Unfortunately we're not able to provide boxes for them in open source use
  340. because of licensing issues. Any Virtualbox image that has WinRM and Powershell
  341. enabled for remote users should work.
  342. Specify the image IDs of the Windows boxes to gradle with the following project
  343. properties. They can be set in `~/.gradle/gradle.properties` like
  344. ------------------------------------
  345. vagrant.windows-2012r2.id=my-image-id
  346. vagrant.windows-2016.id=another-image-id
  347. ------------------------------------
  348. or passed on the command line like `-Pvagrant.windows-2012r2.id=my-image-id`
  349. `-Pvagrant.windows-2016=another-image-id`
  350. These properties are required for Windows support in all gradle tasks that
  351. handle packaging tests. Either or both may be specified.
  352. If you're running vagrant commands outside of gradle, specify the Windows boxes
  353. with the environment variables
  354. * `VAGRANT_WINDOWS_2012R2_BOX`
  355. * `VAGRANT_WINDOWS_2016_BOX`
  356. === Testing VMs are disposable
  357. It's important to think of VMs like cattle. If they become lame you just shoot
  358. them and let vagrant reprovision them. Say you've hosed your precise VM:
  359. ----------------------------------------------------
  360. vagrant ssh ubuntu-1604 -c 'sudo rm -rf /bin'; echo oops
  361. ----------------------------------------------------
  362. All you've got to do to get another one is
  363. ----------------------------------------------
  364. vagrant destroy -f ubuntu-1604 && vagrant up ubuntu-1604 --provider virtualbox
  365. ----------------------------------------------
  366. The whole process takes a minute and a half on a modern laptop, two and a half
  367. without vagrant-cachier.
  368. Its possible that some downloads will fail and it'll be impossible to restart
  369. them. This is a bug in vagrant. See the instructions here for how to work
  370. around it:
  371. https://github.com/mitchellh/vagrant/issues/4479
  372. Some vagrant commands will work on all VMs at once:
  373. ------------------
  374. vagrant halt
  375. vagrant destroy -f
  376. ------------------
  377. `vagrant up` would normally start all the VMs but we've prevented that because
  378. that'd consume a ton of ram.
  379. === Iterating on packaging tests
  380. Because our packaging tests are capable of testing many combinations of OS
  381. (e.g., Windows, Linux, etc.), package type (e.g., zip file, RPM, etc.),
  382. Elasticsearch distribution type (e.g., default or OSS), and so forth, it's
  383. faster to develop against smaller subsets of the tests. For example, to run
  384. tests for the default archive distribution on Fedora 28:
  385. -----------------------------------------------------------
  386. ./gradlew :qa:os:fedora-28:distroTest.default-linux-archive
  387. -----------------------------------------------------------
  388. These test tasks can use the `--tests`, `--info`, and `--debug` parameters just like
  389. non-OS tests can. For example:
  390. -----------------------------------------------------------
  391. ./gradlew :qa:os:fedora-28:distroTest.default-linux-archive \
  392. --tests "com.elasticsearch.packaging.test.ArchiveTests"
  393. -----------------------------------------------------------
  394. == Testing backwards compatibility
  395. Backwards compatibility tests exist to test upgrading from each supported version
  396. to the current version. To run them all use:
  397. -------------------------------------------------
  398. ./gradlew bwcTest
  399. -------------------------------------------------
  400. A specific version can be tested as well. For example, to test bwc with
  401. version 5.3.2 run:
  402. -------------------------------------------------
  403. ./gradlew v5.3.2#bwcTest
  404. -------------------------------------------------
  405. Use -Dtests.class and -Dtests.method to run a specific bwcTest test.
  406. For example to run a specific tests from the x-pack rolling upgrade from 7.7.0:
  407. -------------------------------------------------
  408. ./gradlew :x-pack:qa:rolling-upgrade:v7.7.0#bwcTest \
  409. -Dtests.class=org.elasticsearch.upgrades.UpgradeClusterClientYamlTestSuiteIT \
  410. -Dtests.method="test {p0=*/40_ml_datafeed_crud/*}"
  411. -------------------------------------------------
  412. Tests are ran for versions that are not yet released but with which the current version will be compatible with.
  413. These are automatically checked out and built from source.
  414. See link:./build-tools-internal/src/main/java/org/elasticsearch/gradle/BwcVersions.java[BwcVersions]
  415. and link:./distribution/bwc/build.gradle[distribution/bwc/build.gradle]
  416. for more information.
  417. When running `./gradlew check`, minimal bwc checks are also run against compatible versions that are not yet released.
  418. ==== BWC Testing against a specific remote/branch
  419. Sometimes a backward compatibility change spans two versions. A common case is a new functionality
  420. that needs a BWC bridge in an unreleased versioned of a release branch (for example, 5.x).
  421. To test the changes, you can instruct Gradle to build the BWC version from a another remote/branch combination instead of
  422. pulling the release branch from GitHub. You do so using the `bwc.remote` and `bwc.refspec.BRANCH` system properties:
  423. -------------------------------------------------
  424. ./gradlew check -Dbwc.remote=${remote} -Dbwc.refspec.5.x=index_req_bwc_5.x
  425. -------------------------------------------------
  426. The branch needs to be available on the remote that the BWC makes of the
  427. repository you run the tests from. Using the remote is a handy trick to make
  428. sure that a branch is available and is up to date in the case of multiple runs.
  429. Example:
  430. Say you need to make a change to `master` and have a BWC layer in `5.x`. You
  431. will need to:
  432. . Create a branch called `index_req_change` off your remote `${remote}`. This
  433. will contain your change.
  434. . Create a branch called `index_req_bwc_5.x` off `5.x`. This will contain your bwc layer.
  435. . Push both branches to your remote repository.
  436. . Run the tests with `./gradlew check -Dbwc.remote=${remote} -Dbwc.refspec.5.x=index_req_bwc_5.x`.
  437. ==== Skip fetching latest
  438. For some BWC testing scenarios, you want to use the local clone of the
  439. repository without fetching latest. For these use cases, you can set the system
  440. property `tests.bwc.git_fetch_latest` to `false` and the BWC builds will skip
  441. fetching the latest from the remote.
  442. == Testing in FIPS 140-2 mode
  443. We have a CI matrix job that periodically runs all our tests with the JVM configured
  444. to be FIPS 140-2 compliant with the use of the BouncyCastle FIPS approved Security Provider.
  445. FIPS 140-2 imposes certain requirements that affect how our tests should be set up or what
  446. can be tested. This section summarizes what one needs to take into consideration so that
  447. tests won't fail when run in fips mode.
  448. === Muting tests in FIPS 140-2 mode
  449. If the following limitations cannot be observed, or there is a need to actually test some use
  450. case that is not available/allowed in fips mode, the test can be muted. For unit tests or Java
  451. rest tests one can use
  452. ------------------------------------------------
  453. assumeFalse("Justification why this cannot be run in FIPS mode", inFipsJvm());
  454. ------------------------------------------------
  455. For specific YAML rest tests one can use
  456. ------------------------------------------------
  457. - skip:
  458. features: fips_140
  459. reason: "Justification why this cannot be run in FIPS mode"
  460. ------------------------------------------------
  461. For disabling entire types of tests for subprojects, one can use for example:
  462. ------------------------------------------------
  463. if (BuildParams.inFipsJvm){
  464. // This test cluster is using a BASIC license and FIPS 140 mode is not supported in BASIC
  465. tasks.named("javaRestTest").configure{enabled = false }
  466. }
  467. ------------------------------------------------
  468. in `build.gradle`.
  469. === Limitations
  470. The following should be taken into consideration when writing new tests or adjusting existing ones:
  471. ==== TLS
  472. `JKS` and `PKCS#12` keystores cannot be used in FIPS mode. If the test depends on being able to use
  473. a keystore, it can be muted when needed ( see `ESTestCase#inFipsJvm` ). Alternatively, one can use
  474. PEM encoded files for keys and certificates for the tests or for setting up TLS in a test cluster.
  475. Also, when in FIPS 140 mode, hostname verification for TLS cannot be turned off so if you are using
  476. `*.verification_mode: none` , you'd need to mute the test in fips mode.
  477. When using TLS, ensure that private keys used are longer than 2048 bits, or mute the test in fips mode.
  478. ==== Password hashing algorithm
  479. Test clusters are configured with `xpack.security.fips_mode.enabled` set to true. This means that
  480. FIPS 140-2 related bootstrap checks are enabled and the test cluster will fail to form if the
  481. password hashing algorithm is set to something else than a PBKDF2 based one. You can delegate the choice
  482. of algorithm to i.e. `SecurityIntegTestCase#getFastStoredHashAlgoForTests` if you don't mind the
  483. actual algorithm used, or depend on default values for the test cluster nodes.
  484. ==== Password length
  485. While using `pbkdf2` as the password hashing algorithm, FIPS 140-2 imposes a requirement that
  486. passwords are longer than 14 characters. You can either ensure that all test user passwords in
  487. your test are longer than 14 characters and use i.e. `SecurityIntegTestCase#getFastStoredHashAlgoForTests`
  488. to randomly select a hashing algorithm, or use `pbkdf2_stretch` that doesn't have the same
  489. limitation.
  490. ==== Keystore Password
  491. In FIPS 140-2 mode, the elasticsearch keystore needs to be password protected with a password
  492. of appropriate length. This is handled automatically in `fips.gradle` and the keystore is unlocked
  493. on startup by the test clusters tooling in order to have secure settings available. However, you
  494. might need to take into consideration that the keystore is password-protected with `keystore-password`
  495. if you need to interact with it in a test.
  496. == How to write good tests?
  497. === Base classes for test cases
  498. There are multiple base classes for tests:
  499. * **`ESTestCase`**: The base class of all tests. It is typically extended
  500. directly by unit tests.
  501. * **`ESSingleNodeTestCase`**: This test case sets up a cluster that has a
  502. single node.
  503. * **`ESIntegTestCase`**: An integration test case that creates a cluster that
  504. might have multiple nodes.
  505. * **`ESRestTestCase`**: An integration tests that interacts with an external
  506. cluster via the REST API. This is used for Java based REST tests.
  507. * **`ESClientYamlSuiteTestCase` **: A subclass of `ESRestTestCase` used to run
  508. YAML based REST tests.
  509. === Good practices
  510. ==== What kind of tests should I write?
  511. Unit tests are the preferred way to test some functionality: most of the time
  512. they are simpler to understand, more likely to reproduce, and unlikely to be
  513. affected by changes that are unrelated to the piece of functionality that is
  514. being tested.
  515. The reason why `ESSingleNodeTestCase` exists is that all our components used to
  516. be very hard to set up in isolation, which had led us to having a number of
  517. integration tests but close to no unit tests. `ESSingleNodeTestCase` is a
  518. workaround for this issue which provides an easy way to spin up a node and get
  519. access to components that are hard to instantiate like `IndicesService`.
  520. Whenever practical, you should prefer unit tests.
  521. Many tests extend `ESIntegTestCase`, mostly because this is how most tests used
  522. to work in the early days of Elasticsearch. However the complexity of these
  523. tests tends to make them hard to debug. Whenever the functionality that is
  524. being tested isn't intimately dependent on how Elasticsearch behaves as a
  525. cluster, it is recommended to write unit tests or REST tests instead.
  526. In short, most new functionality should come with unit tests, and optionally
  527. REST tests to test integration.
  528. ==== Refactor code to make it easier to test
  529. Unfortunately, a large part of our code base is still hard to unit test.
  530. Sometimes because some classes have lots of dependencies that make them hard to
  531. instantiate. Sometimes because API contracts make tests hard to write. Code
  532. refactors that make functionality easier to unit test are encouraged. If this
  533. sounds very abstract to you, you can have a look at
  534. https://github.com/elastic/elasticsearch/pull/16610[this pull request] for
  535. instance, which is a good example. It refactors `IndicesRequestCache` in such
  536. a way that:
  537. - it no longer depends on objects that are hard to instantiate such as
  538. `IndexShard` or `SearchContext`,
  539. - time-based eviction is applied on top of the cache rather than internally,
  540. which makes it easier to assert on what the cache is expected to contain at
  541. a given time.
  542. === Bad practices
  543. ==== Use randomized-testing for coverage
  544. In general, randomization should be used for parameters that are not expected
  545. to affect the behavior of the functionality that is being tested. For instance
  546. the number of shards should not impact `date_histogram` aggregations, and the
  547. choice of the `store` type (`niofs` vs `mmapfs`) does not affect the results of
  548. a query. Such randomization helps improve confidence that we are not relying on
  549. implementation details of one component or specifics of some setup.
  550. However it should not be used for coverage. For instance if you are testing a
  551. piece of functionality that enters different code paths depending on whether
  552. the index has 1 shards or 2+ shards, then we shouldn't just test against an
  553. index with a random number of shards: there should be one test for the 1-shard
  554. case, and another test for the 2+ shards case.
  555. ==== Abuse randomization in multi-threaded tests
  556. Multi-threaded tests are often not reproducible due to the fact that there is
  557. no guarantee on the order in which operations occur across threads. Adding
  558. randomization to the mix usually makes things worse and should be done with
  559. care.
  560. == Test coverage analysis
  561. Generating test coverage reports for Elasticsearch is currently not possible through Gradle.
  562. However, it _is_ possible to gain insight in code coverage using IntelliJ's built-in coverage
  563. analysis tool that can measure coverage upon executing specific tests. Eclipse may also be able
  564. to do the same using the EclEmma plugin.
  565. Test coverage reporting used to be possible with JaCoCo when Elasticsearch was using Maven
  566. as its build system. Since the switch to Gradle though, this is no longer possible, seeing as
  567. the code currently used to build Elasticsearch does not allow JaCoCo to recognize its tests.
  568. For more information on this, see the discussion in https://github.com/elastic/elasticsearch/issues/28867[issue #28867].
  569. ---------------------------------------------------------------------------
  570. Read your IDE documentation for how to attach a debugger to a JVM process.
  571. == Building with extra plugins
  572. Additional plugins may be built alongside elasticsearch, where their
  573. dependency on elasticsearch will be substituted with the local elasticsearch
  574. build. To add your plugin, create a directory called elasticsearch-extra as
  575. a sibling of elasticsearch. Checkout your plugin underneath elasticsearch-extra
  576. and the build will automatically pick it up. You can verify the plugin is
  577. included as part of the build by checking the projects of the build.
  578. ---------------------------------------------------------------------------
  579. ./gradlew projects
  580. ---------------------------------------------------------------------------
  581. == Environment misc
  582. There is a known issue with macOS localhost resolve strategy that can cause
  583. some integration tests to fail. This is because integration tests have timings
  584. for cluster formation, discovery, etc. that can be exceeded if name resolution
  585. takes a long time.
  586. To fix this, make sure you have your computer name (as returned by `hostname`)
  587. inside `/etc/hosts`, e.g.:
  588. ....
  589. 127.0.0.1 localhost ElasticMBP.local
  590. 255.255.255.255 broadcasthost
  591. ::1 localhost ElasticMBP.local`
  592. ....
  593. == Benchmarking
  594. For changes that might affect the performance characteristics of Elasticsearch
  595. you should also run macrobenchmarks. We maintain a macrobenchmarking tool
  596. called https://github.com/elastic/rally[Rally]
  597. which you can use to measure the performance impact. It comes with a set of
  598. default benchmarks that we also
  599. https://elasticsearch-benchmarks.elastic.co/[run every night]. To get started,
  600. please see https://esrally.readthedocs.io/en/stable/[Rally's documentation].
  601. == Test doc builds
  602. The Elasticsearch docs are in AsciiDoc format. You can test and build the docs
  603. locally using the Elasticsearch documentation build process. See
  604. https://github.com/elastic/docs.