aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java
blob: 8f480f88f27af726134ce35912656ddb4c8a7f97 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.testutil;

import com.google.common.io.Files;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventCollector;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.util.BlazeClock;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;

import junit.framework.TestCase;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;

/**
 * This is a specialization of {@link TestCase} that's useful for implementing tests of the
 * "foundation" library.
 */
public abstract class FoundationTestCase extends TestCase {

  protected Path rootDirectory;

  protected Path outputBase;

  protected Path actionOutputBase;

  // May be overridden by subclasses:
  protected Reporter reporter;
  protected EventCollector eventCollector;

  protected Scratch scratch;


  // Individual tests can opt-out of this handler if they expect an error, by
  // calling reporter.removeHandler(failFastHandler).
  protected static final EventHandler failFastHandler = new EventHandler() {
      @Override
      public void handle(Event event) {
        if (EventKind.ERRORS.contains(event.getKind())) {
          fail(event.toString());
        }
      }
    };

  protected static final EventHandler printHandler = new EventHandler() {
      @Override
      public void handle(Event event) {
        System.out.println(event);
      }
    };

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    scratch = new Scratch(createFileSystem());
    outputBase = scratch.dir("/usr/local/google/_blaze_jrluser/FAKEMD5/");
    rootDirectory = scratch.dir("/" + TestConstants.TEST_WORKSPACE_DIRECTORY);
    scratchFile(rootDirectory.getRelative("WORKSPACE").getPathString(),
        "bind(",
        "  name = 'objc_proto_lib',",
        "  actual = '//objcproto:ProtocolBuffers_lib',",
        ")",
        "bind(",
        "  name = 'objc_proto_cpp_lib',",
        "  actual = '//objcproto:ProtocolBuffersCPP_lib',",
        ")");
    copySkylarkFilesIfExist();
    actionOutputBase = scratch.dir("/usr/local/google/_blaze_jrluser/FAKEMD5/action_out/");
    eventCollector = new EventCollector(EventKind.ERRORS_AND_WARNINGS);
    reporter = new Reporter(eventCollector);
    reporter.addHandler(failFastHandler);
  }

  /*
   * Creates the file system; override to inject FS behavior.
   */
  protected FileSystem createFileSystem() {
     return new InMemoryFileSystem(BlazeClock.instance());
  }

  private void copySkylarkFilesIfExist() throws IOException {
    scratchFile(rootDirectory.getRelative("devtools/blaze/rules/BUILD").getPathString());
    scratchFile(rootDirectory.getRelative("rules/BUILD").getPathString());
    copySkylarkFilesIfExist("devtools/blaze/rules/staging", "devtools/blaze/rules/staging");
    copySkylarkFilesIfExist("third_party/bazel/tools/build_rules", "rules");
  }

  private void copySkylarkFilesIfExist(String from, String to) throws IOException {
    File rulesDir = new File(from);
    if (rulesDir.exists() && rulesDir.isDirectory()) {
      for (String fileName : rulesDir.list()) {
        File file = new File(from + "/" + fileName);
        if (file.isFile() && fileName.endsWith(".bzl")) {
          String context = loadFile(file);
          Path path = rootDirectory.getRelative(to + "/" + fileName);
          if (path.exists()) {
            overwriteScratchFile(path.getPathString(), context);
          } else {
            scratchFile(path.getPathString(), context);
          }
        }
      }
    }
  }

  @Override
  protected void tearDown() throws Exception {
    Thread.interrupted(); // Clear any interrupt pending against this thread,
                          // so that we don't cause later tests to fail.

    super.tearDown();
  }

  /**
   * A scratch filesystem that is completely in-memory. Since this file system
   * is "cached" in a private (but *not* static) field in the test class,
   * each testFoo method in junit sees a fresh filesystem.
   */
  protected FileSystem scratchFS() {
    return scratch.getFileSystem();
  }

  private String workspaceRelative(String pathName) {
    if (!pathName.startsWith("/")) {
      return "/" + TestConstants.TEST_WORKSPACE_DIRECTORY + "/" + pathName;
    }
    return pathName;
  }

  /**
   * Create a scratch file in the scratch filesystem, with the given pathName,
   * consisting of a set of lines. The method returns a Path instance for the
   * scratch file.
   */
  protected Path scratchFile(String pathName, String... lines) throws IOException {
    return scratch.file(workspaceRelative(pathName), lines);
  }

  /**
   * Create a scratch directory in the scratch filesystem, with the given pathName. The method
   * returns a Path instance for the scratch directory.
   */
  protected Path scratchDir(String pathName) throws IOException {
    return scratch.dir(workspaceRelative(pathName));
  }

  /**
   * Like {@code scratchFile}, but the file is first deleted if it already
   * exists.
   */
  protected Path overwriteScratchFile(String pathName, String... lines) throws IOException {
    return scratch.overwriteFile(workspaceRelative(pathName), lines);
  }

  /**
   * Create a scratch file in the given filesystem, with the given pathName,
   * consisting of a set of lines. The method returns a Path instance for the
   * scratch file.
   */
  protected Path scratchFile(FileSystem fs, String pathName, String... lines)
      throws IOException {
    return scratch.file(fs, workspaceRelative(pathName), lines);
  }

  /**
   * Create a scratch file in the given filesystem, with the given pathName,
   * consisting of a set of lines. The method returns a Path instance for the
   * scratch file.
   */
  protected Path scratchFile(FileSystem fs, String pathName, byte[] content)
      throws IOException {
    return scratch.file(fs, workspaceRelative(pathName), content);
  }

  /**
   * Create a scratch file in the scratch filesystem, with the given pathName,
   * consisting of a set of lines. The method returns a Path instance for the
   * scratch file.
   */
  protected void deleteFile(String pathName) throws IOException {
    scratch.deleteFile(workspaceRelative(pathName));
  }

  // Mix-in assertions:

  protected void assertNoEvents() {
    JunitTestUtils.assertNoEvents(eventCollector);
  }

  protected Event assertContainsEvent(String expectedMessage) {
    return JunitTestUtils.assertContainsEvent(eventCollector,
                                              expectedMessage);
  }

  protected Event assertContainsEvent(String expectedMessage, Set<EventKind> kinds) {
    return JunitTestUtils.assertContainsEvent(eventCollector,
                                              expectedMessage,
                                              kinds);
  }

  protected void assertContainsEventWithFrequency(String expectedMessage,
      int expectedFrequency) {
    JunitTestUtils.assertContainsEventWithFrequency(eventCollector, expectedMessage,
        expectedFrequency);
  }

  protected void assertDoesNotContainEvent(String expectedMessage) {
    JunitTestUtils.assertDoesNotContainEvent(eventCollector,
                                             expectedMessage);
  }

  protected Event assertContainsEventWithWordsInQuotes(String... words) {
    return JunitTestUtils.assertContainsEventWithWordsInQuotes(
        eventCollector, words);
  }

  protected void assertContainsEventsInOrder(String... expectedMessages) {
    JunitTestUtils.assertContainsEventsInOrder(eventCollector, expectedMessages);
  }

  @SuppressWarnings({"unchecked", "varargs"})
  protected static <T> void assertContainsSublist(List<T> arguments,
                                                  T... expectedSublist) {
    JunitTestUtils.assertContainsSublist(arguments, expectedSublist);
  }

  @SuppressWarnings({"unchecked", "varargs"})
  protected static <T> void assertDoesNotContainSublist(List<T> arguments,
                                                        T... expectedSublist) {
    JunitTestUtils.assertDoesNotContainSublist(arguments, expectedSublist);
  }

  protected static <T> void assertContainsSubset(Iterable<T> arguments,
                                                 Iterable<T> expectedSubset) {
    JunitTestUtils.assertContainsSubset(arguments, expectedSubset);
  }

  protected String loadFile(File file) throws IOException {
    return Files.toString(file, Charset.defaultCharset());
  }
}