1 /* 2 * Copyright (C) 2021 The Android Open Source Project 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.android.eventlib.truth; 18 19 import static com.google.common.truth.Truth.assertAbout; 20 21 import androidx.annotation.Nullable; 22 23 import com.android.eventlib.Event; 24 import com.android.eventlib.EventLogs; 25 26 import com.google.common.truth.Fact; 27 import com.google.common.truth.FailureMetadata; 28 import com.google.common.truth.Subject; 29 30 import java.time.Duration; 31 32 /** {@link Subject} for queries about {@link EventLogs}. */ 33 public final class EventLogsSubject<E extends Event> extends Subject { 34 35 /** 36 * Assertions about {@link EventLogs}. 37 */ eventLogs()38 public static <F extends Event> Factory<EventLogsSubject<F>, EventLogs<F>> eventLogs() { 39 return EventLogsSubject::new; 40 } 41 42 /** 43 * Assertions about {@link EventLogs}. 44 */ assertThat(@ullable EventLogs<F> actual)45 public static <F extends Event> EventLogsSubject<F> assertThat(@Nullable EventLogs<F> actual) { 46 return assertAbout(EventLogsSubject.<F>eventLogs()).that(actual); 47 } 48 49 @Nullable private final EventLogs<E> mActual; 50 EventLogsSubject(FailureMetadata metadata, @Nullable EventLogs<E> actual)51 private EventLogsSubject(FailureMetadata metadata, @Nullable EventLogs<E> actual) { 52 super(metadata, actual); 53 this.mActual = actual; 54 } 55 56 /** 57 * Asserts that an event occurred (that {@link EventLogs#poll()} returns non-null). 58 */ eventOccurred()59 public E eventOccurred() { 60 E event = mActual.poll(); 61 62 if (event == null) { 63 fail(); 64 } 65 66 return event; 67 } 68 69 /** 70 * Asserts that an event occurred (that {@link EventLogs#poll(Duration)} returns non-null). 71 */ eventOccurredWithin(Duration timeout)72 public E eventOccurredWithin(Duration timeout) { 73 E event = mActual.poll(timeout); 74 75 if (event == null) { 76 fail(); 77 } 78 79 return event; 80 } 81 fail()82 private void fail() { 83 // TODO(b/197315353): Add non-matching events 84 failWithoutActual(Fact.simpleFact("Expected event to have occurred matching: " 85 + mActual + " but it did not occur.")); 86 } 87 } 88