TESTING.asciidoc 29 KB

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