Repository: incubator-htrace Updated Branches: refs/heads/master afa0b71a4 -> fd889b659
http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestCountSampler.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestCountSampler.java b/htrace-core/src/test/java/org/apache/htrace/core/TestCountSampler.java new file mode 100644 index 0000000..e26115d --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestCountSampler.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import org.junit.Assert; +import org.junit.Test; + +public class TestCountSampler { + + @Test + public void testNext() { + CountSampler half = new CountSampler(HTraceConfiguration. + fromKeyValuePairs("sampler.frequency", "2")); + CountSampler hundred = new CountSampler(HTraceConfiguration. + fromKeyValuePairs("sampler.frequency", "100")); + int halfCount = 0; + int hundredCount = 0; + for (int i = 0; i < 200; i++) { + if (half.next()) + halfCount++; + if (hundred.next()) + hundredCount++; + } + Assert.assertEquals(2, hundredCount); + Assert.assertEquals(100, halfCount); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestHTrace.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestHTrace.java b/htrace-core/src/test/java/org/apache/htrace/core/TestHTrace.java new file mode 100644 index 0000000..f1839cb --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestHTrace.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import java.io.File; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.apache.htrace.core.TraceGraph.SpansByParent; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; + +public class TestHTrace { + + @Rule + public TraceCreator traceCreator = new TraceCreator(); + + public static final String SPAN_FILE_FLAG = "spanFile"; + + /** + * Basic system test of HTrace. + * + * @throws Exception + */ + @Test + public void testHtrace() throws Exception { + final int numTraces = 3; + String fileName = System.getProperty(SPAN_FILE_FLAG); + + // writes spans to a file if one is provided to maven with + // -DspanFile="FILENAME", otherwise writes to standard out. + if (fileName != null) { + File f = new File(fileName); + File parent = f.getParentFile(); + if (parent != null && !parent.exists() && !parent.mkdirs()) { + throw new IllegalArgumentException("Couldn't create file: " + + fileName); + } + HashMap<String, String> conf = new HashMap<String, String>(); + conf.put("local-file-span-receiver.path", fileName); + LocalFileSpanReceiver receiver = + new LocalFileSpanReceiver(HTraceConfiguration.fromMap(conf)); + traceCreator.addReceiver(receiver); + } else { + traceCreator.addReceiver(new StandardOutSpanReceiver(HTraceConfiguration.EMPTY)); + } + + traceCreator.addReceiver(new POJOSpanReceiver(HTraceConfiguration.EMPTY){ + @Override + public void close() { + TraceGraph traceGraph = new TraceGraph(getSpans()); + Collection<Span> roots = traceGraph.getSpansByParent().find(SpanId.INVALID); + Assert.assertTrue("Trace tree must have roots", !roots.isEmpty()); + Assert.assertEquals(numTraces, roots.size()); + + Map<String, Span> descriptionToRootSpan = new HashMap<String, Span>(); + for (Span root : roots) { + descriptionToRootSpan.put(root.getDescription(), root); + } + + Assert.assertTrue(descriptionToRootSpan.keySet().contains( + TraceCreator.RPC_TRACE_ROOT)); + Assert.assertTrue(descriptionToRootSpan.keySet().contains( + TraceCreator.SIMPLE_TRACE_ROOT)); + Assert.assertTrue(descriptionToRootSpan.keySet().contains( + TraceCreator.THREADED_TRACE_ROOT)); + + SpansByParent spansByParentId = traceGraph.getSpansByParent(); + Span rpcTraceRoot = descriptionToRootSpan.get(TraceCreator.RPC_TRACE_ROOT); + Assert.assertEquals(1, spansByParentId.find(rpcTraceRoot.getSpanId()).size()); + + Span rpcTraceChild1 = spansByParentId.find(rpcTraceRoot.getSpanId()) + .iterator().next(); + Assert.assertEquals(1, spansByParentId.find(rpcTraceChild1.getSpanId()).size()); + + Span rpcTraceChild2 = spansByParentId.find(rpcTraceChild1.getSpanId()) + .iterator().next(); + Assert.assertEquals(1, spansByParentId.find(rpcTraceChild2.getSpanId()).size()); + + Span rpcTraceChild3 = spansByParentId.find(rpcTraceChild2.getSpanId()) + .iterator().next(); + Assert.assertEquals(0, spansByParentId.find(rpcTraceChild3.getSpanId()).size()); + } + }); + + traceCreator.createThreadedTrace(); + traceCreator.createSimpleTrace(); + traceCreator.createSampleRpcTrace(); + } + + @Test(timeout=60000) + public void testRootSpansHaveNonZeroSpanId() throws Exception { + TraceScope scope = Trace.startSpan("myRootSpan", new SpanId(100L, 200L)); + Assert.assertNotNull(scope); + Assert.assertEquals("myRootSpan", scope.getSpan().getDescription()); + Assert.assertEquals(100L, scope.getSpan().getSpanId().getHigh()); + Assert.assertTrue(scope.getSpan().getSpanId().isValid()); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestHTraceConfiguration.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestHTraceConfiguration.java b/htrace-core/src/test/java/org/apache/htrace/core/TestHTraceConfiguration.java new file mode 100644 index 0000000..7ca897f --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestHTraceConfiguration.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class TestHTraceConfiguration { + @Test + public void testGetBoolean() throws Exception { + + Map<String, String> m = new HashMap<String, String>(); + m.put("testTrue", " True"); + m.put("testFalse", "falsE "); + HTraceConfiguration configuration = HTraceConfiguration.fromMap(m); + + // Tests for value being there + assertTrue(configuration.getBoolean("testTrue", false)); + assertFalse(configuration.getBoolean("testFalse", true)); + + // Test for absent + assertTrue(configuration.getBoolean("absent", true)); + assertFalse(configuration.getBoolean("absent", false)); + } + + @Test + public void testGetInt() throws Exception { + Map<String, String> m = new HashMap<String, String>(); + m.put("a", "100"); + m.put("b", "0"); + m.put("c", "-100"); + m.put("d", "5"); + + HTraceConfiguration configuration = HTraceConfiguration.fromMap(m); + assertEquals(100, configuration.getInt("a", -999)); + assertEquals(0, configuration.getInt("b", -999)); + assertEquals(-100, configuration.getInt("c", -999)); + assertEquals(5, configuration.getInt("d", -999)); + assertEquals(-999, configuration.getInt("absent", -999)); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestLocalFileSpanReceiver.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestLocalFileSpanReceiver.java b/htrace-core/src/test/java/org/apache/htrace/core/TestLocalFileSpanReceiver.java new file mode 100644 index 0000000..90a009a --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestLocalFileSpanReceiver.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Ignore; +import org.junit.Test; + +public class TestLocalFileSpanReceiver { + @Test + public void testUniqueLocalTraceFileName() { + String filename1 = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); + System.out.println("##### :" + filename1); + String filename2 = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); + System.out.println("##### :" + filename2); + boolean eq = filename1.equals(filename2); + if (System.getProperty("os.name").startsWith("Linux")) { + // ${java.io.tmpdir}/[pid] + assertTrue(eq); + } else { + // ${java.io.tmpdir}/[random UUID] + assertFalse(eq); + } + } + + @Test + public void testWriteToLocalFile() throws IOException { + String traceFileName = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); + HashMap<String, String> confMap = new HashMap<String, String>(); + confMap.put(LocalFileSpanReceiver.PATH_KEY, traceFileName); + confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, + LocalFileSpanReceiver.class.getName()); + confMap.put(TracerId.TRACER_ID_KEY, "testTrid"); + SpanReceiver rcvr = + new SpanReceiverBuilder(HTraceConfiguration.fromMap(confMap)) + .logErrors(false).build(); + Trace.addReceiver(rcvr); + TraceScope ts = Trace.startSpan("testWriteToLocalFile", Sampler.ALWAYS); + ts.close(); + Trace.removeReceiver(rcvr); + rcvr.close(); + + ObjectMapper mapper = new ObjectMapper(); + MilliSpan span = mapper.readValue(new File(traceFileName), MilliSpan.class); + assertEquals("testWriteToLocalFile", span.getDescription()); + assertEquals("testTrid", span.getTracerId()); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestMilliSpan.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestMilliSpan.java b/htrace-core/src/test/java/org/apache/htrace/core/TestMilliSpan.java new file mode 100644 index 0000000..7ce1fdb --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestMilliSpan.java @@ -0,0 +1,145 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +public class TestMilliSpan { + private void compareSpans(Span expected, Span got) throws Exception { + assertEquals(expected.getStartTimeMillis(), got.getStartTimeMillis()); + assertEquals(expected.getStopTimeMillis(), got.getStopTimeMillis()); + assertEquals(expected.getDescription(), got.getDescription()); + assertEquals(expected.getSpanId(), got.getSpanId()); + assertEquals(expected.getTracerId(), got.getTracerId()); + assertTrue(Arrays.equals(expected.getParents(), got.getParents())); + Map<String, String> expectedT = expected.getKVAnnotations(); + Map<String, String> gotT = got.getKVAnnotations(); + if (expectedT == null) { + assertEquals(null, gotT); + } else { + assertEquals(expectedT.size(), gotT.size()); + for (String key : expectedT.keySet()) { + assertEquals(expectedT.get(key), gotT.get(key)); + } + } + List<TimelineAnnotation> expectedTimeline = + expected.getTimelineAnnotations(); + List<TimelineAnnotation> gotTimeline = + got.getTimelineAnnotations(); + if (expectedTimeline == null) { + assertEquals(null, gotTimeline); + } else { + assertEquals(expectedTimeline.size(), gotTimeline.size()); + Iterator<TimelineAnnotation> iter = gotTimeline.iterator(); + for (TimelineAnnotation expectedAnn : expectedTimeline) { + TimelineAnnotation gotAnn = iter.next(); + assertEquals(expectedAnn.getMessage(), gotAnn.getMessage()); + assertEquals(expectedAnn.getTime(), gotAnn.getTime()); + } + } + } + + @Test + public void testJsonSerialization() throws Exception { + MilliSpan span = new MilliSpan.Builder(). + description("foospan"). + begin(123L). + end(456L). + parents(new SpanId[] { new SpanId(7L, 7L) }). + tracerId("b2404.halxg.com:8080"). + spanId(new SpanId(7L, 8L)). + build(); + String json = span.toJson(); + MilliSpan dspan = MilliSpan.fromJson(json); + compareSpans(span, dspan); + } + + @Test + public void testJsonSerializationWithNegativeLongValue() throws Exception { + MilliSpan span = new MilliSpan.Builder(). + description("foospan"). + begin(-1L). + end(-1L). + parents(new SpanId[] { new SpanId(-1L, -1L) }). + tracerId("b2404.halxg.com:8080"). + spanId(new SpanId(-1L, -2L)). + build(); + String json = span.toJson(); + MilliSpan dspan = MilliSpan.fromJson(json); + compareSpans(span, dspan); + } + + @Test + public void testJsonSerializationWithRandomLongValue() throws Exception { + SpanId parentId = SpanId.fromRandom(); + MilliSpan span = new MilliSpan.Builder(). + description("foospan"). + begin(ThreadLocalRandom.current().nextLong()). + end(ThreadLocalRandom.current().nextLong()). + parents(new SpanId[] { parentId }). + tracerId("b2404.halxg.com:8080"). + spanId(parentId.newChildId()). + build(); + String json = span.toJson(); + MilliSpan dspan = MilliSpan.fromJson(json); + compareSpans(span, dspan); + } + + @Test + public void testJsonSerializationWithOptionalFields() throws Exception { + MilliSpan.Builder builder = new MilliSpan.Builder(). + description("foospan"). + begin(300). + end(400). + parents(new SpanId[] { }). + tracerId("b2408.halxg.com:8080"). + spanId(new SpanId(111111111L, 111111111L)); + Map<String, String> traceInfo = new HashMap<String, String>(); + traceInfo.put("abc", "123"); + traceInfo.put("def", "456"); + builder.traceInfo(traceInfo); + List<TimelineAnnotation> timeline = new LinkedList<TimelineAnnotation>(); + timeline.add(new TimelineAnnotation(310L, "something happened")); + timeline.add(new TimelineAnnotation(380L, "something else happened")); + timeline.add(new TimelineAnnotation(390L, "more things")); + builder.timeline(timeline); + MilliSpan span = builder.build(); + String json = span.toJson(); + MilliSpan dspan = MilliSpan.fromJson(json); + compareSpans(span, dspan); + } + + @Test + public void testJsonSerializationWithFieldsNotSet() throws Exception { + MilliSpan span = new MilliSpan.Builder().build(); + String json = span.toJson(); + MilliSpan dspan = MilliSpan.fromJson(json); + compareSpans(span, dspan); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestNullScope.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestNullScope.java b/htrace-core/src/test/java/org/apache/htrace/core/TestNullScope.java new file mode 100644 index 0000000..3fa9210 --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestNullScope.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import org.junit.Assert; +import org.junit.Test; + +public class TestNullScope { + @Test + public void testNullScope() { + Assert.assertTrue(!Trace.isTracing()); + TraceScope tc = Trace.startSpan("NullScopeSingleton"); + Assert.assertTrue(tc == NullScope.INSTANCE); + tc.detach(); + tc.detach(); // should not fail even if called multiple times. + Assert.assertFalse(tc.isDetached()); + tc.close(); + tc.close(); // should not fail even if called multiple times. + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestSampler.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestSampler.java b/htrace-core/src/test/java/org/apache/htrace/core/TestSampler.java new file mode 100644 index 0000000..e11799b --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestSampler.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +public class TestSampler { + @Test + public void testSamplerBuilder() { + Sampler alwaysSampler = new SamplerBuilder( + HTraceConfiguration.fromKeyValuePairs("sampler", "AlwaysSampler")). + build(); + Assert.assertEquals(AlwaysSampler.class, alwaysSampler.getClass()); + + Sampler neverSampler = new SamplerBuilder( + HTraceConfiguration.fromKeyValuePairs("sampler", "NeverSampler")). + build(); + Assert.assertEquals(NeverSampler.class, neverSampler.getClass()); + + Sampler neverSampler2 = new SamplerBuilder(HTraceConfiguration. + fromKeyValuePairs("sampler", "NonExistentSampler")). + build(); + Assert.assertEquals(NeverSampler.class, neverSampler2.getClass()); + + Sampler neverSampler3 = new SamplerBuilder(HTraceConfiguration. + fromKeyValuePairs("sampler.is.not.defined", "NonExistentSampler")). + build(); + Assert.assertEquals(NeverSampler.class, neverSampler3.getClass()); + } + + @Test + public void testAlwaysSampler() { + TraceScope cur = Trace.startSpan("test"); + Assert.assertNotNull(cur); + cur.close(); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestSpanId.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestSpanId.java b/htrace-core/src/test/java/org/apache/htrace/core/TestSpanId.java new file mode 100644 index 0000000..bb57368 --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestSpanId.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import java.util.Random; + +import org.junit.Assert; +import org.junit.Test; + +public class TestSpanId { + private void testRoundTrip(SpanId id) throws Exception { + String str = id.toString(); + SpanId id2 = SpanId.fromString(str); + Assert.assertEquals(id, id2); + } + + @Test + public void testToStringAndFromString() throws Exception { + testRoundTrip(SpanId.INVALID); + testRoundTrip(new SpanId(0x1234567812345678L, 0x1234567812345678L)); + testRoundTrip(new SpanId(0xf234567812345678L, 0xf234567812345678L)); + testRoundTrip(new SpanId(0xffffffffffffffffL, 0xffffffffffffffffL)); + Random rand = new Random(12345); + for (int i = 0; i < 100; i++) { + testRoundTrip(new SpanId(rand.nextLong(), rand.nextLong())); + } + } + + @Test + public void testValidAndInvalidIds() throws Exception { + Assert.assertFalse(SpanId.INVALID.isValid()); + Assert.assertTrue( + new SpanId(0x1234567812345678L, 0x1234567812345678L).isValid()); + Assert.assertTrue( + new SpanId(0xf234567812345678L, 0xf234567812345678L).isValid()); + } + + private void expectLessThan(SpanId a, SpanId b) throws Exception { + int cmp = a.compareTo(b); + Assert.assertTrue("Expected " + a + " to be less than " + b, + (cmp < 0)); + int cmp2 = b.compareTo(a); + Assert.assertTrue("Expected " + b + " to be greater than " + a, + (cmp2 > 0)); + } + + @Test + public void testIdComparisons() throws Exception { + expectLessThan(new SpanId(0x0000000000000001L, 0x0000000000000001L), + new SpanId(0x0000000000000001L, 0x0000000000000002L)); + expectLessThan(new SpanId(0x0000000000000001L, 0x0000000000000001L), + new SpanId(0x0000000000000002L, 0x0000000000000000L)); + expectLessThan(SpanId.INVALID, + new SpanId(0xffffffffffffffffL, 0xffffffffffffffffL)); + expectLessThan(new SpanId(0x1234567812345678L, 0x1234567812345678L), + new SpanId(0x1234567812345678L, 0xf234567812345678L)); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestSpanReceiverBuilder.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestSpanReceiverBuilder.java b/htrace-core/src/test/java/org/apache/htrace/core/TestSpanReceiverBuilder.java new file mode 100644 index 0000000..79795e4 --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestSpanReceiverBuilder.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; + +public class TestSpanReceiverBuilder { + private static final Log LOG = + LogFactory.getLog(TestSpanReceiverBuilder.class); + + /** + * Test that if no span receiver is configured, the builder returns null. + */ + @Test + public void testGetNullSpanReceiver() { + SpanReceiverBuilder builder = + new SpanReceiverBuilder(HTraceConfiguration.EMPTY).logErrors(false); + SpanReceiver rcvr = builder.build(); + Assert.assertEquals(null, rcvr); + } + + private static SpanReceiver createSpanReceiver(Map<String, String> m) { + HTraceConfiguration hconf = HTraceConfiguration.fromMap(m); + SpanReceiverBuilder builder = + new SpanReceiverBuilder(hconf). + logErrors(false); + return builder.build(); + } + + private static final File TMPDIR = + new File(System.getProperty("java.io.tmpdir")); + + /** + * Test getting various SpanReceiver objects. + */ + @Test + public void testGetSpanReceivers() throws Exception { + HashMap<String, String> confMap = new HashMap<String, String>(); + + // Create LocalFileSpanReceiver + File testFile = new File(TMPDIR, UUID.randomUUID().toString()); + try { + confMap.put(LocalFileSpanReceiver.PATH_KEY, testFile.getAbsolutePath()); + confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, + "org.apache.htrace.core.LocalFileSpanReceiver"); + SpanReceiver rcvr = createSpanReceiver(confMap); + Assert.assertNotNull(rcvr); + Assert.assertEquals("org.apache.htrace.core.LocalFileSpanReceiver", + rcvr.getClass().getName()); + rcvr.close(); + } finally { + if (!testFile.delete()) { + LOG.debug("failed to delete " + testFile); // keep findbugs happy + } + } + + // Create POJOSpanReceiver + confMap.remove(LocalFileSpanReceiver.PATH_KEY); + confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, "POJOSpanReceiver"); + SpanReceiver rcvr = createSpanReceiver(confMap); + Assert.assertEquals("org.apache.htrace.core.POJOSpanReceiver", + rcvr.getClass().getName()); + rcvr.close(); + + // Create StandardOutSpanReceiver + confMap.remove(LocalFileSpanReceiver.PATH_KEY); + confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, + "org.apache.htrace.core.StandardOutSpanReceiver"); + rcvr = createSpanReceiver(confMap); + Assert.assertEquals("org.apache.htrace.core.StandardOutSpanReceiver", + rcvr.getClass().getName()); + rcvr.close(); + } + + public static class TestSpanReceiver implements SpanReceiver { + final static String SUCCEEDS = "test.span.receiver.succeeds"; + + public TestSpanReceiver(HTraceConfiguration conf) { + if (conf.get(SUCCEEDS) == null) { + throw new RuntimeException("Can't create TestSpanReceiver: " + + "invalid configuration."); + } + } + + @Override + public void receiveSpan(Span span) { + } + + @Override + public void close() throws IOException { + } + } + + /** + * Test trying to create a SpanReceiver that experiences an error in the + * constructor. + */ + @Test + public void testGetSpanReceiverWithConstructorError() throws Exception { + HashMap<String, String> confMap = new HashMap<String, String>(); + + // Create TestSpanReceiver + confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, + TestSpanReceiver.class.getName()); + confMap.put(TestSpanReceiver.SUCCEEDS, "true"); + SpanReceiver rcvr = createSpanReceiver(confMap); + Assert.assertEquals(TestSpanReceiver.class.getName(), + rcvr.getClass().getName()); + rcvr.close(); + + // Fail to create TestSpanReceiver + confMap.remove(TestSpanReceiver.SUCCEEDS); + rcvr = createSpanReceiver(confMap); + Assert.assertEquals(null, rcvr); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TestTracerId.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TestTracerId.java b/htrace-core/src/test/java/org/apache/htrace/core/TestTracerId.java new file mode 100644 index 0000000..ac43653 --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TestTracerId.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import java.io.IOException; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class TestTracerId { + private void testTracerIdImpl(String expected, String fmt) { + assertEquals(expected, new TracerId(fmt).get()); + } + + @Test + public void testSimpleTracerIds() { + testTracerIdImpl("abc", "abc"); + testTracerIdImpl("abc", "a\\bc"); + testTracerIdImpl("abc", "ab\\c"); + testTracerIdImpl("abc", "\\a\\b\\c"); + testTracerIdImpl("a\\bc", "a\\\\bc"); + } + + @Test + public void testSubstitutionVariables() throws IOException { + testTracerIdImpl(TracerId.getProcessName(), "${pname}"); + testTracerIdImpl("my." + TracerId.getProcessName(), "my.${pname}"); + testTracerIdImpl(TracerId.getBestIpString() + ".str", "${ip}.str"); + testTracerIdImpl("${pname}", "\\${pname}"); + testTracerIdImpl("$cash$money{}", "$cash$money{}"); + testTracerIdImpl("Foo." + Long.valueOf(TracerId.getOsPid()).toString(), + "Foo.${pid}"); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TraceCreator.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TraceCreator.java b/htrace-core/src/test/java/org/apache/htrace/core/TraceCreator.java new file mode 100644 index 0000000..f6ae97f --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TraceCreator.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +import java.util.Collection; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * Does some stuff and traces it. + */ +public class TraceCreator implements TestRule { + private final List<SpanReceiver> receivers = new ArrayList<SpanReceiver>(); + + public static final String RPC_TRACE_ROOT = "createSampleRpcTrace"; + public static final String THREADED_TRACE_ROOT = "createThreadedTrace"; + public static final String SIMPLE_TRACE_ROOT = "createSimpleTrace"; + + public TraceCreator addReceiver(SpanReceiver receiver) { + Trace.addReceiver(receiver); + this.receivers.add(receiver); + return this; + } + + @Override + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + try { + base.evaluate(); + for (SpanReceiver receiver : receivers) { + receiver.close(); + } + } finally { + for (SpanReceiver receiver : receivers) { + Trace.removeReceiver(receiver); + } + } + } + }; + } + + public void createSampleRpcTrace() { + TraceScope s = Trace.startSpan(RPC_TRACE_ROOT, Sampler.ALWAYS); + try { + pretendRpcSend(); + } finally { + s.close(); + } + } + + public void createSimpleTrace() { + TraceScope s = Trace.startSpan(SIMPLE_TRACE_ROOT, Sampler.ALWAYS); + try { + importantWork1(); + } finally { + s.close(); + } + } + + /** + * Creates the demo trace (will create different traces from call to call). + */ + public void createThreadedTrace() { + TraceScope s = Trace.startSpan(THREADED_TRACE_ROOT, Sampler.ALWAYS); + try { + Random r = ThreadLocalRandom.current(); + int numThreads = r.nextInt(4) + 1; + Thread[] threads = new Thread[numThreads]; + + for (int i = 0; i < numThreads; i++) { + threads[i] = new Thread(Trace.wrap(new MyRunnable())); + } + for (int i = 0; i < numThreads; i++) { + threads[i].start(); + } + for (int i = 0; i < numThreads; i++) { + try { + threads[i].join(); + } catch (InterruptedException e) { + } + } + importantWork1(); + } finally { + s.close(); + } + } + + private void importantWork1() { + TraceScope cur = Trace.startSpan("important work 1"); + try { + Thread.sleep((long) (2000 * Math.random())); + importantWork2(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + cur.close(); + } + } + + private void importantWork2() { + TraceScope cur = Trace.startSpan("important work 2"); + try { + Thread.sleep((long) (2000 * Math.random())); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + cur.close(); + } + } + + private class MyRunnable implements Runnable { + @Override + public void run() { + try { + Thread.sleep(750); + Random r = ThreadLocalRandom.current(); + int importantNumber = 100 / r.nextInt(3); + System.out.println("Important number: " + importantNumber); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } catch (ArithmeticException ae) { + TraceScope c = Trace.startSpan("dealing with arithmetic exception."); + try { + Thread.sleep((long) (3000 * Math.random())); + } catch (InterruptedException ie1) { + Thread.currentThread().interrupt(); + } finally { + c.close(); + } + } + } + } + + public void pretendRpcSend() { + pretendRpcReceiveWithTraceInfo(Trace.currentSpan()); + } + + public void pretendRpcReceiveWithTraceInfo(Span parent) { + TraceScope s = Trace.startSpan("received RPC", parent); + try { + importantWork1(); + } finally { + s.close(); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/core/TraceGraph.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/core/TraceGraph.java b/htrace-core/src/test/java/org/apache/htrace/core/TraceGraph.java new file mode 100644 index 0000000..a06e620 --- /dev/null +++ b/htrace-core/src/test/java/org/apache/htrace/core/TraceGraph.java @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.htrace.core; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.TreeSet; + +/** + * Used to create the graph formed by spans. + */ +public class TraceGraph { + private static final Log LOG = LogFactory.getLog(Tracer.class); + + + public static class SpansByParent { + /** + * Compare two spans by span ID. + */ + private static Comparator<Span> COMPARATOR = + new Comparator<Span>() { + @Override + public int compare(Span a, Span b) { + return a.getSpanId().compareTo(b.getSpanId()); + } + }; + + private final TreeSet<Span> treeSet; + + private final HashMap<SpanId, LinkedList<Span>> parentToSpans; + + SpansByParent(Collection<Span> spans) { + TreeSet<Span> treeSet = new TreeSet<Span>(COMPARATOR); + parentToSpans = new HashMap<SpanId, LinkedList<Span>>(); + for (Span span : spans) { + treeSet.add(span); + for (SpanId parent : span.getParents()) { + LinkedList<Span> list = parentToSpans.get(parent); + if (list == null) { + list = new LinkedList<Span>(); + parentToSpans.put(parent, list); + } + list.add(span); + } + if (span.getParents().length == 0) { + LinkedList<Span> list = parentToSpans.get(SpanId.INVALID); + if (list == null) { + list = new LinkedList<Span>(); + parentToSpans.put(SpanId.INVALID, list); + } + list.add(span); + } + } + this.treeSet = treeSet; + } + + public List<Span> find(SpanId parentId) { + LinkedList<Span> spans = parentToSpans.get(parentId); + if (spans == null) { + return new LinkedList<Span>(); + } + return spans; + } + + public Iterator<Span> iterator() { + return Collections.unmodifiableSortedSet(treeSet).iterator(); + } + } + + public static class SpansByTracerId { + /** + * Compare two spans by process ID, and then by span ID. + */ + private static Comparator<Span> COMPARATOR = + new Comparator<Span>() { + @Override + public int compare(Span a, Span b) { + int cmp = a.getTracerId().compareTo(b.getTracerId()); + if (cmp != 0) { + return cmp; + } + return a.getSpanId().compareTo(b.getSpanId()); + } + }; + + private final TreeSet<Span> treeSet; + + SpansByTracerId(Collection<Span> spans) { + TreeSet<Span> treeSet = new TreeSet<Span>(COMPARATOR); + for (Span span : spans) { + treeSet.add(span); + } + this.treeSet = treeSet; + } + + public List<Span> find(String tracerId) { + List<Span> spans = new ArrayList<Span>(); + Span span = new MilliSpan.Builder(). + spanId(SpanId.INVALID). + tracerId(tracerId). + build(); + while (true) { + span = treeSet.higher(span); + if (span == null) { + break; + } + if (span.getTracerId().equals(tracerId)) { + break; + } + spans.add(span); + } + return spans; + } + + public Iterator<Span> iterator() { + return Collections.unmodifiableSortedSet(treeSet).iterator(); + } + } + + private final SpansByParent spansByParent; + private final SpansByTracerId spansByTracerId; + + /** + * Create a new TraceGraph + * + * @param spans The collection of spans to use to create this TraceGraph. Should + * have at least one root span. + */ + public TraceGraph(Collection<Span> spans) { + this.spansByParent = new SpansByParent(spans); + this.spansByTracerId = new SpansByTracerId(spans); + } + + public SpansByParent getSpansByParent() { + return spansByParent; + } + + public SpansByTracerId getSpansByTracerId() { + return spansByTracerId; + } + + @Override + public String toString() { + StringBuilder bld = new StringBuilder(); + String prefix = ""; + for (Iterator<Span> iter = spansByParent.iterator(); iter.hasNext();) { + Span span = iter.next(); + bld.append(prefix).append(span.toString()); + prefix = "\n"; + } + return bld.toString(); + } +} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/impl/TestLocalFileSpanReceiver.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/impl/TestLocalFileSpanReceiver.java b/htrace-core/src/test/java/org/apache/htrace/impl/TestLocalFileSpanReceiver.java deleted file mode 100644 index 311ddc6..0000000 --- a/htrace-core/src/test/java/org/apache/htrace/impl/TestLocalFileSpanReceiver.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.htrace.impl; - -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import org.apache.htrace.HTraceConfiguration; -import org.apache.htrace.Sampler; -import org.apache.htrace.Span; -import org.apache.htrace.SpanReceiver; -import org.apache.htrace.SpanReceiverBuilder; -import org.apache.htrace.Trace; -import org.apache.htrace.TraceScope; -import org.junit.Ignore; -import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertEquals; - -public class TestLocalFileSpanReceiver { - @Test - public void testUniqueLocalTraceFileName() { - String filename1 = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); - System.out.println("##### :" + filename1); - String filename2 = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); - System.out.println("##### :" + filename2); - boolean eq = filename1.equals(filename2); - if (System.getProperty("os.name").startsWith("Linux")) { - // ${java.io.tmpdir}/[pid] - assertTrue(eq); - } else { - // ${java.io.tmpdir}/[random UUID] - assertFalse(eq); - } - } - - @Test - public void testWriteToLocalFile() throws IOException { - String traceFileName = LocalFileSpanReceiver.getUniqueLocalTraceFileName(); - HashMap<String, String> confMap = new HashMap<String, String>(); - confMap.put(LocalFileSpanReceiver.PATH_KEY, traceFileName); - confMap.put(SpanReceiverBuilder.SPAN_RECEIVER_CONF_KEY, - LocalFileSpanReceiver.class.getName()); - confMap.put(TracerId.TRACER_ID_KEY, "testTrid"); - SpanReceiver rcvr = - new SpanReceiverBuilder(HTraceConfiguration.fromMap(confMap)) - .logErrors(false).build(); - Trace.addReceiver(rcvr); - TraceScope ts = Trace.startSpan("testWriteToLocalFile", Sampler.ALWAYS); - ts.close(); - Trace.removeReceiver(rcvr); - rcvr.close(); - - ObjectMapper mapper = new ObjectMapper(); - MilliSpan span = mapper.readValue(new File(traceFileName), MilliSpan.class); - assertEquals("testWriteToLocalFile", span.getDescription()); - assertEquals("testTrid", span.getTracerId()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/impl/TestMilliSpan.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/impl/TestMilliSpan.java b/htrace-core/src/test/java/org/apache/htrace/impl/TestMilliSpan.java deleted file mode 100644 index 9a0be4a..0000000 --- a/htrace-core/src/test/java/org/apache/htrace/impl/TestMilliSpan.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.htrace.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.apache.htrace.Span; -import org.apache.htrace.SpanId; -import org.apache.htrace.TimelineAnnotation; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -public class TestMilliSpan { - private void compareSpans(Span expected, Span got) throws Exception { - assertEquals(expected.getStartTimeMillis(), got.getStartTimeMillis()); - assertEquals(expected.getStopTimeMillis(), got.getStopTimeMillis()); - assertEquals(expected.getDescription(), got.getDescription()); - assertEquals(expected.getSpanId(), got.getSpanId()); - assertEquals(expected.getTracerId(), got.getTracerId()); - assertTrue(Arrays.equals(expected.getParents(), got.getParents())); - Map<String, String> expectedT = expected.getKVAnnotations(); - Map<String, String> gotT = got.getKVAnnotations(); - if (expectedT == null) { - assertEquals(null, gotT); - } else { - assertEquals(expectedT.size(), gotT.size()); - for (String key : expectedT.keySet()) { - assertEquals(expectedT.get(key), gotT.get(key)); - } - } - List<TimelineAnnotation> expectedTimeline = - expected.getTimelineAnnotations(); - List<TimelineAnnotation> gotTimeline = - got.getTimelineAnnotations(); - if (expectedTimeline == null) { - assertEquals(null, gotTimeline); - } else { - assertEquals(expectedTimeline.size(), gotTimeline.size()); - Iterator<TimelineAnnotation> iter = gotTimeline.iterator(); - for (TimelineAnnotation expectedAnn : expectedTimeline) { - TimelineAnnotation gotAnn = iter.next(); - assertEquals(expectedAnn.getMessage(), gotAnn.getMessage()); - assertEquals(expectedAnn.getTime(), gotAnn.getTime()); - } - } - } - - @Test - public void testJsonSerialization() throws Exception { - MilliSpan span = new MilliSpan.Builder(). - description("foospan"). - begin(123L). - end(456L). - parents(new SpanId[] { new SpanId(7L, 7L) }). - tracerId("b2404.halxg.com:8080"). - spanId(new SpanId(7L, 8L)). - build(); - String json = span.toJson(); - MilliSpan dspan = MilliSpan.fromJson(json); - compareSpans(span, dspan); - } - - @Test - public void testJsonSerializationWithNegativeLongValue() throws Exception { - MilliSpan span = new MilliSpan.Builder(). - description("foospan"). - begin(-1L). - end(-1L). - parents(new SpanId[] { new SpanId(-1L, -1L) }). - tracerId("b2404.halxg.com:8080"). - spanId(new SpanId(-1L, -2L)). - build(); - String json = span.toJson(); - MilliSpan dspan = MilliSpan.fromJson(json); - compareSpans(span, dspan); - } - - @Test - public void testJsonSerializationWithRandomLongValue() throws Exception { - SpanId parentId = SpanId.fromRandom(); - MilliSpan span = new MilliSpan.Builder(). - description("foospan"). - begin(ThreadLocalRandom.current().nextLong()). - end(ThreadLocalRandom.current().nextLong()). - parents(new SpanId[] { parentId }). - tracerId("b2404.halxg.com:8080"). - spanId(parentId.newChildId()). - build(); - String json = span.toJson(); - MilliSpan dspan = MilliSpan.fromJson(json); - compareSpans(span, dspan); - } - - @Test - public void testJsonSerializationWithOptionalFields() throws Exception { - MilliSpan.Builder builder = new MilliSpan.Builder(). - description("foospan"). - begin(300). - end(400). - parents(new SpanId[] { }). - tracerId("b2408.halxg.com:8080"). - spanId(new SpanId(111111111L, 111111111L)); - Map<String, String> traceInfo = new HashMap<String, String>(); - traceInfo.put("abc", "123"); - traceInfo.put("def", "456"); - builder.traceInfo(traceInfo); - List<TimelineAnnotation> timeline = new LinkedList<TimelineAnnotation>(); - timeline.add(new TimelineAnnotation(310L, "something happened")); - timeline.add(new TimelineAnnotation(380L, "something else happened")); - timeline.add(new TimelineAnnotation(390L, "more things")); - builder.timeline(timeline); - MilliSpan span = builder.build(); - String json = span.toJson(); - MilliSpan dspan = MilliSpan.fromJson(json); - compareSpans(span, dspan); - } - - @Test - public void testJsonSerializationWithFieldsNotSet() throws Exception { - MilliSpan span = new MilliSpan.Builder().build(); - String json = span.toJson(); - MilliSpan dspan = MilliSpan.fromJson(json); - compareSpans(span, dspan); - } -} http://git-wip-us.apache.org/repos/asf/incubator-htrace/blob/fd889b65/htrace-core/src/test/java/org/apache/htrace/impl/TestTracerId.java ---------------------------------------------------------------------- diff --git a/htrace-core/src/test/java/org/apache/htrace/impl/TestTracerId.java b/htrace-core/src/test/java/org/apache/htrace/impl/TestTracerId.java deleted file mode 100644 index 271d082..0000000 --- a/htrace-core/src/test/java/org/apache/htrace/impl/TestTracerId.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.htrace.impl; - -import java.io.IOException; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestTracerId { - private void testTracerIdImpl(String expected, String fmt) { - assertEquals(expected, new TracerId(fmt).get()); - } - - @Test - public void testSimpleTracerIds() { - testTracerIdImpl("abc", "abc"); - testTracerIdImpl("abc", "a\\bc"); - testTracerIdImpl("abc", "ab\\c"); - testTracerIdImpl("abc", "\\a\\b\\c"); - testTracerIdImpl("a\\bc", "a\\\\bc"); - } - - @Test - public void testSubstitutionVariables() throws IOException { - testTracerIdImpl(TracerId.getProcessName(), "${pname}"); - testTracerIdImpl("my." + TracerId.getProcessName(), "my.${pname}"); - testTracerIdImpl(TracerId.getBestIpString() + ".str", "${ip}.str"); - testTracerIdImpl("${pname}", "\\${pname}"); - testTracerIdImpl("$cash$money{}", "$cash$money{}"); - testTracerIdImpl("Foo." + Long.valueOf(TracerId.getOsPid()).toString(), - "Foo.${pid}"); - } -}
