Merge pull request #8868 from haskell/mergify/bp/3.10/pr-8852
[cabal.git] / cabal-testsuite / README.md
blob0bf85b760c103cbdf44d67b8e97b9fff45c9573c
1 cabal-testsuite is a suite of integration tests for Cabal-based
2 frameworks.
4 How to run
5 ----------
7 1. Build `cabal-testsuite` (`cabal build cabal-testsuite:cabal-tests`)
8 2. Run the `cabal-tests` executable. It will scan for all tests
9    in your current directory and subdirectories and run them.
10    To run a specific set of tests, use `cabal-tests --with-cabal=CABALBIN PATH ...`.
11    (e.g. `cabal run cabal-testsuite:cabal-tests -- --with-cabal=cabal cabal-testsuite/PackageTests/TestOptions/setup.test.hs`)
12    You can control parallelism using the `-j` flag.
14 There are a few useful flags:
16 * `--with-cabal PATH` can be used to specify the path of a
17   `cabal-install` executable.  IF YOU DO NOT SPECIFY THIS FLAG,
18   CABAL INSTALL TESTS WILL NOT RUN.
20 * `--with-ghc PATH` can be used to specify an alternate version of
21   GHC to ask the tests to compile with.
23 * `--builddir DIR` can be used to manually specify the dist directory
24   that was used to build `cabal-tests`; this can be used if
25   the autodetection doesn't work correctly (which may be the
26   case for old versions of GHC.)
28 doctests
29 ========
31 You need to install the doctest tool. Make sure it's compiled with your current
32 GHC, and don't forget to reinstall it every time you switch GHC version:
34 ``` shellsession
35 cabal install doctest --overwrite-policy=always --ignore-project
36 ```
38 After that you can run doctests for a component of your choice via the following command:
40 ``` shellsession
41 cabal repl --with-ghc=doctest --build-depends=QuickCheck --build-depends=template-haskell --repl-options="-w" --project-file="cabal.project.validate" Cabal-syntax
42 ```
44 In this example we have run doctests in `Cabal-syntax`. Notice, that some
45 components have broken doctests
46 ([#8734](https://github.com/haskell/cabal/issues/8734));
47 our CI currently checks that `Cabal-syntax` and `Cabal` doctests pass via
48 `make doctest-install && make doctest` (you can use this make-based workflow too).
50 How to write
51 ------------
53 If you learn better by example, just look at the tests that live
54 in `cabal-testsuite/PackageTests`; if you `git log -p`, you can
55 see the full contents of various commits which added a test for
56 various functionality.  See if you can find an existing test that
57 is similar to what you want to test.
59 Otherwise, here is a walkthrough:
61 1. Create the package(s) that you need for your test in a
62    new directory.
63    (Currently (2021-10-06), tests are stored in `PackageTests`,
64    with the exception of one test stored in `tests`.)
66 2. Create one or more `.test.hs` scripts in your directory, using
67    the template:
68    ```haskell
69    import Test.Cabal.Prelude
70    main = setupAndCabalTest $ do
71        -- your test code here
72    ```
74    `setupAndCabal` test indicates that invocations of `setup`
75    should work both for a raw `Setup` script, as well as
76    `cabal-install` (if your test works only for one or the
77    other, use `setupTest` or `cabalTest`).
79    Code runs in the `TestM` monad, which manages some administrative
80    environment (e.g., the test that is running, etc.).
81    `Test.Cabal.Prelude` contains a number of useful functions
82    for testing implemented in this monad, including the functions `cabal`
83    and `setup` which let you invoke those respective programs.  You should
84    read through that file to get a sense for what capabilities
85    are possible (grep for use-sites of functions to see how they
86    are used).  If you don't see something anywhere, that's probably
87    because it isn't implemented. Implement it!
89    To include parts that are supposed to fail (in the sense that a
90    non-zero exit code is returned), there is the `fails` combinator,
91    e.g.:
92    ```haskell
93    main = cabalTest $ do
94      fails $ cabal "bad-command" [ "bad", "args" ]
95      cabal "good-command" [ "good", "args" ]
96      fails $ cabal "another-bad-one" [ ... ]
97      ...
98    ```
100 3. Run your tests using `cabal-tests` (no need to rebuild when
101    you add or modify a test; it is automatically picked up).
102    The first time you run a test, assuming everything else is
103    in order, it will complain that the actual output doesn't match
104    the expected output.  Use the `--accept` flag to accept the
105    output if it makes sense!
107 We also support a `.multitest.hs` prefix; eventually this will
108 allow multiple tests to be defined in one file but run in parallel;
109 at the moment, these just indicate long running tests that should
110 be run early (to avoid straggling).
112 Frequently asked questions
113 --------------------------
115 For all of these answers, to see examples of the functions in
116 question, grep the test suite.
118 **Why isn't some output I added to Cabal showing up in the recorded
119 test output?** Only "marked" output is picked up by Cabal; currently,
120 only `notice`, `warn` and `die` produce marked output.  Use those
121 combinators for your output.
123 **How do I safely let my test modify version-controlled source files?**
124 Use `withSourceCopy`.  Note that you MUST `git add`
125 all files which are relevant to the test; otherwise they will not be
126 available when running the test.
128 **How can I add a dependency on a package from Hackage in a test?**
129 By default, the test suite is completely independent of the contents
130 of Hackage, to ensure that it keeps working across all GHC versions.
131 If possible, define the package locally.  If the package needs
132 to be from Hackage (e.g., you are testing the global store code
133 in new-build), use `withRepo "repo"` to initialize a "fake" Hackage with
134 the packages placed in the `repo` directory.
136 **How do I run an executable that my test built?** The specific
137 function you should use depends on how you built the executable:
139 * If you built it using `Setup build`, use `runExe`
140 * If you installed it using `Setup install` or `cabal install`, use
141   `runInstalledExe`.
142 * If you built it with `cabal build`, use `runPlanExe`; note
143   that you will need to run this inside of a `withPlan` that is
144   placed *after* you have invoked `build`. (Grep for an example!)
146 **How do I turn off accept tests? My test output wobbles too much.**
147 Use `recordMode DoNotRecord`.  This should be a last resort; consider
148 modifying Cabal so that the output is stable.  If you must do this, make
149 sure you add extra, manual tests to ensure the output looks like what
150 you expect.
152 **How can I manually test for a string in output?**  Use the primed
153 variants of a command (e.g., `cabal'` rather than `cabal`) and use
154 `assertOutputContains`.  Note that this will search over BOTH stdout
155 and stderr.
157 **How do I skip running a test in some environments?**  Use the
158 `skipIf` and `skipUnless` combinators.  Useful parameters to test
159 these with include `hasSharedLibraries`, `hasProfiledLibraries`,
160 `hasCabalShared`, `isGhcVersion`, `isWindows`, `isLinux`, `isOSX`
161 and `hasCabalForGhc`.
163 **I programmatically modified a file in my test suite, but Cabal/GHC
164 doesn't seem to be picking it up.**  You need to sleep sufficiently
165 long before editing a file, in order for file system timestamp
166 resolution to pick it up.  Use `withDelay` and `delay` prior to
167 making a modification.
169 **How do I mark a test as broken?**  Use `expectBroken`, which takes
170 the ticket number as its first argument.  Note that this does NOT
171 handle accept-test brokenness, so you will have to add a manual
172 string output test, if that is how your test is "failing."
174 Hermetic tests
175 --------------
177 By default, we run tests directly on the source code that is checked into the
178 source code repository.  However, some tests require programmatically
179 modifying source files, or interact with Cabal commands which are
180 not hermetic (e.g., `cabal freeze`).  In this case, cabal-testsuite
181 supports opting into a hermetic test, where we first make copy of all
182 the relevant source code before starting the test.  You can opt into
183 this mode using the `withSourceCopy` combinator (search for examples!)
184 This mode is subject to the following limitations:
186 * You must be running the test inside a valid Git checkout of the test
187   suite (`withSourceCopy` uses Git to determine which files should be copied.)
189 * You must `git add` all files which are relevant to the test, otherwise
190   they will not be copied.
192 * The source copy is still made at a well-known location, so running
193   a test is still not reentrant. (See also Known Limitations.)
195 Design notes
196 ------------
198 This is the second rewrite of the integration testing framework.  The
199 primary goal was to use Haskell as the test language (letting us take
200 advantage of a real programming language, and use utilities provided to
201 us by the Cabal library itself), while at the same time compensating for
202 two perceived problems of pure-Haskell test suites:
204 * Haskell test suites are generally compiled before they run
205   (for example, this is the modus operandi of `cabal test`).
206   In practice, this results in a long edit-recompile cycle
207   when working on tests. This hurts a lot when you would
208   like to experimentally edit a test when debugging an issue.
210 * Haskell's metaprogramming facilities (e.g., Template Haskell)
211   can't handle dynamically loading modules from the file system;
212   thus, there ends up being a considerable amount of boilerplate
213   needed to "wire" up test cases to the central test runner.
215 Our approach to address these issues is to maintain Haskell test scripts
216 as self-contained programs which are run by the GHCi interpreter.
217 This is not altogether trivial, and so there are a few important
218 technical innovations to make this work:
220 * Unlike a traditional test program which can be built by the Cabal
221   build system, these test scripts must be interpretable at
222   runtime (outside of the build system.)  Our approach to handle
223   this is to link against the same version of Cabal that was
224   used to build the top-level test program (by way of a Custom
225   setup linked against the Cabal library under test) and then
226   use this library to compute the necessary GHC flags to pass
227   to these scripts.
229 * The startup latency of `runghc` can be quite high, which adds up
230   when you have many tests.  To solve this, in `Test.Cabal.Server`
231   we have an implementation an GHCi server, for which we can reuse
232   a GHCi instance as we are running test scripts.  It took some
233   technical ingenuity to implement this, but the result is that
234   running scripts is essentially free.
236 Here is the general outline of how the `cabal-tests` program operates:
238 1. It first loads the cached `LocalBuildInfo` associated with the
239    host build system (which was responsible for building `cabal-tests`
240    in the first place.)  This information lets us compute the
241    flags that we will use to subsequently invoke GHC.
243 2. We then recursively scan the current working directory, looking
244    for files suffixed `.test.hs`; these are the test scripts we
245    will run.
247 3. For every thread specified via the `-j`, we spawn a GHCi
248    server, and then use these to run the test scripts until all
249    test scripts have been run.
251 The new `cabal-tests` runner doesn't use Tasty because I couldn't
252 figure out how to get out the threading setting, and then spawn
253 that many GHCi servers to service the running threads.  Improvements
254 welcome.
256 Expect tests
257 ------------
259 An expect test (aka _golden test_)
260 is a test where we read out the output of the test
261 and compare it directly against a saved copy of the test output.
262 When test output changes, you can ask the test suite to "accept"
263 the new output, which automatically overwrites the old expected
264 test output with the new.
266 Supporting expect tests with Cabal is challenging, because Cabal
267 interacts with multiple versions of external components (most
268 prominently GHC) with different variants of their output, and no
269 one wants to rerun a test on four different versions of GHC to make
270 sure we've picked up the correct output in all cases.
272 Still, we'd like to take advantage of expect tests for Cabal's error
273 reporting.  So here's our strategy:
275 1. We have a new verbosity flag `+markoutput` which lets you toggle the emission
276    of `-----BEGIN CABAL OUTPUT-----` and  `-----END CABAL OUTPUT-----`
277    stanzas.
279 2. When someone requests an expect test, we ONLY consider output between
280    these flags.
282 The expectation is that Cabal will only enclose output it controls
283 between these stanzas.  In practice, this just means we wrap `die`,
284 `warn` and `notice` with these markers.
286 An added benefit of this strategy is that we can continue operating
287 at high verbosity by default (which is very helpful for having useful
288 diagnostic information immediately, e.g. in CI.)
290 We also need to deal with nondeterminism in test output in some
291 situations.  Here are the most common ones:
293 * Dependency solving output on failure is still non-deterministic, due to
294   its dependence on the global package database.  We're tracking this
295   in https://github.com/haskell/cabal/issues/4332 but for now, we're
296   not running expect tests on this output.
298 * Tests against Custom setup will build against the Cabal that shipped with
299   GHC, so you need to be careful NOT to record this output (since we
300   don't control that output.)
302 * We have some munging on the output, to remove common sources of
303   non-determinism: paths, GHC versions, boot package versions, etc.
304   Check `normalizeOutput` to see what we do.  Note that we save
305   *normalized* output, so if you modify the normalizer you will
306   need to rerun the test suite accepting everything.
308 * The Setup interface gets a `--enable-deterministic` flag which we
309   pass by default.  The intent is to make Cabal more deterministic;
310   for example, with this flag we no longer compute a hash when
311   computing IPIDs, but just use the tag `-inplace`.  You can manually
312   disable this using `--disable-deterministic` (as is the case with
313   `UniqueIPID`.)
315 Some other notes:
317 * It's good style to put `default-language` in all your stanzas, so
318   Cabal doesn't complain about it (that warning is marked!).  Ditto
319   with `cabal-version` at the top of your Cabal file.
321 * If you can't get the output of a test to be deterministic, no
322   problem: just exclude it from recording and do a manual test
323   on the output for the string you're looking for.  Try to be
324   deterministic, but sometimes it's not (easily) possible.
326 Non-goals
327 ---------
329 Here are some things we do not currently plan on supporting:
331 * A file format for specifying multiple packages and source files.
332   While in principle there is nothing wrong with making it easier
333   to write tests, tests stored in this manner are more difficult
334   to debug with, as they must first be "decompressed" into a full
335   folder hierarchy before they can be interacted with.  (But some
336   of our tests need substantial setup; for example, tests that
337   have to setup a package repository.  In this case, because there
338   already is a setup necessary, we might consider making things easier here.)
340 Known limitations
341 -----------------
343 * Tests are NOT reentrant: test build products are always built into
344   the same location, and if you run the same test at the same time,
345   you will clobber each other.  This is convenient for debugging and
346   doesn't seem to be a problem in practice.