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.bedstead.metricsrecorder.truth; 18 19 import static com.google.common.truth.Truth.assertAbout; 20 21 import androidx.annotation.Nullable; 22 23 import com.android.bedstead.metricsrecorder.MetricQueryBuilder; 24 25 import com.google.common.truth.Fact; 26 import com.google.common.truth.FailureMetadata; 27 import com.google.common.truth.Subject; 28 29 import java.time.Duration; 30 31 public final class MetricQueryBuilderSubject extends Subject { 32 33 /** 34 * Assertions about {@link MetricQueryBuilder}. 35 */ MetricQueryBuilder()36 public static Factory<MetricQueryBuilderSubject, MetricQueryBuilder> MetricQueryBuilder() { 37 return MetricQueryBuilderSubject::new; 38 } 39 40 /** 41 * Assertions about {@link MetricQueryBuilder}. 42 */ assertThat(@ullable MetricQueryBuilder actual)43 public static MetricQueryBuilderSubject assertThat(@Nullable MetricQueryBuilder actual) { 44 return assertAbout(MetricQueryBuilder()).that(actual); 45 } 46 47 @Nullable private final MetricQueryBuilder mActual; 48 MetricQueryBuilderSubject(FailureMetadata metadata, @Nullable MetricQueryBuilder actual)49 private MetricQueryBuilderSubject(FailureMetadata metadata, @Nullable MetricQueryBuilder actual) { 50 super(metadata, actual); 51 this.mActual = actual; 52 } 53 54 /** 55 * Asserts that an event occurred (that {@link MetricQueryBuilder#poll()} returns non-null). 56 */ wasLogged()57 public void wasLogged() { 58 if (mActual.poll() == null) { 59 // TODO(b/197315353): Add non-matching metrics 60 failWithoutActual(Fact.simpleFact("Expected metric to have been logged matching: " 61 + mActual + " but it was not logged. Did see: " + mActual.nonMatchingMetrics())); 62 } 63 } 64 65 /** 66 * Asserts that an event occurred (that {@link MetricQueryBuilder#poll(Duration)} returns non-null). 67 */ wasLoggedWithin(Duration timeout)68 public void wasLoggedWithin(Duration timeout) { 69 if (mActual.poll(timeout) == null) { 70 // TODO(b/197315353): Add non-matching events 71 failWithoutActual(Fact.simpleFact("Expected metric to have been logged matching: " 72 + mActual + " but it was not logged.")); 73 } 74 } 75 } 76