File: StaticProtoFuzzer.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (63 lines) | stat: -rw-r--r-- 2,053 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
ProtoFuzzer is a mutable class, even when seeded by a compile-time constant.
We're trying to avoid the following pitfalls which can arise when assigning a
ProtoFuzzer to a static field:

*   Accidental state leakage between unit tests, causing non-deterministic or
    flaky behavior. In this scenario, it's recommended to instantiate a distinct
    ProtoFuzzer for each relevant unit test, possibly by using a `@Before`
    method.

``` {.good}
 private ProtoFuzzer protoFuzzer;
 ...
  @Before
  public void setUp() {
    ...
    // Customize as appropriate
    protoFuzzer = ProtoFuzzer.newBuilder().setSeed(...).build();
    ...
  }
```

*   If a static ProtoFuzzer is used to initialize other static fields, then this
    initialization process can have program-order dependency; for example,
    re-ordering two such initialized fields can cause their values to change.
    This problem can be avoided by using static builder methods to initialize.

``` {.bad}
private static final ProtoFuzzer protoFuzzer =
    ProtoFuzzer.newBuilder()
               .setSeed(...)
               .build();
...
// Re-ordering myFirstCustomProto and mySecondCustomProto can change their values!
private static final MyCustomProto myFirstCustomProto =
    protoFuzzer.makeMessageOfType(
      MyCustomProto.getDefaultInstance()
    );
private static final MyCustomProto mySecondCustomProto =
    protoFuzzer.makeMessageOfType(
      MyCustomProto.getDefaultInstance()
    );

```

Instead, create a static builder method and replace references to the static
ProtoFuzzer field with calls to the builder:

``` {.good}

private static final MyCustomProto myFirstCustomProto =
  buildMyCustomProtoFuzzer().makeMessageOfType(
    MyCustomProto.getDefaultInstance()
  );
private static final MyCustomProto mySecondCustomProto =
  buildMyCustomProtoFuzzer().makeMessageOfType(
    MyCustomProto.getDefaultInstance()
  );
...
private static ProtoFuzzer buildMyCustomProtoFuzzer() {
  // Customize as appropriate
  return ProtoFuzzer.newBuilder().setSeed(...).build();
}
```