TESTING.asciidoc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. [[TestingFrameworkCheatsheet]]
  2. = Testing
  3. [partintro]
  4. Elasticsearch uses jUnit for testing, it also uses randomness in the
  5. tests, that can be set using a seed, the following is a cheatsheet of
  6. options for running the tests for ES.
  7. == Creating packages
  8. To create a distribution without running the tests, simply run the
  9. following:
  10. -----------------------------
  11. ./gradlew assemble
  12. -----------------------------
  13. To create a platform-specific build including the x-pack modules, use the
  14. following depending on your operating system:
  15. -----------------------------
  16. ./gradlew :distribution:archives:linux-tar:assemble --parallel
  17. ./gradlew :distribution:archives:darwin-tar:assemble --parallel
  18. ./gradlew :distribution:archives:windows-zip:assemble --parallel
  19. -----------------------------
  20. === Running Elasticsearch from a checkout
  21. In order to run Elasticsearch from source without building a package, you can
  22. run it using Gradle:
  23. -------------------------------------
  24. ./gradlew run
  25. -------------------------------------
  26. ==== Launching and debugging from an IDE
  27. If you want to run Elasticsearch from your IDE, the `./gradlew run` task
  28. supports a remote debugging option:
  29. ---------------------------------------------------------------------------
  30. ./gradlew run --debug-jvm
  31. ---------------------------------------------------------------------------
  32. ==== Distribution
  33. By default a node is started with the zip distribution.
  34. In order to start with a different distribution use the `-Drun.distribution` argument.
  35. To for example start the open source distribution:
  36. -------------------------------------
  37. ./gradlew run -Drun.distribution=oss
  38. -------------------------------------
  39. ==== License type
  40. By default a node is started with the `basic` license type.
  41. In order to start with a different license type use the `-Drun.license_type` argument.
  42. In order to start a node with a trial license execute the following command:
  43. -------------------------------------
  44. ./gradlew run -Drun.license_type=trial
  45. -------------------------------------
  46. This enables security and other paid features and adds a superuser with the username: `elastic-admin` and
  47. password: `elastic-password`.
  48. ==== Other useful arguments
  49. In order to start a node with a different max heap space add: `-Dtests.heap.size=4G`
  50. In order to disable annotations add: `-Dtests.asserts=false`
  51. In order to set an Elasticsearch setting, provide a setting with the following prefix: `-Dtests.es.`
  52. === Test case filtering.
  53. - `tests.class` is a class-filtering shell-like glob pattern,
  54. - `tests.method` is a method-filtering glob pattern.
  55. Run a single test case (variants)
  56. ----------------------------------------------------------
  57. ./gradlew test -Dtests.class=org.elasticsearch.package.ClassName
  58. ./gradlew test "-Dtests.class=*.ClassName"
  59. ----------------------------------------------------------
  60. Run all tests in a package and its sub-packages
  61. ----------------------------------------------------
  62. ./gradlew test "-Dtests.class=org.elasticsearch.package.*"
  63. ----------------------------------------------------
  64. Run any test methods that contain 'esi' (like: ...r*esi*ze...)
  65. -------------------------------
  66. ./gradlew test "-Dtests.method=*esi*"
  67. -------------------------------
  68. Run all tests that are waiting for a bugfix (disabled by default)
  69. ------------------------------------------------
  70. ./gradlew test -Dtests.filter=@awaitsfix
  71. ------------------------------------------------
  72. === Seed and repetitions.
  73. Run with a given seed (seed is a hex-encoded long).
  74. ------------------------------
  75. ./gradlew test -Dtests.seed=DEADBEEF
  76. ------------------------------
  77. === Repeats _all_ tests of ClassName N times.
  78. Every test repetition will have a different method seed
  79. (derived from a single random master seed).
  80. --------------------------------------------------
  81. ./gradlew test -Dtests.iters=N -Dtests.class=*.ClassName
  82. --------------------------------------------------
  83. === Repeats _all_ tests of ClassName N times.
  84. Every test repetition will have exactly the same master (0xdead) and
  85. method-level (0xbeef) seed.
  86. ------------------------------------------------------------------------
  87. ./gradlew test -Dtests.iters=N -Dtests.class=*.ClassName -Dtests.seed=DEAD:BEEF
  88. ------------------------------------------------------------------------
  89. === Repeats a given test N times
  90. (note the filters - individual test repetitions are given suffixes,
  91. ie: testFoo[0], testFoo[1], etc... so using testmethod or tests.method
  92. ending in a glob is necessary to ensure iterations are run).
  93. -------------------------------------------------------------------------
  94. ./gradlew test -Dtests.iters=N -Dtests.class=*.ClassName -Dtests.method=mytest*
  95. -------------------------------------------------------------------------
  96. Repeats N times but skips any tests after the first failure or M initial failures.
  97. -------------------------------------------------------------
  98. ./gradlew test -Dtests.iters=N -Dtests.failfast=true -Dtestcase=...
  99. ./gradlew test -Dtests.iters=N -Dtests.maxfailures=M -Dtestcase=...
  100. -------------------------------------------------------------
  101. === Test groups.
  102. Test groups can be enabled or disabled (true/false).
  103. Default value provided below in [brackets].
  104. ------------------------------------------------------------------
  105. ./gradlew test -Dtests.awaitsfix=[false] - known issue (@AwaitsFix)
  106. ------------------------------------------------------------------
  107. === Load balancing and caches.
  108. By default the tests run on multiple processes using all the available cores on all
  109. available CPUs. Not including hyper-threading.
  110. If you want to explicitly specify the number of JVMs you can do so on the command
  111. line:
  112. ----------------------------
  113. ./gradlew test -Dtests.jvms=8
  114. ----------------------------
  115. Or in `~/.gradle/gradle.properties`:
  116. ----------------------------
  117. systemProp.tests.jvms=8
  118. ----------------------------
  119. Its difficult to pick the "right" number here. Hypercores don't count for CPU
  120. intensive tests and you should leave some slack for JVM-interal threads like
  121. the garbage collector. And you have to have enough RAM to handle each JVM.
  122. === Test compatibility.
  123. It is possible to provide a version that allows to adapt the tests behaviour
  124. to older features or bugs that have been changed or fixed in the meantime.
  125. -----------------------------------------
  126. ./gradlew test -Dtests.compatibility=1.0.0
  127. -----------------------------------------
  128. === Miscellaneous.
  129. Run all tests without stopping on errors (inspect log files).
  130. -----------------------------------------
  131. ./gradlew test -Dtests.haltonfailure=false
  132. -----------------------------------------
  133. Run more verbose output (slave JVM parameters, etc.).
  134. ----------------------
  135. ./gradlew test -verbose
  136. ----------------------
  137. Change the default suite timeout to 5 seconds for all
  138. tests (note the exclamation mark).
  139. ---------------------------------------
  140. ./gradlew test -Dtests.timeoutSuite=5000! ...
  141. ---------------------------------------
  142. Change the logging level of ES (not Gradle)
  143. --------------------------------
  144. ./gradlew test -Dtests.es.logger.level=DEBUG
  145. --------------------------------
  146. Print all the logging output from the test runs to the commandline
  147. even if tests are passing.
  148. ------------------------------
  149. ./gradlew test -Dtests.output=always
  150. ------------------------------
  151. Configure the heap size.
  152. ------------------------------
  153. ./gradlew test -Dtests.heap.size=512m
  154. ------------------------------
  155. Pass arbitrary jvm arguments.
  156. ------------------------------
  157. # specify heap dump path
  158. ./gradlew test -Dtests.jvm.argline="-XX:HeapDumpPath=/path/to/heapdumps"
  159. # enable gc logging
  160. ./gradlew test -Dtests.jvm.argline="-verbose:gc"
  161. # enable security debugging
  162. ./gradlew test -Dtests.jvm.argline="-Djava.security.debug=access,failure"
  163. ------------------------------
  164. == Running verification tasks
  165. To run all verification tasks, including static checks, unit tests, and integration tests:
  166. ---------------------------------------------------------------------------
  167. ./gradlew check
  168. ---------------------------------------------------------------------------
  169. Note that this will also run the unit tests and precommit tasks first. If you want to just
  170. run the integration tests (because you are debugging them):
  171. ---------------------------------------------------------------------------
  172. ./gradlew integTest
  173. ---------------------------------------------------------------------------
  174. If you want to just run the precommit checks:
  175. ---------------------------------------------------------------------------
  176. ./gradlew precommit
  177. ---------------------------------------------------------------------------
  178. Some of these checks will require `docker-compose` installed for bringing up
  179. test fixtures. If it's not present those checks will be skipped automatically.
  180. == Testing the REST layer
  181. The available integration tests make use of the java API to communicate with
  182. the elasticsearch nodes, using the internal binary transport (port 9300 by
  183. default).
  184. The REST layer is tested through specific tests that are shared between all
  185. the elasticsearch official clients and consist of YAML files that describe the
  186. operations to be executed and the obtained results that need to be tested.
  187. The YAML files support various operators defined in the link:/rest-api-spec/src/main/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]
  188. The REST tests are run automatically when executing the "./gradlew check" command. To run only the
  189. REST tests use the following command:
  190. ---------------------------------------------------------------------------
  191. ./gradlew :distribution:archives:integ-test-zip:integTest \
  192. -Dtests.class="org.elasticsearch.test.rest.*Yaml*IT"
  193. ---------------------------------------------------------------------------
  194. A specific test case can be run with
  195. ---------------------------------------------------------------------------
  196. ./gradlew :distribution:archives:integ-test-zip:integTest \
  197. -Dtests.class="org.elasticsearch.test.rest.*Yaml*IT" \
  198. -Dtests.method="test {p0=cat.shards/10_basic/Help}"
  199. ---------------------------------------------------------------------------
  200. `*Yaml*IT` are the executable test classes that runs all the
  201. yaml suites available within the `rest-api-spec` folder.
  202. The REST tests support all the options provided by the randomized runner, plus the following:
  203. * `tests.rest[true|false]`: determines whether the REST tests need to be run (default) or not.
  204. * `tests.rest.suite`: comma separated paths of the test suites to be run
  205. (by default loaded from /rest-api-spec/test). It is possible to run only a subset
  206. of the tests providing a sub-folder or even a single yaml file (the default
  207. /rest-api-spec/test prefix is optional when files are loaded from classpath)
  208. e.g. -Dtests.rest.suite=index,get,create/10_with_id
  209. * `tests.rest.blacklist`: comma separated globs that identify tests that are
  210. blacklisted and need to be skipped
  211. e.g. -Dtests.rest.blacklist=index/*/Index document,get/10_basic/*
  212. Note that the REST tests, like all the integration tests, can be run against an external
  213. cluster by specifying the `tests.cluster` property, which if present needs to contain a
  214. comma separated list of nodes to connect to (e.g. localhost:9300). A transport client will
  215. be created based on that and used for all the before|after test operations, and to extract
  216. the http addresses of the nodes so that REST requests can be sent to them.
  217. == Testing packaging
  218. The packaging tests use Vagrant virtual machines to verify that installing
  219. and running elasticsearch distributions works correctly on supported operating systems.
  220. These tests should really only be run in vagrant vms because they're destructive.
  221. . Install Virtual Box and Vagrant.
  222. +
  223. . (Optional) Install https://github.com/fgrehm/vagrant-cachier[vagrant-cachier] to squeeze
  224. a bit more performance out of the process:
  225. +
  226. --------------------------------------
  227. vagrant plugin install vagrant-cachier
  228. --------------------------------------
  229. +
  230. . Validate your installed dependencies:
  231. +
  232. -------------------------------------
  233. ./gradlew :qa:vagrant:vagrantCheckVersion
  234. -------------------------------------
  235. +
  236. . Download and smoke test the VMs with `./gradlew vagrantSmokeTest` or
  237. `./gradlew -Pvagrant.boxes=all vagrantSmokeTest`. The first time you run this it will
  238. download the base images and provision the boxes and immediately quit. Downloading all
  239. the images may take a long time. After the images are already on your machine, they won't
  240. be downloaded again unless they have been updated to a new version.
  241. +
  242. . Run the tests with `./gradlew packagingTest`. This will cause Gradle to build
  243. the tar, zip, and deb packages and all the plugins. It will then run the tests
  244. on ubuntu-1404 and centos-7. We chose those two distributions as the default
  245. because they cover deb and rpm packaging and SyvVinit and systemd.
  246. You can choose which boxes to test by setting the `-Pvagrant.boxes` project property. All of
  247. the valid options for this property are:
  248. * `sample` - The default, only chooses ubuntu-1404 and centos-7
  249. * List of box names, comma separated (e.g. `oel-7,fedora-28`) - Chooses exactly the boxes listed.
  250. * `linux-all` - All linux boxes.
  251. * `windows-all` - All Windows boxes. If there are any Windows boxes which do not
  252. have images available when this value is provided, the build will fail.
  253. * `all` - All boxes we test. If there are any boxes (e.g. Windows) which do not have images
  254. available when this value is provided, the build will fail.
  255. For a complete list of boxes on which tests can be run, run `./gradlew :qa:vagrant:listAllBoxes`.
  256. For a list of boxes that have images available from your configuration, run
  257. `./gradlew :qa:vagrant:listAvailableBoxes`
  258. Note that if you interrupt gradle in the middle of running these tasks, any boxes started
  259. will remain running and you'll have to stop them manually with `./gradlew stop` or
  260. `vagrant halt`.
  261. All the regular vagrant commands should just work so you can get a shell in a
  262. VM running trusty by running
  263. `vagrant up ubuntu-1404 --provider virtualbox && vagrant ssh ubuntu-1404`.
  264. These are the linux flavors supported, all of which we provide images for
  265. * ubuntu-1404 aka trusty
  266. * ubuntu-1604 aka xenial
  267. * ubuntu-1804 aka bionic beaver
  268. * debian-8 aka jessie
  269. * debian-9 aka stretch, the current debian stable distribution
  270. * centos-6
  271. * centos-7
  272. * fedora-28
  273. * fedora-29
  274. * oel-6 aka Oracle Enterprise Linux 6
  275. * oel-7 aka Oracle Enterprise Linux 7
  276. * sles-12
  277. * opensuse-42 aka Leap
  278. We're missing the following from the support matrix because there aren't high
  279. quality boxes available in vagrant atlas:
  280. * sles-11
  281. === Testing packaging on Windows
  282. The packaging tests also support Windows Server 2012R2 and Windows Server 2016.
  283. Unfortunately we're not able to provide boxes for them in open source use
  284. because of licensing issues. Any Virtualbox image that has WinRM and Powershell
  285. enabled for remote users should work.
  286. Specify the image IDs of the Windows boxes to gradle with the following project
  287. properties. They can be set in `~/.gradle/gradle.properties` like
  288. ------------------------------------
  289. vagrant.windows-2012r2.id=my-image-id
  290. vagrant.windows-2016.id=another-image-id
  291. ------------------------------------
  292. or passed on the command line like `-Pvagrant.windows-2012r2.id=my-image-id`
  293. `-Pvagrant.windows-2016=another-image-id`
  294. These properties are required for Windows support in all gradle tasks that
  295. handle packaging tests. Either or both may be specified. Remember that to run tests
  296. on these boxes, the project property `vagrant.boxes` still needs to be set to a
  297. value that will include them.
  298. If you're running vagrant commands outside of gradle, specify the Windows boxes
  299. with the environment variables
  300. * `VAGRANT_WINDOWS_2012R2_BOX`
  301. * `VAGRANT_WINDOWS_2016_BOX`
  302. === Testing VMs are disposable
  303. It's important to think of VMs like cattle. If they become lame you just shoot
  304. them and let vagrant reprovision them. Say you've hosed your precise VM:
  305. ----------------------------------------------------
  306. vagrant ssh ubuntu-1404 -c 'sudo rm -rf /bin'; echo oops
  307. ----------------------------------------------------
  308. All you've got to do to get another one is
  309. ----------------------------------------------
  310. vagrant destroy -f ubuntu-1404 && vagrant up ubuntu-1404 --provider virtualbox
  311. ----------------------------------------------
  312. The whole process takes a minute and a half on a modern laptop, two and a half
  313. without vagrant-cachier.
  314. Its possible that some downloads will fail and it'll be impossible to restart
  315. them. This is a bug in vagrant. See the instructions here for how to work
  316. around it:
  317. https://github.com/mitchellh/vagrant/issues/4479
  318. Some vagrant commands will work on all VMs at once:
  319. ------------------
  320. vagrant halt
  321. vagrant destroy -f
  322. ------------------
  323. `vagrant up` would normally start all the VMs but we've prevented that because
  324. that'd consume a ton of ram.
  325. === Iterating on packaging tests
  326. Running the packaging tests through gradle can take a while because it will start
  327. and stop the VM each time. You can iterate faster by keeping the VM up and running
  328. the tests directly.
  329. The packaging tests use a random seed to determine which past version to use for
  330. testing upgrades. To use a single past version fix the test seed when running
  331. the commands below (see <<Seed and repetitions.>>)
  332. First build the packaging tests and their dependencies
  333. --------------------------------------------
  334. ./gradlew :qa:vagrant:setupPackagingTest
  335. --------------------------------------------
  336. Then choose the VM you want to test on and bring it up. For example, to bring
  337. up Debian 9 use the gradle command below. Bringing the box up with vagrant directly
  338. may not mount the packaging test project in the right place. Once the VM is up, ssh
  339. into it
  340. --------------------------------------------
  341. ./gradlew :qa:vagrant:vagrantDebian9#up
  342. vagrant ssh debian-9
  343. --------------------------------------------
  344. Now inside the VM, start the packaging tests from the terminal. There are two packaging
  345. test projects. The old ones are written with https://github.com/sstephenson/bats[bats]
  346. and only run on linux. To run them do
  347. --------------------------------------------
  348. cd $PACKAGING_ARCHIVES
  349. # runs all bats tests
  350. sudo bats $BATS_TESTS/*.bats
  351. # you can also pass specific test files
  352. sudo bats $BATS_TESTS/20_tar_package.bats $BATS_TESTS/25_tar_plugins.bats
  353. --------------------------------------------
  354. The new packaging tests are written in Java and run on both linux and windows. On
  355. linux (again, inside the VM)
  356. --------------------------------------------
  357. # run the full suite
  358. sudo bash $PACKAGING_TESTS/run-tests.sh
  359. # run specific test cases
  360. sudo bash $PACKAGING_TESTS/run-tests.sh \
  361. org.elasticsearch.packaging.test.DefaultZipTests \
  362. org.elasticsearch.packaging.test.OssZipTests
  363. --------------------------------------------
  364. or on Windows, from a terminal running as Administrator
  365. --------------------------------------------
  366. # run the full suite
  367. powershell -File $Env:PACKAGING_TESTS/run-tests.ps1
  368. # run specific test cases
  369. powershell -File $Env:PACKAGING_TESTS/run-tests.ps1 `
  370. org.elasticsearch.packaging.test.DefaultZipTests `
  371. org.elasticsearch.packaging.test.OssZipTests
  372. --------------------------------------------
  373. Note that on Windows boxes when running from inside the GUI, you may have to log out and
  374. back in to the `vagrant` user (password `vagrant`) for the environment variables that
  375. locate the packaging tests and distributions to take effect, due to how vagrant provisions
  376. Windows machines.
  377. When you've made changes you want to test, keep the VM up and reload the tests and
  378. distributions inside by running (on the host)
  379. --------------------------------------------
  380. ./gradlew :qa:vagrant:clean :qa:vagrant:setupPackagingTest
  381. --------------------------------------------
  382. Note: Starting vagrant VM outside of the elasticsearch folder requires to
  383. indicates the folder that contains the Vagrantfile using the VAGRANT_CWD
  384. environment variable.
  385. == Testing backwards compatibility
  386. Backwards compatibility tests exist to test upgrading from each supported version
  387. to the current version. To run them all use:
  388. -------------------------------------------------
  389. ./gradlew bwcTest
  390. -------------------------------------------------
  391. A specific version can be tested as well. For example, to test bwc with
  392. version 5.3.2 run:
  393. -------------------------------------------------
  394. ./gradlew v5.3.2#bwcTest
  395. -------------------------------------------------
  396. Tests are ran for versions that are not yet released but with which the current version will be compatible with.
  397. These are automatically checked out and built from source.
  398. See link:./buildSrc/src/main/java/org/elasticsearch/gradle/VersionCollection.java[VersionCollection]
  399. and link:./distribution/bwc/build.gradle[distribution/bwc/build.gradle]
  400. for more information.
  401. When running `./gradlew check`, minimal bwc checks are also run against compatible versions that are not yet released.
  402. ==== BWC Testing against a specific remote/branch
  403. Sometimes a backward compatibility change spans two versions. A common case is a new functionality
  404. that needs a BWC bridge in an unreleased versioned of a release branch (for example, 5.x).
  405. To test the changes, you can instruct Gradle to build the BWC version from a another remote/branch combination instead of
  406. pulling the release branch from GitHub. You do so using the `tests.bwc.remote` and `tests.bwc.refspec.BRANCH` system properties:
  407. -------------------------------------------------
  408. ./gradlew check -Dtests.bwc.remote=${remote} -Dtests.bwc.refspec.5.x=index_req_bwc_5.x
  409. -------------------------------------------------
  410. The branch needs to be available on the remote that the BWC makes of the
  411. repository you run the tests from. Using the remote is a handy trick to make
  412. sure that a branch is available and is up to date in the case of multiple runs.
  413. Example:
  414. Say you need to make a change to `master` and have a BWC layer in `5.x`. You
  415. will need to:
  416. . Create a branch called `index_req_change` off your remote `${remote}`. This
  417. will contain your change.
  418. . Create a branch called `index_req_bwc_5.x` off `5.x`. This will contain your bwc layer.
  419. . Push both branches to your remote repository.
  420. . Run the tests with `./gradlew check -Dtests.bwc.remote=${remote} -Dtests.bwc.refspec.5.x=index_req_bwc_5.x`.
  421. ==== Skip fetching latest
  422. For some BWC testing scenarios, you want to use the local clone of the
  423. repository without fetching latest. For these use cases, you can set the system
  424. property `tests.bwc.git_fetch_latest` to `false` and the BWC builds will skip
  425. fetching the latest from the remote.
  426. == How to write good tests?
  427. === Base classes for test cases
  428. There are multiple base classes for tests:
  429. * **`ESTestCase`**: The base class of all tests. It is typically extended
  430. directly by unit tests.
  431. * **`ESSingleNodeTestCase`**: This test case sets up a cluster that has a
  432. single node.
  433. * **`ESIntegTestCase`**: An integration test case that creates a cluster that
  434. might have multiple nodes.
  435. * **`ESRestTestCase`**: An integration tests that interacts with an external
  436. cluster via the REST API. For instance, YAML tests run via sub classes of
  437. `ESRestTestCase`.
  438. === Good practices
  439. ==== What kind of tests should I write?
  440. Unit tests are the preferred way to test some functionality: most of the time
  441. they are simpler to understand, more likely to reproduce, and unlikely to be
  442. affected by changes that are unrelated to the piece of functionality that is
  443. being tested.
  444. The reason why `ESSingleNodeTestCase` exists is that all our components used to
  445. be very hard to set up in isolation, which had led us to having a number of
  446. integration tests but close to no unit tests. `ESSingleNodeTestCase` is a
  447. workaround for this issue which provides an easy way to spin up a node and get
  448. access to components that are hard to instantiate like `IndicesService`.
  449. Whenever practical, you should prefer unit tests.
  450. Many tests extend `ESIntegTestCase`, mostly because this is how most tests used
  451. to work in the early days of Elasticsearch. However the complexity of these
  452. tests tends to make them hard to debug. Whenever the functionality that is
  453. being tested isn't intimately dependent on how Elasticsearch behaves as a
  454. cluster, it is recommended to write unit tests or REST tests instead.
  455. In short, most new functionality should come with unit tests, and optionally
  456. REST tests to test integration.
  457. ==== Refactor code to make it easier to test
  458. Unfortunately, a large part of our code base is still hard to unit test.
  459. Sometimes because some classes have lots of dependencies that make them hard to
  460. instantiate. Sometimes because API contracts make tests hard to write. Code
  461. refactors that make functionality easier to unit test are encouraged. If this
  462. sounds very abstract to you, you can have a look at
  463. https://github.com/elastic/elasticsearch/pull/16610[this pull request] for
  464. instance, which is a good example. It refactors `IndicesRequestCache` in such
  465. a way that:
  466. - it no longer depends on objects that are hard to instantiate such as
  467. `IndexShard` or `SearchContext`,
  468. - time-based eviction is applied on top of the cache rather than internally,
  469. which makes it easier to assert on what the cache is expected to contain at
  470. a given time.
  471. === Bad practices
  472. ==== Use randomized-testing for coverage
  473. In general, randomization should be used for parameters that are not expected
  474. to affect the behavior of the functionality that is being tested. For instance
  475. the number of shards should not impact `date_histogram` aggregations, and the
  476. choice of the `store` type (`niofs` vs `mmapfs`) does not affect the results of
  477. a query. Such randomization helps improve confidence that we are not relying on
  478. implementation details of one component or specifics of some setup.
  479. However it should not be used for coverage. For instance if you are testing a
  480. piece of functionality that enters different code paths depending on whether
  481. the index has 1 shards or 2+ shards, then we shouldn't just test against an
  482. index with a random number of shards: there should be one test for the 1-shard
  483. case, and another test for the 2+ shards case.
  484. ==== Abuse randomization in multi-threaded tests
  485. Multi-threaded tests are often not reproducible due to the fact that there is
  486. no guarantee on the order in which operations occur across threads. Adding
  487. randomization to the mix usually makes things worse and should be done with
  488. care.
  489. == Test coverage analysis
  490. Generating test coverage reports for Elasticsearch is currently not possible through Gradle.
  491. However, it _is_ possible to gain insight in code coverage using IntelliJ's built-in coverage
  492. analysis tool that can measure coverage upon executing specific tests. Eclipse may also be able
  493. to do the same using the EclEmma plugin.
  494. Test coverage reporting used to be possible with JaCoCo when Elasticsearch was using Maven
  495. as its build system. Since the switch to Gradle though, this is no longer possible, seeing as
  496. the code currently used to build Elasticsearch does not allow JaCoCo to recognize its tests.
  497. For more information on this, see the discussion in https://github.com/elastic/elasticsearch/issues/28867[issue #28867].
  498. == Debugging remotely from an IDE
  499. If you want to run Elasticsearch and be able to remotely attach the process
  500. for debugging purposes from your IDE, can start Elasticsearch using `ES_JAVA_OPTS`:
  501. ---------------------------------------------------------------------------
  502. ES_JAVA_OPTS="-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=y" ./bin/elasticsearch
  503. ---------------------------------------------------------------------------
  504. Read your IDE documentation for how to attach a debugger to a JVM process.
  505. == Building with extra plugins
  506. Additional plugins may be built alongside elasticsearch, where their
  507. dependency on elasticsearch will be substituted with the local elasticsearch
  508. build. To add your plugin, create a directory called elasticsearch-extra as
  509. a sibling of elasticsearch. Checkout your plugin underneath elasticsearch-extra
  510. and the build will automatically pick it up. You can verify the plugin is
  511. included as part of the build by checking the projects of the build.
  512. ---------------------------------------------------------------------------
  513. ./gradlew projects
  514. ---------------------------------------------------------------------------
  515. == Environment misc
  516. There is a known issue with macOS localhost resolve strategy that can cause
  517. some integration tests to fail. This is because integration tests have timings
  518. for cluster formation, discovery, etc. that can be exceeded if name resolution
  519. takes a long time.
  520. To fix this, make sure you have your computer name (as returned by `hostname`)
  521. inside `/etc/hosts`, e.g.:
  522. ....
  523. 127.0.0.1 localhost ElasticMBP.local
  524. 255.255.255.255 broadcasthost
  525. ::1 localhost ElasticMBP.local`
  526. ....
  527. == Benchmarking
  528. For changes that might affect the performance characteristics of Elasticsearch
  529. you should also run macrobenchmarks. We maintain a macrobenchmarking tool
  530. called https://github.com/elastic/rally[Rally]
  531. which you can use to measure the performance impact. It comes with a set of
  532. default benchmarks that we also
  533. https://elasticsearch-benchmarks.elastic.co/[run every night]. To get started,
  534. please see https://esrally.readthedocs.io/en/stable/[Rally's documentation].