Merge lp:~thumper/juju-core/testing-docs into lp:~go-bot/juju-core/trunk

Proposed by Tim Penhey
Status: Merged
Approved by: Tim Penhey
Approved revision: no longer in the source branch.
Merged at revision: 2711
Proposed branch: lp:~thumper/juju-core/testing-docs
Merge into: lp:~go-bot/juju-core/trunk
Diff against target: 308 lines (+304/-0)
1 file modified
doc/how-to-write-tests.txt (+304/-0)
To merge this branch: bzr merge lp:~thumper/juju-core/testing-docs
Reviewer Review Type Date Requested Status
Juju Engineering Pending
Review via email: mp+218732@code.launchpad.net

Commit message

Add some developer docs for writing tests.

Obviously there is a lot that could be written, but this
is a start.

https://codereview.appspot.com/96110043/

Description of the change

Add some developer docs for writing tests.

Obviously there is a lot that could be written, but this
is a start.

https://codereview.appspot.com/96110043/

To post a comment you must log in.
Revision history for this message
Tim Penhey (thumper) wrote :

Reviewers: mp+218732_code.launchpad.net,

Message:
Please take a look.

Description:
Add some developer docs for writing tests.

Obviously there is a lot that could be written, but this
is a start.

https://code.launchpad.net/~thumper/juju-core/testing-docs/+merge/218732

(do not edit description out of merge proposal)

Please review this at https://codereview.appspot.com/96110043/

Affected files (+234, -0 lines):
   A [revision details]
   A doc/how-to-write-tests.txt

Revision history for this message
Ian Booth (wallyworld) wrote :

A great start.
I'd also mention github.com/juju/testing/checkers
LGTM. We should get this in and iterate on it.

https://codereview.appspot.com/96110043/

Revision history for this message
Menno Finlay-Smits (menno.smits) wrote :

Minor fixes

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt
File doc/how-to-write-tests.txt (right):

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode165
doc/how-to-write-tests.txt:165: To create your new test suite composing
one of the following, you can
Clearer as:

To create a new suite composed of one or more of the suites above, you
can do something like:

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode207
doc/how-to-write-tests.txt:207: in the compisition tree, there are a few
very helpful functions.
composition

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode223
doc/how-to-write-tests.txt:223: PatchValue works with any matching type.
This includes function variables.
Is it possible to patch methods? I'm guessing it isn't, but if it is
could you add an example here?

https://codereview.appspot.com/96110043/

Revision history for this message
Tim Penhey (thumper) wrote :

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt
File doc/how-to-write-tests.txt (right):

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode165
doc/how-to-write-tests.txt:165: To create your new test suite composing
one of the following, you can
On 2014/05/08 04:38:58, menn0 wrote:
> Clearer as:

> To create a new suite composed of one or more of the suites above, you
can do
> something like:

Done.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode207
doc/how-to-write-tests.txt:207: in the compisition tree, there are a few
very helpful functions.
On 2014/05/08 04:38:58, menn0 wrote:
> composition

Done.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode223
doc/how-to-write-tests.txt:223: PatchValue works with any matching type.
This includes function variables.
On 2014/05/08 04:38:58, menn0 wrote:
> Is it possible to patch methods? I'm guessing it isn't, but if it is
could you
> add an example here?

No, you can't patch methods. You do that by using interfaces, and
mocking them out.

https://codereview.appspot.com/96110043/

Revision history for this message
William Reade (fwereade) wrote :

This is awesome. Not all my comments are necessarily directly
actionable, in that they're complaints about our current testing, but
perhaps you can find some way to work their intent in usefully.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt
File doc/how-to-write-tests.txt (right):

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode119
doc/how-to-write-tests.txt:119: // a pointer to that variable so we can
patch it in the tests.
formatting

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode151
doc/how-to-write-tests.txt:151: github.com/juju/testing, which brings in
the CleanupSute from the same.
s/Sute/Suite/

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode159
doc/how-to-write-tests.txt:159: JUJU_ENV, and JUJU_LOGGING_CONFIG
environment variables.
The FakeHomeSuite should generally not be used, because it assumes a
context of a running (cmd/juju) client; almost all the code should avoid
making this assumption, because it's actually generally going to run on
an API server.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode162
doc/how-to-write-tests.txt:162: api server.
The JujuConnSuite is all fucked up, and should be used when you just
don't care about having coherent context available, you just kinda want
everything and don't want to think too hard. State server? Client? Both?
Whooo! Who cares!

