aboutsummaryrefslogtreecommitdiffstats
path: root/api/src/test
diff options
context:
space:
mode:
authorsebright <sebright@google.com>2017-10-23 17:13:14 -0700
committerBogdan Drutu <bdrutu@google.com>2017-10-23 17:13:14 -0700
commit92e363fb2daa1a8aee308d3bd5fc20c9e83eeab2 (patch)
tree34cf4a254947a69b24ed522f997d15c072bfe8e4 /api/src/test
parente69bb99d61c529fc9ad8c0be83d1f438c93a63af (diff)
downloadplatform_external_opencensus-java-92e363fb2daa1a8aee308d3bd5fc20c9e83eeab2.tar.gz
platform_external_opencensus-java-92e363fb2daa1a8aee308d3bd5fc20c9e83eeab2.tar.bz2
platform_external_opencensus-java-92e363fb2daa1a8aee308d3bd5fc20c9e83eeab2.zip
Move stats and tags packages to opencensus-api to prepare for release. (#723)
Diffstat (limited to 'api/src/test')
-rw-r--r--api/src/test/java/io/opencensus/stats/AggregationDataTest.java168
-rw-r--r--api/src/test/java/io/opencensus/stats/AggregationTest.java119
-rw-r--r--api/src/test/java/io/opencensus/stats/BucketBoundariesTest.java90
-rw-r--r--api/src/test/java/io/opencensus/stats/MeasureMapTest.java132
-rw-r--r--api/src/test/java/io/opencensus/stats/MeasureTest.java155
-rw-r--r--api/src/test/java/io/opencensus/stats/NoopStatsTest.java118
-rw-r--r--api/src/test/java/io/opencensus/stats/NoopViewManagerTest.java134
-rw-r--r--api/src/test/java/io/opencensus/stats/StatsRecorderTest.java81
-rw-r--r--api/src/test/java/io/opencensus/stats/StatsTest.java82
-rw-r--r--api/src/test/java/io/opencensus/stats/ViewDataTest.java221
-rw-r--r--api/src/test/java/io/opencensus/stats/ViewTest.java162
-rw-r--r--api/src/test/java/io/opencensus/tags/InternalUtilsTest.java49
-rw-r--r--api/src/test/java/io/opencensus/tags/NoopTagsTest.java192
-rw-r--r--api/src/test/java/io/opencensus/tags/TagContextTest.java106
-rw-r--r--api/src/test/java/io/opencensus/tags/TagKeyTest.java156
-rw-r--r--api/src/test/java/io/opencensus/tags/TagTest.java158
-rw-r--r--api/src/test/java/io/opencensus/tags/TagValueTest.java154
-rw-r--r--api/src/test/java/io/opencensus/tags/TagsTest.java85
-rw-r--r--api/src/test/java/io/opencensus/tags/propagation/TagContextParseExceptionTest.java42
-rw-r--r--api/src/test/java/io/opencensus/tags/unsafe/ContextUtilsTest.java62
20 files changed, 2466 insertions, 0 deletions
diff --git a/api/src/test/java/io/opencensus/stats/AggregationDataTest.java b/api/src/test/java/io/opencensus/stats/AggregationDataTest.java
new file mode 100644
index 00000000..3eafd18e
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/AggregationDataTest.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.stats.AggregationData.CountData;
+import io.opencensus.stats.AggregationData.DistributionData;
+import io.opencensus.stats.AggregationData.MeanData;
+import io.opencensus.stats.AggregationData.SumDataDouble;
+import io.opencensus.stats.AggregationData.SumDataLong;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link io.opencensus.stats.AggregationData}. */
+@RunWith(JUnit4.class)
+public class AggregationDataTest {
+
+ private static final double TOLERANCE = 1e-6;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testCreateDistributionData() {
+ DistributionData distributionData = DistributionData.create(
+ 7.7, 10, 1.1, 9.9, 32.2, new long[]{4, 1, 5});
+ assertThat(distributionData.getMean()).isWithin(TOLERANCE).of(7.7);
+ assertThat(distributionData.getCount()).isEqualTo(10);
+ assertThat(distributionData.getMin()).isWithin(TOLERANCE).of(1.1);
+ assertThat(distributionData.getMax()).isWithin(TOLERANCE).of(9.9);
+ assertThat(distributionData.getSumOfSquaredDeviations()).isWithin(TOLERANCE).of(32.2);
+ assertThat(distributionData.getBucketCounts()).containsExactly(4L, 1L, 5L).inOrder();
+ }
+
+ @Test
+ public void preventNullBucketCountData() {
+ thrown.expect(NullPointerException.class);
+ thrown.expectMessage("bucket counts should not be null.");
+ DistributionData.create(1, 1, 1, 1, 0, null);
+ }
+
+ @Test
+ public void preventMinIsGreaterThanMax() {
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("max should be greater or equal to min.");
+ DistributionData.create(1, 1, 10, 1, 0, new long[]{0, 1, 0});
+ }
+
+ @Test
+ public void testEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ SumDataDouble.create(10.0),
+ SumDataDouble.create(10.0))
+ .addEqualityGroup(
+ SumDataDouble.create(20.0),
+ SumDataDouble.create(20.0))
+ .addEqualityGroup(
+ SumDataLong.create(20),
+ SumDataLong.create(20))
+ .addEqualityGroup(
+ CountData.create(40),
+ CountData.create(40))
+ .addEqualityGroup(
+ CountData.create(80),
+ CountData.create(80))
+ .addEqualityGroup(
+ DistributionData.create(10, 10, 1, 1, 0, new long[]{0, 10, 0}),
+ DistributionData.create(10, 10, 1, 1, 0, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ DistributionData.create(10, 10, 1, 1, 0, new long[]{0, 10, 100}))
+ .addEqualityGroup(
+ DistributionData.create(110, 10, 1, 1, 0, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ DistributionData.create(10, 110, 1, 1, 0, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ DistributionData.create(10, 10, -1, 1, 0, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ DistributionData.create(10, 10, 1, 5, 0, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ DistributionData.create(10, 10, 1, 1, 55.5, new long[]{0, 10, 0}))
+ .addEqualityGroup(
+ MeanData.create(5.0, 1),
+ MeanData.create(5.0, 1))
+ .addEqualityGroup(
+ MeanData.create(-5.0, 1),
+ MeanData.create(-5.0, 1))
+ .testEquals();
+ }
+
+ @Test
+ public void testMatchAndGet() {
+ List<AggregationData> aggregations = Arrays.asList(
+ SumDataDouble.create(10.0),
+ SumDataLong.create(100000000),
+ CountData.create(40),
+ MeanData.create(5.0, 1),
+ DistributionData.create(1, 1, 1, 1, 0, new long[]{0, 10, 0}));
+
+ final List<Object> actual = new ArrayList<Object>();
+ for (AggregationData aggregation : aggregations) {
+ aggregation.match(
+ new Function<SumDataDouble, Void>() {
+ @Override
+ public Void apply(SumDataDouble arg) {
+ actual.add(arg.getSum());
+ return null;
+ }
+ },
+ new Function<SumDataLong, Void>() {
+ @Override
+ public Void apply(SumDataLong arg) {
+ actual.add(arg.getSum());
+ return null;
+ }
+ },
+ new Function<CountData, Void>() {
+ @Override
+ public Void apply(CountData arg) {
+ actual.add(arg.getCount());
+ return null;
+ }
+ },
+ new Function<MeanData, Void>() {
+ @Override
+ public Void apply(MeanData arg) {
+ actual.add(arg.getMean());
+ return null;
+ }
+ },
+ new Function<DistributionData, Void>() {
+ @Override
+ public Void apply(DistributionData arg) {
+ actual.add(arg.getBucketCounts());
+ return null;
+ }
+ },
+ Functions.<Void>throwIllegalArgumentException());
+ }
+
+ assertThat(actual).isEqualTo(
+ Arrays.asList(10.0, 100000000L, 40L, 5.0, Arrays.asList(0L, 10L, 0L)));
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/AggregationTest.java b/api/src/test/java/io/opencensus/stats/AggregationTest.java
new file mode 100644
index 00000000..66376cbb
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/AggregationTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.stats.Aggregation.Count;
+import io.opencensus.stats.Aggregation.Distribution;
+import io.opencensus.stats.Aggregation.Mean;
+import io.opencensus.stats.Aggregation.Sum;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link io.opencensus.stats.Aggregation}. */
+@RunWith(JUnit4.class)
+public class AggregationTest {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testCreateDistribution() {
+ BucketBoundaries bucketBoundaries = BucketBoundaries.create(Arrays.asList(0.1, 2.2, 33.3));
+ Distribution distribution = Distribution.create(bucketBoundaries);
+ assertThat(distribution.getBucketBoundaries()).isEqualTo(bucketBoundaries);
+ }
+
+ @Test
+ public void testNullBucketBoundaries() {
+ thrown.expect(NullPointerException.class);
+ thrown.expectMessage("bucketBoundaries should not be null.");
+ Distribution.create(null);
+ }
+
+ @Test
+ public void testEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ Sum.create(),
+ Sum.create())
+ .addEqualityGroup(
+ Count.create(),
+ Count.create())
+ .addEqualityGroup(
+ Distribution.create(BucketBoundaries.create(Arrays.asList(-10.0, 1.0, 5.0))),
+ Distribution.create(BucketBoundaries.create(Arrays.asList(-10.0, 1.0, 5.0))))
+ .addEqualityGroup(
+ Distribution.create(BucketBoundaries.create(Arrays.asList(0.0, 1.0, 5.0))),
+ Distribution.create(BucketBoundaries.create(Arrays.asList(0.0, 1.0, 5.0))))
+ .addEqualityGroup(
+ Mean.create(),
+ Mean.create())
+ .testEquals();
+ }
+
+ @Test
+ public void testMatch() {
+ List<Aggregation> aggregations = Arrays.asList(
+ Sum.create(),
+ Count.create(),
+ Mean.create(),
+ Distribution.create(BucketBoundaries.create(Arrays.asList(-10.0, 1.0, 5.0))));
+
+ List<String> actual = new ArrayList<String>();
+ for (Aggregation aggregation : aggregations) {
+ actual.add(aggregation.match(
+ new Function<Sum, String>() {
+ @Override
+ public String apply(Sum arg) {
+ return "SUM";
+ }
+ },
+ new Function<Count, String>() {
+ @Override
+ public String apply(Count arg) {
+ return "COUNT";
+ }
+ },
+ new Function<Mean, String>() {
+ @Override
+ public String apply(Mean arg) {
+ return "MEAN";
+ }
+ },
+ new Function<Distribution, String>() {
+ @Override
+ public String apply(Distribution arg) {
+ return "DISTRIBUTION";
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()));
+ }
+
+ assertThat(actual).isEqualTo(Arrays.asList("SUM", "COUNT", "MEAN", "DISTRIBUTION"));
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/BucketBoundariesTest.java b/api/src/test/java/io/opencensus/stats/BucketBoundariesTest.java
new file mode 100644
index 00000000..e3fd3222
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/BucketBoundariesTest.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Unit tests for {@link io.opencensus.stats.BucketBoundaries}.
+ */
+@RunWith(JUnit4.class)
+public class BucketBoundariesTest {
+
+ @Rule
+ public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testConstructBoundaries() {
+ List<Double> buckets = Arrays.asList(0.0, 1.0, 2.0);
+ BucketBoundaries bucketBoundaries = BucketBoundaries.create(buckets);
+ assertThat(bucketBoundaries.getBoundaries()).isEqualTo(buckets);
+ }
+
+ @Test
+ public void testBoundariesDoesNotChangeWithOriginalList() {
+ List<Double> original = new ArrayList<Double>();
+ original.add(0.0);
+ original.add(1.0);
+ original.add(2.0);
+ BucketBoundaries bucketBoundaries = BucketBoundaries.create(original);
+ original.set(2, 3.0);
+ original.add(4.0);
+ List<Double> expected = Arrays.asList(0.0, 1.0, 2.0);
+ assertThat(bucketBoundaries.getBoundaries()).isNotEqualTo(original);
+ assertThat(bucketBoundaries.getBoundaries()).isEqualTo(expected);
+ }
+
+ @Test
+ public void testNullBoundaries() throws Exception {
+ thrown.expect(NullPointerException.class);
+ BucketBoundaries.create(null);
+ }
+
+ @Test
+ public void testUnsortedBoundaries() throws Exception {
+ List<Double> buckets = Arrays.asList(0.0, 1.0, 1.0);
+ thrown.expect(IllegalArgumentException.class);
+ BucketBoundaries.create(buckets);
+ }
+
+ @Test
+ public void testNoBoundaries() {
+ List<Double> buckets = Arrays.asList();
+ BucketBoundaries bucketBoundaries = BucketBoundaries.create(buckets);
+ assertThat(bucketBoundaries.getBoundaries()).isEqualTo(buckets);
+ }
+
+ @Test
+ public void testBucketBoundariesEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ BucketBoundaries.create(Arrays.asList(-1.0, 2.0)),
+ BucketBoundaries.create(Arrays.asList(-1.0, 2.0)))
+ .addEqualityGroup(BucketBoundaries.create(Arrays.asList(-1.0)))
+ .testEquals();
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/MeasureMapTest.java b/api/src/test/java/io/opencensus/stats/MeasureMapTest.java
new file mode 100644
index 00000000..1a408e85
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/MeasureMapTest.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2016-17, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import io.opencensus.stats.Measure.MeasureDouble;
+import io.opencensus.stats.Measure.MeasureLong;
+import io.opencensus.stats.Measurement.MeasurementDouble;
+import io.opencensus.stats.Measurement.MeasurementLong;
+import java.util.ArrayList;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link MeasureMap}. */
+@RunWith(JUnit4.class)
+public class MeasureMapTest {
+
+ @Test
+ public void testPutDouble() {
+ MeasureMap metrics = MeasureMap.builder().put(M1, 44.4).build();
+ assertContains(metrics, MeasurementDouble.create(M1, 44.4));
+ }
+
+ @Test
+ public void testPutLong() {
+ MeasureMap metrics = MeasureMap.builder().put(M3, 9999L).put(M4, 8888L).build();
+ assertContains(metrics,
+ MeasurementLong.create(M3, 9999L),
+ MeasurementLong.create(M4, 8888L));
+ }
+
+ @Test
+ public void testCombination() {
+ MeasureMap metrics =
+ MeasureMap.builder().put(M1, 44.4).put(M2, 66.6).put(M3, 9999L).put(M4, 8888L).build();
+ assertContains(metrics,
+ MeasurementDouble.create(M1, 44.4),
+ MeasurementDouble.create(M2, 66.6),
+ MeasurementLong.create(M3, 9999L),
+ MeasurementLong.create(M4, 8888L));
+ }
+
+ @Test
+ public void testBuilderEmpty() {
+ MeasureMap metrics = MeasureMap.builder().build();
+ assertContains(metrics);
+ }
+
+ @Test
+ public void testBuilder() {
+ ArrayList<Measurement> expected = new ArrayList<Measurement>(10);
+ MeasureMap.Builder builder = MeasureMap.builder();
+ for (int i = 1; i <= 10; i++) {
+ expected
+ .add(MeasurementDouble.create(makeSimpleMeasureDouble("m" + i), i * 11.1));
+ builder.put(makeSimpleMeasureDouble("m" + i), i * 11.1);
+ assertContains(builder.build(), expected.toArray(new Measurement[i]));
+ }
+ }
+
+ @Test
+ public void testDuplicateMeasureDoubles() {
+ assertContains(MeasureMap.builder().put(M1, 1.0).put(M1, 2.0).build(),
+ MeasurementDouble.create(M1, 2.0));
+ assertContains(MeasureMap.builder().put(M1, 1.0).put(M1, 2.0).put(M1, 3.0).build(),
+ MeasurementDouble.create(M1, 3.0));
+ assertContains(MeasureMap.builder().put(M1, 1.0).put(M2, 2.0).put(M1, 3.0).build(),
+ MeasurementDouble.create(M1, 3.0),
+ MeasurementDouble.create(M2, 2.0));
+ assertContains(MeasureMap.builder().put(M1, 1.0).put(M1, 2.0).put(M2, 2.0).build(),
+ MeasurementDouble.create(M1, 2.0),
+ MeasurementDouble.create(M2, 2.0));
+ }
+
+ @Test
+ public void testDuplicateMeasureLongs() {
+ assertContains(MeasureMap.builder().put(M3, 100L).put(M3, 100L).build(),
+ MeasurementLong.create(M3, 100L));
+ assertContains(MeasureMap.builder().put(M3, 100L).put(M3, 200L).put(M3, 300L).build(),
+ MeasurementLong.create(M3, 300L));
+ assertContains(MeasureMap.builder().put(M3, 100L).put(M4, 200L).put(M3, 300L).build(),
+ MeasurementLong.create(M3, 300L),
+ MeasurementLong.create(M4, 200L));
+ assertContains(MeasureMap.builder().put(M3, 100L).put(M3, 200L).put(M4, 200L).build(),
+ MeasurementLong.create(M3, 200L),
+ MeasurementLong.create(M4, 200L));
+ }
+
+ @Test
+ public void testDuplicateMeasures() {
+ assertContains(MeasureMap.builder().put(M3, 100L).put(M1, 1.0).put(M3, 300L).build(),
+ MeasurementLong.create(M3, 300L),
+ MeasurementDouble.create(M1, 1.0));
+ assertContains(MeasureMap.builder().put(M2, 2.0).put(M3, 100L).put(M2, 3.0).build(),
+ MeasurementDouble.create(M2, 3.0),
+ MeasurementLong.create(M3, 100L));
+ }
+
+ private static final MeasureDouble M1 = makeSimpleMeasureDouble("m1");
+ private static final MeasureDouble M2 = makeSimpleMeasureDouble("m2");
+ private static final MeasureLong M3 = makeSimpleMeasureLong("m3");
+ private static final MeasureLong M4 = makeSimpleMeasureLong("m4");
+
+ private static MeasureDouble makeSimpleMeasureDouble(String measure) {
+ return Measure.MeasureDouble.create(measure, measure + " description", "1");
+ }
+
+ private static MeasureLong makeSimpleMeasureLong(String measure) {
+ return Measure.MeasureLong.create(measure, measure + " description", "1");
+ }
+
+ private static void assertContains(MeasureMap metrics, Measurement... measurements) {
+ assertThat(Lists.newArrayList(metrics.iterator())).containsExactly((Object[]) measurements);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/MeasureTest.java b/api/src/test/java/io/opencensus/stats/MeasureTest.java
new file mode 100644
index 00000000..d243637a
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/MeasureTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2016-17, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.stats.Measure.MeasureDouble;
+import io.opencensus.stats.Measure.MeasureLong;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link Measure}. */
+@RunWith(JUnit4.class)
+public final class MeasureTest {
+
+ @Rule
+ public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testConstants() {
+ assertThat(Measure.NAME_MAX_LENGTH).isEqualTo(256);
+ }
+
+ @Test
+ public void preventTooLongMeasureName() {
+ char[] chars = new char[Measure.NAME_MAX_LENGTH + 1];
+ Arrays.fill(chars, 'a');
+ String longName = String.valueOf(chars);
+ thrown.expect(IllegalArgumentException.class);
+ Measure.MeasureDouble.create(longName, "description", "1");
+ }
+
+ @Test
+ public void preventNonPrintableMeasureName() {
+ thrown.expect(IllegalArgumentException.class);
+ Measure.MeasureDouble.create("\2", "description", "1");
+ }
+
+ @Test
+ public void testMeasureDoubleComponents() {
+ Measure measurement = Measure.MeasureDouble.create(
+ "Foo",
+ "The description of Foo",
+ "Mbit/s");
+ assertThat(measurement.getName()).isEqualTo("Foo");
+ assertThat(measurement.getDescription()).isEqualTo("The description of Foo");
+ assertThat(measurement.getUnit()).isEqualTo("Mbit/s");
+ }
+
+ @Test
+ public void testMeasureLongComponents() {
+ Measure measurement = Measure.MeasureLong.create(
+ "Bar",
+ "The description of Bar",
+ "1");
+ assertThat(measurement.getName()).isEqualTo("Bar");
+ assertThat(measurement.getDescription()).isEqualTo("The description of Bar");
+ assertThat(measurement.getUnit()).isEqualTo("1");
+ }
+
+ @Test
+ public void testMeasureDoubleEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ Measure.MeasureDouble.create(
+ "name",
+ "description",
+ "bit/s"),
+ Measure.MeasureDouble.create(
+ "name",
+ "description",
+ "bit/s"))
+ .addEqualityGroup(
+ Measure.MeasureDouble.create(
+ "name",
+ "description 2",
+ "bit/s"))
+ .testEquals();
+ }
+
+ @Test
+ public void testMeasureLongEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ Measure.MeasureLong.create(
+ "name",
+ "description",
+ "bit/s"),
+ Measure.MeasureLong.create(
+ "name",
+ "description",
+ "bit/s"))
+ .addEqualityGroup(
+ Measure.MeasureLong.create(
+ "name",
+ "description 2",
+ "bit/s"))
+ .testEquals();
+ }
+
+ @Test
+ public void testMatch() {
+ List<Measure> measures = Arrays.asList(
+ MeasureDouble.create("measure1", "description", "1"),
+ MeasureLong.create("measure2", "description", "1"));
+ List<String> outputs = Lists.newArrayList();
+ for (Measure measure : measures) {
+ outputs.add(
+ measure.match(
+ new Function<MeasureDouble, String>() {
+ @Override
+ public String apply(MeasureDouble arg) {
+ return "double";
+ }
+ },
+ new Function<MeasureLong, String>() {
+ @Override
+ public String apply(MeasureLong arg) {
+ return "long";
+ }
+ },
+ Functions.<String>throwAssertionError()));
+ }
+ assertThat(outputs).containsExactly("double", "long").inOrder();
+ }
+
+ @Test
+ public void testMeasureDoubleIsNotEqualToMeasureLong() {
+ assertThat(Measure.MeasureDouble.create("name", "description", "bit/s"))
+ .isNotEqualTo(Measure.MeasureLong.create("name", "description", "bit/s"));
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/NoopStatsTest.java b/api/src/test/java/io/opencensus/stats/NoopStatsTest.java
new file mode 100644
index 00000000..8348adc4
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/NoopStatsTest.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import io.opencensus.stats.Measure.MeasureDouble;
+import io.opencensus.tags.Tag;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagContext;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueString;
+import java.util.Collections;
+import java.util.Iterator;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Unit tests for {@link NoopStats}. Tests for {@link NoopStats#newNoopViewManager} are in {@link
+ * NoopViewManagerTest}
+ */
+@RunWith(JUnit4.class)
+public final class NoopStatsTest {
+ private static final TagString TAG =
+ TagString.create(TagKeyString.create("key"), TagValueString.create("value"));
+ private static final MeasureDouble MEASURE =
+ Measure.MeasureDouble.create("my measure", "description", "s");
+
+ private final TagContext tagContext =
+ new TagContext() {
+
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return Collections.<Tag>singleton(TAG).iterator();
+ }
+ };
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void noopStatsComponent() {
+ assertThat(NoopStats.newNoopStatsComponent().getStatsRecorder())
+ .isSameAs(NoopStats.getNoopStatsRecorder());
+ assertThat(NoopStats.newNoopStatsComponent().getViewManager())
+ .isInstanceOf(NoopStats.newNoopViewManager().getClass());
+ }
+
+ @Test
+ public void noopStatsComponent_GetState() {
+ assertThat(NoopStats.newNoopStatsComponent().getState())
+ .isEqualTo(StatsCollectionState.DISABLED);
+ }
+
+ @Test
+ public void noopStatsComponent_SetState_IgnoresInput() {
+ StatsComponent noopStatsComponent = NoopStats.newNoopStatsComponent();
+ noopStatsComponent.setState(StatsCollectionState.ENABLED);
+ assertThat(noopStatsComponent.getState()).isEqualTo(StatsCollectionState.DISABLED);
+ }
+
+ @Test
+ public void noopStatsComponent_SetState_DisallowsNull() {
+ StatsComponent noopStatsComponent = NoopStats.newNoopStatsComponent();
+ thrown.expect(NullPointerException.class);
+ noopStatsComponent.setState(null);
+ }
+
+ // The NoopStatsRecorder should do nothing, so this test just checks that record doesn't throw an
+ // exception.
+ @Test
+ public void noopStatsRecorder_Record() {
+ NoopStats.getNoopStatsRecorder()
+ .record(tagContext, MeasureMap.builder().put(MEASURE, 5).build());
+ }
+
+ // The NoopStatsRecorder should do nothing, so this test just checks that record doesn't throw an
+ // exception.
+ @Test
+ public void noopStatsRecorder_RecordWithCurrentContext() {
+ NoopStats.getNoopStatsRecorder().record(MeasureMap.builder().put(MEASURE, 6).build());
+ }
+
+ @Test
+ public void noopStatsRecorder_Record_DisallowNullTagContext() {
+ MeasureMap measures = MeasureMap.builder().put(MEASURE, 7).build();
+ thrown.expect(NullPointerException.class);
+ NoopStats.getNoopStatsRecorder().record(null, measures);
+ }
+
+ @Test
+ public void noopStatsRecorder_Record_DisallowNullMeasureMap() {
+ thrown.expect(NullPointerException.class);
+ NoopStats.getNoopStatsRecorder().record(tagContext, null);
+ }
+
+ @Test
+ public void noopStatsRecorder_RecordWithCurrentContext_DisallowNullMeasureMap() {
+ thrown.expect(NullPointerException.class);
+ NoopStats.getNoopStatsRecorder().record(null);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/NoopViewManagerTest.java b/api/src/test/java/io/opencensus/stats/NoopViewManagerTest.java
new file mode 100644
index 00000000..01196e1d
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/NoopViewManagerTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import io.opencensus.common.Duration;
+import io.opencensus.common.Timestamp;
+import io.opencensus.stats.Aggregation.Sum;
+import io.opencensus.stats.Measure.MeasureDouble;
+import io.opencensus.stats.View.AggregationWindow.Cumulative;
+import io.opencensus.stats.View.AggregationWindow.Interval;
+import io.opencensus.stats.View.Name;
+import io.opencensus.stats.ViewData.AggregationWindowData.CumulativeData;
+import io.opencensus.stats.ViewData.AggregationWindowData.IntervalData;
+import io.opencensus.tags.TagKey.TagKeyString;
+import java.util.Arrays;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link NoopStats#newNoopViewManager}. */
+@RunWith(JUnit4.class)
+public final class NoopViewManagerTest {
+ private static final MeasureDouble MEASURE =
+ Measure.MeasureDouble.create("my measure", "description", "s");
+ private static final TagKeyString KEY = TagKeyString.create("KEY");
+ private static final Name VIEW_NAME = Name.create("my view");
+ private static final String VIEW_DESCRIPTION = "view description";
+ private static final Sum AGGREGATION = Sum.create();
+ private static final Cumulative CUMULATIVE = Cumulative.create();
+ private static final Duration TEN_SECONDS = Duration.create(10, 0);
+ private static final Interval INTERVAL = Interval.create(TEN_SECONDS);
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void noopViewManager_RegisterView_DisallowRegisteringDifferentViewWithSameName() {
+ final View view1 =
+ View.create(
+ VIEW_NAME, "description 1", MEASURE, AGGREGATION, Arrays.asList(KEY), CUMULATIVE);
+ final View view2 =
+ View.create(
+ VIEW_NAME, "description 2", MEASURE, AGGREGATION, Arrays.asList(KEY), CUMULATIVE);
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ viewManager.registerView(view1);
+
+ try {
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("A different view with the same name already exists.");
+ viewManager.registerView(view2);
+ } finally {
+ assertThat(viewManager.getView(VIEW_NAME).getView()).isEqualTo(view1);
+ }
+ }
+
+ @Test
+ public void noopViewManager_RegisterView_AllowRegisteringSameViewTwice() {
+ View view =
+ View.create(
+ VIEW_NAME, VIEW_DESCRIPTION, MEASURE, AGGREGATION, Arrays.asList(KEY), CUMULATIVE);
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ viewManager.registerView(view);
+ viewManager.registerView(view);
+ }
+
+ @Test
+ public void noopViewManager_RegisterView_DisallowNull() {
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ thrown.expect(NullPointerException.class);
+ viewManager.registerView(null);
+ }
+
+ @Test
+ public void noopViewManager_GetView_DisallowGettingNonExistentView() {
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("View is not registered.");
+ viewManager.getView(VIEW_NAME);
+ }
+
+ @Test
+ public void noopViewManager_GetView_Cumulative() {
+ View view =
+ View.create(
+ VIEW_NAME, VIEW_DESCRIPTION, MEASURE, AGGREGATION, Arrays.asList(KEY), CUMULATIVE);
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ viewManager.registerView(view);
+
+ ViewData viewData = viewManager.getView(VIEW_NAME);
+ assertThat(viewData.getView()).isEqualTo(view);
+ assertThat(viewData.getAggregationMap()).isEmpty();
+ assertThat(viewData.getWindowData())
+ .isEqualTo(CumulativeData.create(Timestamp.create(0, 0), Timestamp.create(0, 0)));
+ }
+
+ @Test
+ public void noopViewManager_GetView_Interval() {
+ View view =
+ View.create(
+ VIEW_NAME, VIEW_DESCRIPTION, MEASURE, AGGREGATION, Arrays.asList(KEY), INTERVAL);
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ viewManager.registerView(view);
+
+ ViewData viewData = viewManager.getView(VIEW_NAME);
+ assertThat(viewData.getView()).isEqualTo(view);
+ assertThat(viewData.getAggregationMap()).isEmpty();
+ assertThat(viewData.getWindowData()).isEqualTo(IntervalData.create(Timestamp.create(0, 0)));
+ }
+
+ @Test
+ public void noopViewManager_GetView_DisallowNull() {
+ ViewManager viewManager = NoopStats.newNoopViewManager();
+ thrown.expect(NullPointerException.class);
+ viewManager.getView(null);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/StatsRecorderTest.java b/api/src/test/java/io/opencensus/stats/StatsRecorderTest.java
new file mode 100644
index 00000000..793da8a0
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/StatsRecorderTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.verify;
+
+import io.grpc.Context;
+import io.opencensus.stats.Measure.MeasureDouble;
+import io.opencensus.tags.Tag;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagContext;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueString;
+import io.opencensus.tags.unsafe.ContextUtils;
+import java.util.Collections;
+import java.util.Iterator;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/** Tests for {@link StatsRecorder}. */
+@RunWith(JUnit4.class)
+public final class StatsRecorderTest {
+ private static final TagString TAG =
+ TagString.create(TagKeyString.create("key"), TagValueString.create("value"));
+ private static final MeasureDouble MEASURE =
+ Measure.MeasureDouble.create("my measure", "description", "bit/s");
+
+ private final TagContext tagContext =
+ new TagContext() {
+
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return Collections.<Tag>singleton(TAG).iterator();
+ }
+ };
+
+ @Mock private StatsRecorder statsRecorder;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void record_CurrentContextNotSet() {
+ MeasureMap measures = MeasureMap.builder().put(MEASURE, 1.0).build();
+ statsRecorder.record(measures);
+ verify(statsRecorder).record(same(ContextUtils.TAG_CONTEXT_KEY.get()), same(measures));
+ }
+
+ @Test
+ public void record_CurrentContextSet() {
+ Context orig = Context.current().withValue(ContextUtils.TAG_CONTEXT_KEY, tagContext).attach();
+ try {
+ MeasureMap measures = MeasureMap.builder().put(MEASURE, 2.0).build();
+ statsRecorder.record(measures);
+ verify(statsRecorder).record(same(tagContext), same(measures));
+ } finally {
+ Context.current().detach(orig);
+ }
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/StatsTest.java b/api/src/test/java/io/opencensus/stats/StatsTest.java
new file mode 100644
index 00000000..cb2f3a23
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/StatsTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2016-17, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link Stats}. */
+@RunWith(JUnit4.class)
+public final class StatsTest {
+ @Rule public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void loadStatsManager_UsesProvidedClassLoader() {
+ final RuntimeException toThrow = new RuntimeException("UseClassLoader");
+ thrown.expect(RuntimeException.class);
+ thrown.expectMessage("UseClassLoader");
+ Stats.loadStatsComponent(
+ new ClassLoader() {
+ @Override
+ public Class<?> loadClass(String name) {
+ throw toThrow;
+ }
+ });
+ }
+
+ @Test
+ public void loadStatsManager_IgnoresMissingClasses() {
+ assertThat(
+ Stats.loadStatsComponent(
+ new ClassLoader() {
+ @Override
+ public Class<?> loadClass(String name) throws ClassNotFoundException {
+ throw new ClassNotFoundException();
+ }
+ })
+ .getClass()
+ .getName())
+ .isEqualTo("io.opencensus.stats.NoopStats$NoopStatsComponent");
+ }
+
+ @Test
+ public void defaultValues() {
+ assertThat(Stats.getStatsRecorder()).isEqualTo(NoopStats.getNoopStatsRecorder());
+ assertThat(Stats.getViewManager()).isInstanceOf(NoopStats.newNoopViewManager().getClass());
+ }
+
+ @Test
+ public void getState() {
+ assertThat(Stats.getState()).isEqualTo(StatsCollectionState.DISABLED);
+ }
+
+ @Test
+ public void setState_IgnoresInput() {
+ Stats.setState(StatsCollectionState.ENABLED);
+ assertThat(Stats.getState()).isEqualTo(StatsCollectionState.DISABLED);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void setState_DisallowsNull() {
+ Stats.setState(null);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/stats/ViewDataTest.java b/api/src/test/java/io/opencensus/stats/ViewDataTest.java
new file mode 100644
index 00000000..43cc956a
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/ViewDataTest.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2016-17, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.fail;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Duration;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.common.Timestamp;
+import io.opencensus.stats.Aggregation.Distribution;
+import io.opencensus.stats.AggregationData.DistributionData;
+import io.opencensus.stats.View.AggregationWindow;
+import io.opencensus.stats.View.AggregationWindow.Cumulative;
+import io.opencensus.stats.View.AggregationWindow.Interval;
+import io.opencensus.stats.ViewData.AggregationWindowData;
+import io.opencensus.stats.ViewData.AggregationWindowData.CumulativeData;
+import io.opencensus.stats.ViewData.AggregationWindowData.IntervalData;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue;
+import io.opencensus.tags.TagValue.TagValueString;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for class {@link ViewData}. */
+@RunWith(JUnit4.class)
+public final class ViewDataTest {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testCumulativeViewData() {
+ View view = View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, CUMULATIVE);
+ Timestamp start = Timestamp.fromMillis(1000);
+ Timestamp end = Timestamp.fromMillis(2000);
+ AggregationWindowData windowData = CumulativeData.create(start, end);
+ ViewData viewData = ViewData.create(view, ENTRIES, windowData);
+ assertThat(viewData.getView()).isEqualTo(view);
+ assertThat(viewData.getAggregationMap()).isEqualTo(ENTRIES);
+ assertThat(viewData.getWindowData()).isEqualTo(windowData);
+ }
+
+ @Test
+ public void testIntervalViewData() {
+ View view = View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, INTERVAL_HOUR);
+ Timestamp end = Timestamp.fromMillis(2000);
+ AggregationWindowData windowData = IntervalData.create(end);
+ ViewData viewData = ViewData.create(view, ENTRIES, windowData);
+ assertThat(viewData.getView()).isEqualTo(view);
+ assertThat(viewData.getAggregationMap()).isEqualTo(ENTRIES);
+ assertThat(viewData.getWindowData()).isEqualTo(windowData);
+ }
+
+ @Test
+ public void testViewDataEquals() {
+ View cumulativeView =
+ View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, CUMULATIVE);
+ View intervalView =
+ View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, INTERVAL_HOUR);
+
+ new EqualsTester()
+ .addEqualityGroup(
+ ViewData.create(
+ cumulativeView,
+ ENTRIES,
+ CumulativeData.create(
+ Timestamp.fromMillis(1000), Timestamp.fromMillis(2000))),
+ ViewData.create(
+ cumulativeView,
+ ENTRIES,
+ CumulativeData.create(
+ Timestamp.fromMillis(1000), Timestamp.fromMillis(2000))))
+ .addEqualityGroup(
+ ViewData.create(
+ cumulativeView,
+ ENTRIES,
+ CumulativeData.create(
+ Timestamp.fromMillis(1000), Timestamp.fromMillis(3000))))
+ .addEqualityGroup(
+ ViewData.create(
+ intervalView,
+ ENTRIES,
+ IntervalData.create(Timestamp.fromMillis(2000))),
+ ViewData.create(
+ intervalView,
+ ENTRIES,
+ IntervalData.create(Timestamp.fromMillis(2000))))
+ .addEqualityGroup(
+ ViewData.create(
+ intervalView,
+ Collections.<List<TagValue>, AggregationData>emptyMap(),
+ IntervalData.create(Timestamp.fromMillis(2000))))
+ .testEquals();
+ }
+
+ @Test
+ public void testAggregationWindowDataMatch() {
+ final Timestamp start = Timestamp.fromMillis(1000);
+ final Timestamp end = Timestamp.fromMillis(2000);
+ final AggregationWindowData windowData1 = CumulativeData.create(start, end);
+ final AggregationWindowData windowData2 = IntervalData.create(end);
+ windowData1.match(
+ new Function<CumulativeData, Void>() {
+ @Override
+ public Void apply(CumulativeData windowData) {
+ assertThat(windowData.getStart()).isEqualTo(start);
+ assertThat(windowData.getEnd()).isEqualTo(end);
+ return null;
+ }
+ },
+ new Function<IntervalData, Void>() {
+ @Override
+ public Void apply(IntervalData windowData) {
+ fail("CumulativeData expected.");
+ return null;
+ }
+ },
+ Functions.<Void>throwIllegalArgumentException());
+ windowData2.match(
+ new Function<CumulativeData, Void>() {
+ @Override
+ public Void apply(CumulativeData windowData) {
+ fail("IntervalData expected.");
+ return null;
+ }
+ },
+ new Function<IntervalData, Void>() {
+ @Override
+ public Void apply(IntervalData windowData) {
+ assertThat(windowData.getEnd()).isEqualTo(end);
+ return null;
+ }
+ },
+ Functions.<Void>throwIllegalArgumentException());
+ }
+
+ @Test
+ public void preventWindowAndAggregationWindowDataMismatch() {
+ thrown.expect(IllegalArgumentException.class);
+ ViewData.create(
+ View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, INTERVAL_HOUR),
+ ENTRIES,
+ CumulativeData.create(
+ Timestamp.fromMillis(1000), Timestamp.fromMillis(2000)));
+ }
+
+ @Test
+ public void preventWindowAndAggregationWindowDataMismatch2() {
+ thrown.expect(IllegalArgumentException.class);
+ ViewData.create(
+ View.create(NAME, DESCRIPTION, MEASURE, DISTRIBUTION, tagKeys, CUMULATIVE),
+ ENTRIES,
+ IntervalData.create(Timestamp.fromMillis(1000)));
+ }
+
+ @Test
+ public void preventStartTimeLaterThanEndTime() {
+ thrown.expect(IllegalArgumentException.class);
+ CumulativeData.create(Timestamp.fromMillis(3000), Timestamp.fromMillis(2000));
+ }
+
+ // tag keys
+ private static final TagKeyString K1 = TagKeyString.create("k1");
+ private static final TagKeyString K2 = TagKeyString.create("k2");
+ private final List<TagKeyString> tagKeys = Arrays.asList(K1, K2);
+
+ // tag values
+ private static final TagValueString V1 = TagValueString.create("v1");
+ private static final TagValueString V2 = TagValueString.create("v2");
+ private static final TagValueString V10 = TagValueString.create("v10");
+ private static final TagValueString V20 = TagValueString.create("v20");
+
+ private static final AggregationWindow CUMULATIVE = Cumulative.create();
+ private static final AggregationWindow INTERVAL_HOUR = Interval.create(Duration.create(3600, 0));
+
+ private static final BucketBoundaries BUCKET_BOUNDARIES = BucketBoundaries.create(
+ Arrays.asList(10.0, 20.0, 30.0, 40.0));
+
+ private static final Aggregation DISTRIBUTION = Distribution.create(BUCKET_BOUNDARIES);
+
+ private static final ImmutableMap<List<TagValueString>, DistributionData> ENTRIES =
+ ImmutableMap.of(
+ Arrays.asList(V1, V2),
+ DistributionData.create(1, 1, 1, 1, 0, new long[]{0, 1, 0}),
+ Arrays.asList(V10, V20),
+ DistributionData.create(-5, 6, -20, 5, 100.1, new long[]{5, 0, 1}));
+
+ // name
+ private static final View.Name NAME = View.Name.create("test-view");
+ // description
+ private static final String DESCRIPTION = "test-view-descriptor description";
+ // measure
+ private static final Measure MEASURE = Measure.MeasureDouble.create(
+ "measure",
+ "measure description",
+ "1");
+}
diff --git a/api/src/test/java/io/opencensus/stats/ViewTest.java b/api/src/test/java/io/opencensus/stats/ViewTest.java
new file mode 100644
index 00000000..99215352
--- /dev/null
+++ b/api/src/test/java/io/opencensus/stats/ViewTest.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright 2016-17, OpenCensus Authors
+ *
+ * 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 io.opencensus.stats;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Duration;
+import io.opencensus.stats.Aggregation.Mean;
+import io.opencensus.stats.View.AggregationWindow.Cumulative;
+import io.opencensus.stats.View.AggregationWindow.Interval;
+import io.opencensus.tags.TagKey.TagKeyString;
+import java.util.Arrays;
+import java.util.List;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link View}. */
+@RunWith(JUnit4.class)
+public final class ViewTest {
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testConstants() {
+ assertThat(View.NAME_MAX_LENGTH).isEqualTo(256);
+ }
+
+ @Test
+ public void testDistributionView() {
+ final View view = View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Cumulative.create());
+ assertThat(view.getName()).isEqualTo(NAME);
+ assertThat(view.getDescription()).isEqualTo(DESCRIPTION);
+ assertThat(view.getMeasure().getName()).isEqualTo(MEASURE.getName());
+ assertThat(view.getAggregation()).isEqualTo(MEAN);
+ assertThat(view.getColumns()).hasSize(2);
+ assertThat(view.getColumns()).containsExactly(FOO, BAR).inOrder();
+ assertThat(view.getWindow()).isEqualTo(Cumulative.create());
+ }
+
+ @Test
+ public void testIntervalView() {
+ final View view = View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Interval.create(MINUTE));
+ assertThat(view.getName()).isEqualTo(NAME);
+ assertThat(view.getDescription()).isEqualTo(DESCRIPTION);
+ assertThat(view.getMeasure().getName())
+ .isEqualTo(MEASURE.getName());
+ assertThat(view.getAggregation()).isEqualTo(MEAN);
+ assertThat(view.getColumns()).hasSize(2);
+ assertThat(view.getColumns()).containsExactly(FOO, BAR).inOrder();
+ assertThat(view.getWindow()).isEqualTo(Interval.create(MINUTE));
+ }
+
+ @Test
+ public void testViewEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Cumulative.create()),
+ View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Cumulative.create()))
+ .addEqualityGroup(
+ View.create(
+ NAME, DESCRIPTION + 2, MEASURE, MEAN, keys, Cumulative.create()))
+ .addEqualityGroup(
+ View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Interval.create(MINUTE)),
+ View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Interval.create(MINUTE)))
+ .addEqualityGroup(
+ View.create(
+ NAME, DESCRIPTION, MEASURE, MEAN, keys, Interval.create(TWO_MINUTES)))
+ .testEquals();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void preventDuplicateColumns() {
+ View.create(
+ NAME,
+ DESCRIPTION,
+ MEASURE,
+ MEAN,
+ Arrays.asList(TagKeyString.create("duplicate"), TagKeyString.create("duplicate")),
+ Cumulative.create());
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void preventNullViewName() {
+ View.create(null, DESCRIPTION, MEASURE, MEAN, keys, Interval.create(MINUTE));
+ }
+
+ @Test
+ public void preventTooLongViewName() {
+ char[] chars = new char[View.NAME_MAX_LENGTH + 1];
+ Arrays.fill(chars, 'a');
+ String longName = String.valueOf(chars);
+ thrown.expect(IllegalArgumentException.class);
+ View.Name.create(longName);
+ }
+
+ @Test
+ public void preventNonPrintableViewName() {
+ thrown.expect(IllegalArgumentException.class);
+ View.Name.create("\2");
+ }
+
+ @Test
+ public void testViewName() {
+ assertThat(View.Name.create("my name").asString()).isEqualTo("my name");
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void preventNullNameString() {
+ View.Name.create(null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void preventNegativeIntervalDuration() {
+ Interval.create(NEG_TEN_SECONDS);
+ }
+
+ @Test
+ public void testViewNameEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ View.Name.create("view-1"), View.Name.create("view-1"))
+ .addEqualityGroup(View.Name.create("view-2"))
+ .testEquals();
+ }
+
+ private static final View.Name NAME = View.Name.create("test-view-name");
+ private static final String DESCRIPTION = "test-view-name description";
+ private static final Measure MEASURE = Measure.MeasureDouble.create(
+ "measure", "measure description", "1");
+ private static final TagKeyString FOO = TagKeyString.create("foo");
+ private static final TagKeyString BAR = TagKeyString.create("bar");
+ private static final List<TagKeyString> keys = ImmutableList.of(FOO, BAR);
+ private static final Mean MEAN = Mean.create();
+ private static final Duration MINUTE = Duration.create(60, 0);
+ private static final Duration TWO_MINUTES = Duration.create(120, 0);
+ private static final Duration NEG_TEN_SECONDS = Duration.create(-10, 0);
+}
diff --git a/api/src/test/java/io/opencensus/tags/InternalUtilsTest.java b/api/src/test/java/io/opencensus/tags/InternalUtilsTest.java
new file mode 100644
index 00000000..ba69ef88
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/InternalUtilsTest.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueString;
+import java.util.Iterator;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link InternalUtils}. */
+@RunWith(JUnit4.class)
+public final class InternalUtilsTest {
+
+ @Test
+ public void getTags() {
+ final Iterator<Tag> iterator =
+ Lists.<Tag>newArrayList(
+ TagString.create(TagKeyString.create("k"), TagValueString.create("v")))
+ .iterator();
+ TagContext ctx =
+ new TagContext() {
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return iterator;
+ }
+ };
+ assertThat(InternalUtils.getTags(ctx)).isSameAs(iterator);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/NoopTagsTest.java b/api/src/test/java/io/opencensus/tags/NoopTagsTest.java
new file mode 100644
index 00000000..2ee1c8cc
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/NoopTagsTest.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import io.opencensus.internal.NoopScope;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagKey.TagKeyBoolean;
+import io.opencensus.tags.TagKey.TagKeyLong;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueBoolean;
+import io.opencensus.tags.TagValue.TagValueLong;
+import io.opencensus.tags.TagValue.TagValueString;
+import io.opencensus.tags.propagation.TagContextBinarySerializer;
+import io.opencensus.tags.propagation.TagContextParseException;
+import java.util.Arrays;
+import java.util.Iterator;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link NoopTags}. */
+@RunWith(JUnit4.class)
+public final class NoopTagsTest {
+ private static final TagKeyString KEY_STRING = TagKeyString.create("key");
+ private static final TagValueString VALUE_STRING = TagValueString.create("value");
+ private static final TagKeyLong KEY_LONG = TagKeyLong.create("key");
+ private static final TagValueLong VALUE_LONG = TagValueLong.create(1L);
+ private static final TagKeyBoolean KEY_BOOLEAN = TagKeyBoolean.create("key");
+ private static final TagValueBoolean VALUE_BOOLEAN = TagValueBoolean.create(true);
+
+ private static final TagContext TAG_CONTEXT =
+ new TagContext() {
+
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return Arrays.<Tag>asList(TagString.create(KEY_STRING, VALUE_STRING)).iterator();
+ }
+ };
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void noopTagsComponent() {
+ assertThat(NoopTags.getNoopTagsComponent().getTagger()).isSameAs(NoopTags.getNoopTagger());
+ assertThat(NoopTags.getNoopTagsComponent().getTagPropagationComponent())
+ .isSameAs(NoopTags.getNoopTagPropagationComponent());
+ }
+
+ @Test
+ public void noopTagsComponent_SetState_DisallowsNull() {
+ TagsComponent noopTagsComponent = NoopTags.getNoopTagsComponent();
+ thrown.expect(NullPointerException.class);
+ noopTagsComponent.setState(null);
+ }
+
+ @Test
+ public void noopTagger() {
+ Tagger noopTagger = NoopTags.getNoopTagger();
+ assertThat(noopTagger.empty()).isSameAs(NoopTags.getNoopTagContext());
+ assertThat(noopTagger.getCurrentTagContext()).isSameAs(NoopTags.getNoopTagContext());
+ assertThat(noopTagger.emptyBuilder()).isSameAs(NoopTags.getNoopTagContextBuilder());
+ assertThat(noopTagger.toBuilder(TAG_CONTEXT)).isSameAs(NoopTags.getNoopTagContextBuilder());
+ assertThat(noopTagger.currentBuilder()).isSameAs(NoopTags.getNoopTagContextBuilder());
+ assertThat(noopTagger.withTagContext(TAG_CONTEXT)).isSameAs(NoopScope.getInstance());
+ }
+
+ @Test
+ public void noopTagger_ToBuilder_DisallowsNull() {
+ Tagger noopTagger = NoopTags.getNoopTagger();
+ thrown.expect(NullPointerException.class);
+ noopTagger.toBuilder(null);
+ }
+
+ @Test
+ public void noopTagger_WithTagContext_DisallowsNull() {
+ Tagger noopTagger = NoopTags.getNoopTagger();
+ thrown.expect(NullPointerException.class);
+ noopTagger.withTagContext(null);
+ }
+
+ @Test
+ public void noopTagContextBuilder() {
+ assertThat(NoopTags.getNoopTagContextBuilder().build()).isSameAs(NoopTags.getNoopTagContext());
+ assertThat(NoopTags.getNoopTagContextBuilder().put(KEY_STRING, VALUE_STRING).build())
+ .isSameAs(NoopTags.getNoopTagContext());
+ assertThat(NoopTags.getNoopTagContextBuilder().buildScoped()).isSameAs(NoopScope.getInstance());
+ assertThat(NoopTags.getNoopTagContextBuilder().put(KEY_STRING, VALUE_STRING).buildScoped())
+ .isSameAs(NoopScope.getInstance());
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutString_DisallowsNullKey() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(null, VALUE_STRING);
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutString_DisallowsNullValue() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(KEY_STRING, null);
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutLong_DisallowsNullKey() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(null, VALUE_LONG);
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutLong_DisallowsNullValue() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(KEY_LONG, null);
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutBoolean_DisallowsNullKey() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(null, VALUE_BOOLEAN);
+ }
+
+ @Test
+ public void noopTagContextBuilder_PutBoolean_DisallowsNullValue() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.put(KEY_BOOLEAN, null);
+ }
+
+ @Test
+ public void noopTagContextBuilder_Remove_DisallowsNullKey() {
+ TagContextBuilder noopBuilder = NoopTags.getNoopTagContextBuilder();
+ thrown.expect(NullPointerException.class);
+ noopBuilder.remove(null);
+ }
+
+ @Test
+ public void noopTagContext() {
+ assertThat(Lists.newArrayList(NoopTags.getNoopTagContext().getIterator())).isEmpty();
+ }
+
+ @Test
+ public void noopTagPropagationComponent() {
+ assertThat(NoopTags.getNoopTagPropagationComponent().getBinarySerializer())
+ .isSameAs(NoopTags.getNoopTagContextBinarySerializer());
+ }
+
+ @Test
+ public void noopTagContextBinarySerializer() throws TagContextParseException {
+ assertThat(NoopTags.getNoopTagContextBinarySerializer().toByteArray(TAG_CONTEXT))
+ .isEqualTo(new byte[0]);
+ assertThat(NoopTags.getNoopTagContextBinarySerializer().fromByteArray(new byte[5]))
+ .isEqualTo(NoopTags.getNoopTagContext());
+ }
+
+ @Test
+ public void noopTagContextBinarySerializer_ToByteArray_DisallowsNull() {
+ TagContextBinarySerializer noopSerializer = NoopTags.getNoopTagContextBinarySerializer();
+ thrown.expect(NullPointerException.class);
+ noopSerializer.toByteArray(null);
+ }
+
+ @Test
+ public void noopTagContextBinarySerializer_FromByteArray_DisallowsNull()
+ throws TagContextParseException {
+ TagContextBinarySerializer noopSerializer = NoopTags.getNoopTagContextBinarySerializer();
+ thrown.expect(NullPointerException.class);
+ noopSerializer.fromByteArray(null);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/TagContextTest.java b/api/src/test/java/io/opencensus/tags/TagContextTest.java
new file mode 100644
index 00000000..d6adfe12
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/TagContextTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import com.google.common.testing.EqualsTester;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueString;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link TagContext}. */
+@RunWith(JUnit4.class)
+public final class TagContextTest {
+ private static final Tag TAG1 =
+ TagString.create(TagKeyString.create("key"), TagValueString.create("val"));
+ private static final Tag TAG2 =
+ TagString.create(TagKeyString.create("key2"), TagValueString.create("val"));
+
+ @Test
+ public void equals_IgnoresTagOrderAndTagContextClass() {
+ new EqualsTester()
+ .addEqualityGroup(
+ new SimpleTagContext(TAG1, TAG2),
+ new SimpleTagContext(TAG1, TAG2),
+ new SimpleTagContext(TAG2, TAG1),
+ new TagContext() {
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return Lists.newArrayList(TAG1, TAG2).iterator();
+ }
+ })
+ .testEquals();
+ }
+
+ @Test
+ public void equals_HandlesNullIterator() {
+ new EqualsTester()
+ .addEqualityGroup(
+ new SimpleTagContext((List<Tag>) null),
+ new SimpleTagContext((List<Tag>) null),
+ new SimpleTagContext())
+ .testEquals();
+ }
+
+ @Test
+ public void equals_DoesNotIgnoreNullTags() {
+ new EqualsTester()
+ .addEqualityGroup(new SimpleTagContext(TAG1))
+ .addEqualityGroup(new SimpleTagContext(TAG1, null), new SimpleTagContext(null, TAG1))
+ .addEqualityGroup(new SimpleTagContext(TAG1, null, null))
+ .testEquals();
+ }
+
+ @Test
+ public void equals_DoesNotIgnoreDuplicateTags() {
+ new EqualsTester()
+ .addEqualityGroup(new SimpleTagContext(TAG1))
+ .addEqualityGroup(new SimpleTagContext(TAG1, TAG1))
+ .testEquals();
+ }
+
+ @Test
+ public void testToString() {
+ assertThat(new SimpleTagContext().toString()).isEqualTo("TagContext");
+ assertThat(new SimpleTagContext(TAG1, TAG2).toString()).isEqualTo("TagContext");
+ }
+
+ private static final class SimpleTagContext extends TagContext {
+ private final List<Tag> tags;
+
+ SimpleTagContext(Tag... tags) {
+ this(Lists.newArrayList(tags));
+ }
+
+ SimpleTagContext(List<Tag> tags) {
+ this.tags = tags == null ? null : Collections.unmodifiableList(Lists.newArrayList(tags));
+ }
+
+ @Override
+ protected Iterator<Tag> getIterator() {
+ return tags == null ? null : tags.iterator();
+ }
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/TagKeyTest.java b/api/src/test/java/io/opencensus/tags/TagKeyTest.java
new file mode 100644
index 00000000..5b70ba7a
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/TagKeyTest.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.tags.TagKey.TagKeyBoolean;
+import io.opencensus.tags.TagKey.TagKeyLong;
+import io.opencensus.tags.TagKey.TagKeyString;
+import java.util.Arrays;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link TagKey}. */
+@RunWith(JUnit4.class)
+public final class TagKeyTest {
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testGetName() {
+ assertThat(TagKeyString.create("foo").getName()).isEqualTo("foo");
+ }
+
+ @Test
+ public void createString_AllowTagKeyNameWithMaxLength() {
+ char[] key = new char[TagKey.MAX_LENGTH];
+ Arrays.fill(key, 'k');
+ TagKeyString.create(new String(key));
+ }
+
+ @Test
+ public void createString_DisallowTagKeyNameOverMaxLength() {
+ char[] key = new char[TagKey.MAX_LENGTH + 1];
+ Arrays.fill(key, 'k');
+ thrown.expect(IllegalArgumentException.class);
+ TagKeyString.create(new String(key));
+ }
+
+ @Test
+ public void createString_DisallowUnprintableChars() {
+ thrown.expect(IllegalArgumentException.class);
+ TagKeyString.create("\2ab\3cd");
+ }
+
+ @Test
+ public void testMatchStringKey() {
+ assertThat(
+ TagKeyString.create("key")
+ .match(
+ new Function<TagKeyString, String>() {
+ @Override
+ public String apply(TagKeyString tag) {
+ return tag.getName();
+ }
+ },
+ new Function<TagKeyLong, String>() {
+ @Override
+ public String apply(TagKeyLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagKeyBoolean, String>() {
+ @Override
+ public String apply(TagKeyBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()))
+ .isEqualTo("key");
+ }
+
+ @Test
+ public void testMatchLongKey() {
+ assertThat(
+ TagKeyLong.create("key")
+ .match(
+ new Function<TagKeyString, String>() {
+ @Override
+ public String apply(TagKeyString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagKeyLong, String>() {
+ @Override
+ public String apply(TagKeyLong tag) {
+ return tag.getName();
+ }
+ },
+ new Function<TagKeyBoolean, String>() {
+ @Override
+ public String apply(TagKeyBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()))
+ .isEqualTo("key");
+ }
+
+ @Test
+ public void testMatchBooleanKey() {
+ assertThat(
+ TagKeyBoolean.create("key")
+ .match(
+ new Function<TagKeyString, String>() {
+ @Override
+ public String apply(TagKeyString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagKeyLong, String>() {
+ @Override
+ public String apply(TagKeyLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagKeyBoolean, String>() {
+ @Override
+ public String apply(TagKeyBoolean tag) {
+ return tag.getName();
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()))
+ .isEqualTo("key");
+ }
+
+ @Test
+ public void testTagKeyEquals() {
+ new EqualsTester()
+ .addEqualityGroup(TagKeyString.create("foo"), TagKeyString.create("foo"))
+ .addEqualityGroup(TagKeyLong.create("foo"))
+ .addEqualityGroup(TagKeyBoolean.create("foo"))
+ .addEqualityGroup(TagKeyString.create("bar"))
+ .testEquals();
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/TagTest.java b/api/src/test/java/io/opencensus/tags/TagTest.java
new file mode 100644
index 00000000..79b2eb4d
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/TagTest.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.tags.Tag.TagBoolean;
+import io.opencensus.tags.Tag.TagLong;
+import io.opencensus.tags.Tag.TagString;
+import io.opencensus.tags.TagKey.TagKeyBoolean;
+import io.opencensus.tags.TagKey.TagKeyLong;
+import io.opencensus.tags.TagKey.TagKeyString;
+import io.opencensus.tags.TagValue.TagValueBoolean;
+import io.opencensus.tags.TagValue.TagValueLong;
+import io.opencensus.tags.TagValue.TagValueString;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link Tag}. */
+@RunWith(JUnit4.class)
+public final class TagTest {
+
+ @Test
+ public void testGetStringKey() {
+ assertThat(TagString.create(TagKeyString.create("k"), TagValueString.create("v")).getKey())
+ .isEqualTo(TagKeyString.create("k"));
+ }
+
+ @Test
+ public void testGetLongKey() {
+ assertThat(TagLong.create(TagKeyLong.create("k"), TagValueLong.create(2L)).getKey())
+ .isEqualTo(TagKeyLong.create("k"));
+ }
+
+ @Test
+ public void testGetBooleanKey() {
+ assertThat(TagBoolean.create(TagKeyBoolean.create("k"), TagValueBoolean.create(false)).getKey())
+ .isEqualTo(TagKeyBoolean.create("k"));
+ }
+
+ @Test
+ public void testMatchStringTag() {
+ assertThat(
+ TagString.create(TagKeyString.create("k1"), TagValueString.create("value"))
+ .match(
+ new Function<TagString, String>() {
+ @Override
+ public String apply(TagString tag) {
+ return tag.getValue().asString();
+ }
+ },
+ new Function<TagLong, String>() {
+ @Override
+ public String apply(TagLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagBoolean, String>() {
+ @Override
+ public String apply(TagBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()))
+ .isEqualTo("value");
+ }
+
+ @Test
+ public void testMatchLong() {
+ assertThat(
+ TagLong.create(TagKeyLong.create("k2"), TagValueLong.create(3L))
+ .match(
+ new Function<TagString, Long>() {
+ @Override
+ public Long apply(TagString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagLong, Long>() {
+ @Override
+ public Long apply(TagLong tag) {
+ return tag.getValue().asLong();
+ }
+ },
+ new Function<TagBoolean, Long>() {
+ @Override
+ public Long apply(TagBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<Long>throwIllegalArgumentException()))
+ .isEqualTo(3L);
+ }
+
+ @Test
+ public void testMatchBoolean() {
+ assertThat(
+ TagBoolean.create(TagKeyBoolean.create("k3"), TagValueBoolean.create(false))
+ .match(
+ new Function<TagString, Boolean>() {
+ @Override
+ public Boolean apply(TagString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagLong, Boolean>() {
+ @Override
+ public Boolean apply(TagLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagBoolean, Boolean>() {
+ @Override
+ public Boolean apply(TagBoolean tag) {
+ return tag.getValue().asBoolean();
+ }
+ },
+ Functions.<Boolean>throwIllegalArgumentException()))
+ .isEqualTo(false);
+ }
+
+ @Test
+ public void testTagEquals() {
+ new EqualsTester()
+ .addEqualityGroup(
+ TagString.create(TagKeyString.create("Key1"), TagValueString.create("foo")),
+ TagString.create(TagKeyString.create("Key1"), TagValueString.create("foo")))
+ .addEqualityGroup(
+ TagLong.create(TagKeyLong.create("Key1"), TagValueLong.create(100L)),
+ TagLong.create(TagKeyLong.create("Key1"), TagValueLong.create(100L)))
+ .addEqualityGroup(
+ TagBoolean.create(TagKeyBoolean.create("Key1"), TagValueBoolean.create(true)),
+ TagBoolean.create(TagKeyBoolean.create("Key1"), TagValueBoolean.create(true)))
+ .addEqualityGroup(
+ TagBoolean.create(TagKeyBoolean.create("Key2"), TagValueBoolean.create(true)))
+ .addEqualityGroup(
+ TagBoolean.create(TagKeyBoolean.create("Key1"), TagValueBoolean.create(false)))
+ .testEquals();
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/TagValueTest.java b/api/src/test/java/io/opencensus/tags/TagValueTest.java
new file mode 100644
index 00000000..b1382312
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/TagValueTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.testing.EqualsTester;
+import io.opencensus.common.Function;
+import io.opencensus.common.Functions;
+import io.opencensus.tags.TagValue.TagValueBoolean;
+import io.opencensus.tags.TagValue.TagValueLong;
+import io.opencensus.tags.TagValue.TagValueString;
+import java.util.Arrays;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Tests for {@link TagValue}. */
+@RunWith(JUnit4.class)
+public final class TagValueTest {
+
+ @Rule public final ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void testMatchStringValue() {
+ assertThat(
+ TagValueString.create("value")
+ .match(
+ new Function<TagValueString, String>() {
+ @Override
+ public String apply(TagValueString tag) {
+ return tag.asString();
+ }
+ },
+ new Function<TagValueLong, String>() {
+ @Override
+ public String apply(TagValueLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagValueBoolean, String>() {
+ @Override
+ public String apply(TagValueBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<String>throwIllegalArgumentException()))
+ .isEqualTo("value");
+ }
+
+ @Test
+ public void testMatchLongValue() {
+ assertThat(
+ TagValueLong.create(1234)
+ .match(
+ new Function<TagValueString, Long>() {
+ @Override
+ public Long apply(TagValueString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagValueLong, Long>() {
+ @Override
+ public Long apply(TagValueLong tag) {
+ return tag.asLong();
+ }
+ },
+ new Function<TagValueBoolean, Long>() {
+ @Override
+ public Long apply(TagValueBoolean tag) {
+ throw new AssertionError();
+ }
+ },
+ Functions.<Long>throwIllegalArgumentException()))
+ .isEqualTo(1234);
+ }
+
+ @Test
+ public void testMatchBooleanValue() {
+ assertThat(
+ TagValueBoolean.create(false)
+ .match(
+ new Function<TagValueString, Boolean>() {
+ @Override
+ public Boolean apply(TagValueString tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagValueLong, Boolean>() {
+ @Override
+ public Boolean apply(TagValueLong tag) {
+ throw new AssertionError();
+ }
+ },
+ new Function<TagValueBoolean, Boolean>() {
+ @Override
+ public Boolean apply(TagValueBoolean tag) {
+ return tag.asBoolean();
+ }
+ },
+ Functions.<Boolean>throwIllegalArgumentException()))
+ .isEqualTo(false);
+ }
+
+ @Test
+ public void allowStringTagValueWithMaxLength() {
+ char[] chars = new char[TagValueString.MAX_LENGTH];
+ Arrays.fill(chars, 'v');
+ String value = new String(chars);
+ assertThat(TagValueString.create(value).asString()).isEqualTo(value);
+ }
+
+ @Test
+ public void disallowStringTagValueOverMaxLength() {
+ char[] chars = new char[TagValueString.MAX_LENGTH + 1];
+ Arrays.fill(chars, 'v');
+ String value = new String(chars);
+ thrown.expect(IllegalArgumentException.class);
+ TagValueString.create(value);
+ }
+
+ @Test
+ public void disallowStringTagValueWithUnprintableChars() {
+ String value = "\2ab\3cd";
+ thrown.expect(IllegalArgumentException.class);
+ TagValueString.create(value);
+ }
+
+ @Test
+ public void testTagValueEquals() {
+ new EqualsTester()
+ .addEqualityGroup(TagValueString.create("foo"), TagValueString.create("foo"))
+ .addEqualityGroup(TagValueLong.create(2))
+ .addEqualityGroup(TagValueBoolean.create(true))
+ .addEqualityGroup(TagValueString.create("bar"))
+ .testEquals();
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/TagsTest.java b/api/src/test/java/io/opencensus/tags/TagsTest.java
new file mode 100644
index 00000000..e87407db
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/TagsTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link Tags}. */
+@RunWith(JUnit4.class)
+public class TagsTest {
+ @Rule public ExpectedException thrown = ExpectedException.none();
+
+ @Test
+ public void loadTagsComponent_UsesProvidedClassLoader() {
+ final RuntimeException toThrow = new RuntimeException("UseClassLoader");
+ thrown.expect(RuntimeException.class);
+ thrown.expectMessage("UseClassLoader");
+ Tags.loadTagsComponent(
+ new ClassLoader() {
+ @Override
+ public Class<?> loadClass(String name) {
+ throw toThrow;
+ }
+ });
+ }
+
+ @Test
+ public void loadTagsComponent_IgnoresMissingClasses() {
+ ClassLoader classLoader =
+ new ClassLoader() {
+ @Override
+ public Class<?> loadClass(String name) throws ClassNotFoundException {
+ throw new ClassNotFoundException();
+ }
+ };
+ assertThat(Tags.loadTagsComponent(classLoader).getClass().getName())
+ .isEqualTo("io.opencensus.tags.NoopTags$NoopTagsComponent");
+ }
+
+ @Test
+ public void getState() {
+ assertThat(Tags.getState()).isEqualTo(TaggingState.DISABLED);
+ }
+
+ @Test
+ public void setState_IgnoresInput() {
+ Tags.setState(TaggingState.ENABLED);
+ assertThat(Tags.getState()).isEqualTo(TaggingState.DISABLED);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void setState_DisallowsNull() {
+ Tags.setState(null);
+ }
+
+ @Test
+ public void defaultTagger() {
+ assertThat(Tags.getTagger()).isEqualTo(NoopTags.getNoopTagger());
+ }
+
+ @Test
+ public void defaultTagContextSerializer() {
+ assertThat(Tags.getTagPropagationComponent())
+ .isEqualTo(NoopTags.getNoopTagPropagationComponent());
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/propagation/TagContextParseExceptionTest.java b/api/src/test/java/io/opencensus/tags/propagation/TagContextParseExceptionTest.java
new file mode 100644
index 00000000..0c2afadc
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/propagation/TagContextParseExceptionTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags.propagation;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import java.io.IOException;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link TagContextParseException}. */
+@RunWith(JUnit4.class)
+public final class TagContextParseExceptionTest {
+
+ @Test
+ public void createWithMessage() {
+ assertThat(new TagContextParseException("my message").getMessage()).isEqualTo("my message");
+ }
+
+ @Test
+ public void createWithMessageAndCause() {
+ IOException cause = new IOException();
+ TagContextParseException parseException = new TagContextParseException("my message", cause);
+ assertThat(parseException.getMessage()).isEqualTo("my message");
+ assertThat(parseException.getCause()).isEqualTo(cause);
+ }
+}
diff --git a/api/src/test/java/io/opencensus/tags/unsafe/ContextUtilsTest.java b/api/src/test/java/io/opencensus/tags/unsafe/ContextUtilsTest.java
new file mode 100644
index 00000000..c35c5dc4
--- /dev/null
+++ b/api/src/test/java/io/opencensus/tags/unsafe/ContextUtilsTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2017, OpenCensus Authors
+ *
+ * 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 io.opencensus.tags.unsafe;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.Lists;
+import io.grpc.Context;
+import io.opencensus.tags.InternalUtils;
+import io.opencensus.tags.Tag;
+import io.opencensus.tags.TagContext;
+import java.util.List;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Unit tests for {@link ContextUtils}. */
+@RunWith(JUnit4.class)
+public final class ContextUtilsTest {
+ @Test
+ public void testContextKeyName() {
+ // Context.Key.toString() returns the name.
+ assertThat(ContextUtils.TAG_CONTEXT_KEY.toString()).isEqualTo("opencensus-tag-context-key");
+ }
+
+ @Test
+ public void testGetCurrentTagContext_DefaultContext() {
+ TagContext tags = ContextUtils.TAG_CONTEXT_KEY.get();
+ assertThat(tags).isNotNull();
+ assertThat(asList(tags)).isEmpty();
+ }
+
+ @Test
+ public void testGetCurrentTagContext_ContextSetToNull() {
+ Context orig = Context.current().withValue(ContextUtils.TAG_CONTEXT_KEY, null).attach();
+ try {
+ TagContext tags = ContextUtils.TAG_CONTEXT_KEY.get();
+ assertThat(tags).isNotNull();
+ assertThat(asList(tags)).isEmpty();
+ } finally {
+ Context.current().detach(orig);
+ }
+ }
+
+ private static List<Tag> asList(TagContext tags) {
+ return Lists.newArrayList(InternalUtils.getTags(tags));
+ }
+}