guava

Форк
0
100 строк · 2.8 Кб
1
/*
2
 * Copyright (C) 2008 The Guava Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 * http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package com.google.common.testing;
18

19
import com.google.common.annotations.GwtCompatible;
20
import com.google.errorprone.annotations.concurrent.GuardedBy;
21
import java.util.ArrayList;
22
import java.util.Collections;
23
import java.util.List;
24
import java.util.logging.Handler;
25
import java.util.logging.LogRecord;
26
import org.checkerframework.checker.nullness.qual.Nullable;
27

28
/**
29
 * Tests may use this to intercept messages that are logged by the code under test. Example:
30
 *
31
 * <pre>
32
 *   TestLogHandler handler;
33
 *
34
 *   protected void setUp() throws Exception {
35
 *     super.setUp();
36
 *     handler = new TestLogHandler();
37
 *     SomeClass.logger.addHandler(handler);
38
 *     addTearDown(new TearDown() {
39
 *       public void tearDown() throws Exception {
40
 *         SomeClass.logger.removeHandler(handler);
41
 *       }
42
 *     });
43
 *   }
44
 *
45
 *   public void test() {
46
 *     SomeClass.foo();
47
 *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
48
 *     assertEquals("some message", firstRecord.getMessage());
49
 *   }
50
 * </pre>
51
 *
52
 * @author Kevin Bourrillion
53
 * @since 10.0
54
 */
55
@GwtCompatible
56
@ElementTypesAreNonnullByDefault
57
public class TestLogHandler extends Handler {
58
  private final Object lock = new Object();
59

60
  /** We will keep a private list of all logged records */
61
  @GuardedBy("lock")
62
  private final List<LogRecord> list = new ArrayList<>();
63

64
  /** Adds the most recently logged record to our list. */
65
  @Override
66
  public void publish(@Nullable LogRecord record) {
67
    synchronized (lock) {
68
      if (record != null) {
69
        list.add(record);
70
      }
71
    }
72
  }
73

74
  @Override
75
  public void flush() {}
76

77
  @Override
78
  public void close() {}
79

80
  public void clear() {
81
    synchronized (lock) {
82
      list.clear();
83
    }
84
  }
85

86
  /** Returns a snapshot of the logged records. */
87
  /*
88
   * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
89
   * getOnlyRecordLogged(), getAndClearLogRecords()...)
90
   *
91
   * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
92
   * an ImmutableList)
93
   */
94
  public List<LogRecord> getStoredLogRecords() {
95
    synchronized (lock) {
96
      List<LogRecord> result = new ArrayList<>(list);
97
      return Collections.unmodifiableList(result);
98
    }
99
  }
100
}
101

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.