Yeah, we should fix this; but in the meantime I want people to know it's
at least somewhat bad/wrong, because then *maybe* someone will take it
upon themselves to extract a saner subset of the functionality and start
using that; as it is it's all too easy to just allow the rot to gently
spread without even knowing that's what you're doing.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode215
doc/how-to-write-tests.txt:215: // of the test.
Really, FWIW, I think we should always be clearing the env at the very
start of a test.

https://codereview.appspot.com/96110043/

Revision history for this message
Tim Penhey (thumper) wrote :

Please take a look.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt
File doc/how-to-write-tests.txt (right):

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode119
doc/how-to-write-tests.txt:119: // a pointer to that variable so we can
patch it in the tests.
On 2014/05/08 05:34:49, fwereade wrote:
> formatting

Done.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode151
doc/how-to-write-tests.txt:151: github.com/juju/testing, which brings in
the CleanupSute from the same.
On 2014/05/08 05:34:49, fwereade wrote:
> s/Sute/Suite/

Done.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode159
doc/how-to-write-tests.txt:159: JUJU_ENV, and JUJU_LOGGING_CONFIG
environment variables.
On 2014/05/08 05:34:49, fwereade wrote:
> The FakeHomeSuite should generally not be used, because it assumes a
context of
> a running (cmd/juju) client; almost all the code should avoid making
this
> assumption, because it's actually generally going to run on an API
server.

Perhaps that was the original intent, but it has been extended somewhat
to allow writing of custom files into the HOME directory, and the
isolation of the environment variables that juju cares about.

Perhaps we should split and isolate more.

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode162
doc/how-to-write-tests.txt:162: api server.
On 2014/05/08 05:34:49, fwereade wrote:
> The JujuConnSuite is all fucked up, and should be used when you just
don't care
> about having coherent context available, you just kinda want
everything and
> don't want to think too hard. State server? Client? Both? Whooo! Who
cares!

> Yeah, we should fix this; but in the meantime I want people to know
it's at
> least somewhat bad/wrong, because then *maybe* someone will take it
upon
> themselves to extract a saner subset of the functionality and start
using that;
> as it is it's all too easy to just allow the rot to gently spread
without even
> knowing that's what you're doing.

Added a note to indicate that we aren't happy with it as it stands :-)

https://codereview.appspot.com/96110043/diff/1/doc/how-to-write-tests.txt#newcode215
doc/how-to-write-tests.txt:215: // of the test.
On 2014/05/08 05:34:49, fwereade wrote:
> Really, FWIW, I think we should always be clearing the env at the very
start of
> a test.

Is there not some part of the environment that we actually care about?

Pretty sure some expect bash.

https://codereview.appspot.com/96110043/

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'doc/how-to-write-tests.txt'
2--- doc/how-to-write-tests.txt 1970-01-01 00:00:00 +0000
3+++ doc/how-to-write-tests.txt 2014-05-08 22:33:29 +0000
4@@ -0,0 +1,304 @@
5+How to write tests
6+==================
7+
8+On the whole, new or updated code will not pass review unless there are tests
9+associated with the code. For code additions, the tests should cover as much
10+of the new code as practical, and for code changes, either the tests should be
11+updated, or at least the tests that already exist that cover the refactored
12+code should be identified when requesting a review to show that there is already
13+test coverage, and that the refactoring didn't break anything.
14+
15+
16+go test and gocheck
17+-------------------
18+
19+The `go test` command is used to run the tests. Juju uses the `gocheck` package
20+("launchpad.net/gocheck") to provide a checkers and assert methods for the test
21+writers. The use of gocheck replaces the standard `testing` library.
22+
23+Across all of the tests in juju-core, the gocheck package is imported
24+with a shorter alias, because it is used a lot.
25+
26+```go
27+import (
28+ // system packages
29+
30+ gc "launchpad.net/gocheck"
31+
32+ // juju packages
33+)
34+```
35+
36+
37+setting up tests for new packages
38+---------------------------------
39+
40+Lets say we are creating a new provider for "magic" cloud, and we have a package
41+called "magic" that lives at "launchpad.net/juju-core/provider/magic". The
42+general approach for testing in juju is to have the tests in a separate package.
43+Continuing with this example the tests would be in a package called "magic_test".
44+
45+A common idiom that has occurred in juju is to setup to gocheck hooks in a special
46+file called `package_test.go` that would look like this:
47+
48+
49+```go
50+// Copyright 2014 Canonical Ltd.
51+// Licensed under the AGPLv3, see LICENCE file for details.
52+
53+package magic_test
54+
55+import (
56+ "testing"
57+
58+ gc "launchpad.net/gocheck"
59+)
60+
61+func Test(t *testing.T) {
62+ gc.TestingT(t)
63+}
64+```
65+
66+or
67+
68+```go
69+// Copyright 2014 Canonical Ltd.
70+// Licensed under the AGPLv3, see LICENCE file for details.
71+
72+package magic_test
73+
74+import (
75+ stdtesting "testing"
76+
77+ "launchpad.net/juju-core/testing"
78+)
79+
80+func Test(t *stdtesting.T) {
81+ testing.MgoTestPackage(t)
82+}
83+```
84+
85+The key difference here is that the first one just hooks up `gocheck`
86+so it looks for the `gocheck` suites in the package. The second makes
87+sure that there is a mongo available for the duration of the package tests.
88+
89+A general rule is not to setup mongo for a package unless you really
90+need to as it is extra overhead.
91+
92+
93+writing the test files
94+----------------------
95+
96+Normally there will be a test file for each file with code in the package.
97+For a file called `config.go` there should be a test file called `config_test.go`.
98+
99+The package should in most cases be the same as the normal files with a "_test" suffix.
100+In this way, the tests are testing the same interface as any normal user of the
101+package. It is reasonably common to want to modify some internal aspect of the package
102+under test for the tests. This is normally handled by a file called `export_test.go`.
103+Even though the file ends with `_test.go`, the package definition is the same as the
104+normal source files. In this way, for the tests and only the tests, additional
105+public symbols can be defined for the package and used in the tests.
106+
107+Here is an annotated extract from `provider/local/export_test.go`
108+
109+```go
110+// The package is the "local" so it has access to the package symbols
111+// and not just the public ones.
112+package local
113+
114+import (
115+ "github.com/juju/testing"
116+ gc "launchpad.net/gocheck"
117+
118+ "launchpad.net/juju-core/environs/config"
119+)
120+
121+var (
122+ // checkIfRoot is a variable of type `func() bool`, so CheckIfRoot is
123+ // a pointer to that variable so we can patch it in the tests.
124+ CheckIfRoot = &checkIfRoot
125+ // providerInstance is a pointer to an instance of a private structure.
126+ // Provider points to the same instance, so public methods on that instance
127+ // are available in the tests.
128+ Provider = providerInstance
129+)
130+
131+// ConfigNamespace is a helper function for the test that steps through a
132+// number of private methods or variables, and is an alternative mechanism
133+// to provide functionality for the tests.
134+func ConfigNamespace(cfg *config.Config) string {
135+ env, _ := providerInstance.Open(cfg)
136+ return env.(*localEnviron).config.namespace()
137+}
138+```
139+
140+Suites and Juju base suites
141+---------------------------
142+
143+With gocheck tests are grouped into Suites. Each suite has distinct
144+set-up and tear-down logic. Suites are often composed of other suites
145+that provide specific set-up and tear-down behaviour.
146+
147+There are three main suites:
148+
149+ * /testing/testbase.LoggingSuite (testing/testbase/log.go)
150+ * /testing.FakeHomeSuite (testing/environ.go)
151+ * /juju/testing.JujuConnSuite (juju/testing/conn.go)
152+
153+The second two have the LoggingSuite functionality included through
154+composition. The LoggingSuite is also composed of the LoggingSuite from
155+github.com/juju/testing, which brings in the CleanupSuite from the same.
156+The CleanupSuite has the functionality around patching environment
157+variables and normal variables for the duration of a test. It also
158+provides a clean-up stack that gets called when the test teardown happens.
159+
160+The FakeHomeSuite creates a temporary directory and sets the HOME environment
161+variable to it. It also creates ~/.juju and a simple environments.yaml file,
162+~/.ssh with a fake id_rsa.pub key, it isolates the test from the JUJU_HOME,
163+JUJU_ENV, and JUJU_LOGGING_CONFIG environment variables.
164+
165+The JujuConnSuite does this and more. It also sets up a state server and api
166+server. This is one problem with the JujuConnSuite, it almost always does a
167+lot more than you actually want or need. This should really be broken into
168+smaller component parts that make more sense. If you can get away with not
169+using the JujuConnSuite, you should try.
170+
171+To create a new suite composed of one or more of the suites above, you can do
172+something like:
173+
174+```go
175+type ToolsSuite struct {
176+ testbase.LoggingSuite
177+ dataDir string
178+}
179+
180+var _ = gc.Suite(&ToolsSuite{})
181+
182+```
183+
184+If there is no extra setup needed, then you don't need to specify any
185+set-up or tear-down methods as the LoggingSuite has them, and they are
186+called by default.
187+
188+If you did want to do something, say, create a directory and save it in
189+the dataDir, you would do something like this:
190+
191+```go
192+func (t *ToolsSuite) SetUpTest(c *gc.C) {
193+ t.LoggingSuite.SetUpTest(c)
194+ t.dataDir = c.MkDir()
195+}
196+```
197+
198+If the test suite has multiple contained suites, please call them in the
199+order that they are defined, and make sure something that is composed from
200+the LoggingSuite is first. They should be torn down in the reverse order.
201+
202+Even if the code that is being tested currently has no logging in it, it
203+is a good idea to use the LoggingSuite as a base for two reasons:
204+ * it brings in something composed of the CleanupSuite
205+ * if someone does add logging later, it is captured and doesn't polute
206+ the logging output
207+
208+
209+Patching variables and the environment
210+--------------------------------------
211+
212+Inside a test, and assuming that the Suite has a CleanupSuite somewhere
213+in the composition tree, there are a few very helpful functions.
214+
215+```go
216+
217+var foo int
218+
219+func (s *someTest) TestFubar(c *gc.C) {
220+ // The TEST_OMG environment value will have "new value" for the duration
221+ // of the test.
222+ s.PatchEnvironment("TEST_OMG", "new value")
223+
224+ // foo is set to the value 42 for the duration of the test
225+ s.PatchValue(&foo, 42)
226+}
227+```
228+
229+PatchValue works with any matching type. This includes function variables.
230+
231+
232+Checkers
233+--------
234+
235+Checkers are a core concept of `gocheck` and will feel familiar to anyone
236+who has used the python testtools. Assertions are made on the gocheck.C
237+methods.
238+
239+```go
240+c.Check(err, gc.IsNil)
241+c.Assert(something, gc.Equals, somethingElse)
242+```
243+
244+The `Check` method will cause the test to fail if the checker returns
245+false, but it will continue immediately cause the test to fail and will
246+continue with the test. `Assert` if it fails will cause the test to
247+immediately stop.
248+
249+For the purpose of further discussion, we have the following parts:
250+
251+ `c.Assert(observed, checker, args...)`
252+
253+The key checkers in the `gocheck` module that juju uses most frequently are:
254+
255+ * `IsNil` - the observed value must be `nil`
256+ * `NotNil` - the observed value must not be `nil`
257+ * `Equals` - the observed value must be the same type and value as the arg,
258+ which is the expected value
259+ * `DeepEquals` - checks for equality for more complex types like slices,
260+ maps, or structures. This is DEPRECATED in favour of the DeepEquals from
261+ the `github.com/juju/testing/checkers` covered below
262+ * `ErrorMatches` - the observed value is expected to be an `error`, and
263+ the arg is a string that is a regular expression, and used to match the
264+ error string
265+ * `Matches` - a regular expression match where the observed value is a string
266+ * `HasLen` - the expected value is an integer, and works happily on nil
267+ slices or maps
268+
269+
270+Over time in the juju project there were repeated patterns of testing that
271+were then encoded into new and more complicated checkers. These are found
272+in `github.com/juju/testing/checkers`, and are normally imported with the
273+alias `jc`.
274+
275+The matchers there include (not an exclusive list):
276+
277+ * `IsTrue` - just an easier way to say `gc.Equals, true`
278+ * `IsFalse` - observed value must be false
279+ * `GreaterThan` - for integer or float types
280+ * `LessThan` - for integer or float types
281+ * `HasPrefix` - obtained is expected to be a string or a `Stringer`, and
282+ the string (or string value) must have the arg as start of the string
283+ * `HasSuffix` - the same as `HasPrefix` but checks the end of the string
284+ * `Contains` - obtained is a string or `Stringer` and expected needs to be
285+ a string. The checker passes if the expected string is a substring of the
286+ obtained value.
287+ * `DeepEquals` - works the same way as the `gocheck.DeepEquals` except
288+ gives better errors when the values do not match
289+ * `SameContents` - obtained and expected are slices of the same type,
290+ the checker makes sure that the values in one are in the other. They do
291+ not have the be in the same order.
292+ * `Satisfies` - the arg is expected to be `func(observed) bool`
293+ often used for error type checks
294+ * `IsNonEmptyFile` - obtained is a string or `Stringer` and refers to a
295+ path. The checker passes if the file exists, is a file, and is not empty
296+ * `IsDirectory` - works in a similar way to `IsNonEmptyFile` but passes if
297+ the path element is a directory
298+ * `DoesNotExist` - also works with a string or `Stringer`, and passes if
299+ the path element does not exist
300+
301+
302+
303+Good tests
304+----------
305+
306+Good tests should be:
307+ * small and obviously correct
308+ * isolated from any system or environment values that may impact the test

Subscribers

People subscribed via source and target branches

to status/vote changes: