测试

当依赖 OpenTelemetry 来满足您的可观察性需求时,验证某些 Span 是否已创建以及属性是否已正确设置非常重要。例如,您能确定您是否将正确的元数据附加到了最终为 SLO 提供动力的数据中吗?本文档介绍了一种处理此类验证的方法。

设置

在 Elixir/Erlang 中进行测试仅需要 opentelemetryopentelemetry_api

{deps, [{opentelemetry_api, "~> 1.4"},
        {opentelemetry, "~> 1.5"}]}.
def deps do
  [
    {:opentelemetry_api, "~> 1.4"},
    {:opentelemetry, "~> 1.5"}
  ]
end

将您的 exporter 设置为 :none,将 Span Processor 设置为 :otel_simple_processor。这可以确保您的测试不会实际将数据导出到目的地,并且 Span 在处理后可以进行分析。

%% config/sys.config.src
{opentelemetry,
  [{traces_exporter, none},
   {processors,
     [{otel_simple_processor, #{}}]}]}
# config/test.exs
import Config

config :opentelemetry,
    traces_exporter: :none

config :opentelemetry, :processors, [
  {:otel_simple_processor, %{}}
]

来自 入门指南hello 函数的修改版本将作为我们的测试用例

%% apps/otel_getting_started/src/otel_getting_started.erl
-module(otel_getting_started).

-export([hello/0]).

-include_lib("opentelemetry_api/include/otel_tracer.hrl").

hello() ->
    %% start an active span and run a local function
    ?with_span(<<"operation">>, #{}, fun nice_operation/1).

nice_operation(_SpanCtx) ->
    ?set_attributes([{a_key, <<"a value">>}]),
    world
# lib/otel_getting_started.ex
defmodule OtelGettingStarted do
  require OpenTelemetry.Tracer, as: Tracer

  def hello do
    Tracer.with_span "operation" do
      Tracer.set_attributes([{:a_key, "a value"}])
      :world
    end
  end
end

测试

-module(otel_getting_started_SUITE).

-compile(export_all).

-include_lib("stdlib/include/assert.hrl").
-include_lib("common_test/include/ct.hrl").

-include_lib("opentelemetry/include/otel_span.hrl").

-define(assertReceive(SpanName),
        receive
            {span, Span=#span{name=SpanName}} ->
                Span
        after
            1000 ->
                ct:fail("Did not receive the span after 1s")
        end).

all() ->
    [greets_the_world].

init_per_suite(Config) ->
    application:load(opentelemetry),
    application:set_env(opentelemetry, processors, [{otel_simple_processor, #{}}]),
    {ok, _} = application:ensure_all_started(opentelemetry),
    Config.

end_per_suite(_Config) ->
    _ = application:stop(opentelemetry),
    _ = application:unload(opentelemetry),
    ok.

init_per_testcase(greets_the_world, Config) ->
    otel_simple_processor:set_exporter(otel_exporter_pid, self()),
    Config.

end_per_testcase(greets_the_world, _Config) ->
    otel_simple_processor:set_exporter(none),
    ok.

greets_the_world(_Config) ->
    otel_getting_started:hello(),

    ExpectedAttributes = otel_attributes:new(#{a_key => <<"a_value">>}, 128, infinity),
    #span{attributes=ReceivedAttributes} = ?assertReceive(<<"operation">>),

    %% use an assertMatch instead of matching in the `receive'
    %% so we get a nice error message if it fails
    ?assertMatch(ReceivedAttributes, ExpectedAttributes),

    ok.
defmodule OtelGettingStartedTest do
  use ExUnit.Case

  # Use Record module to extract fields of the Span record from the opentelemetry dependency.
  require Record
  @fields Record.extract(:span, from: "deps/opentelemetry/include/otel_span.hrl")
  # Define macros for `Span`.
  Record.defrecordp(:span, @fields)

  test "greets the world" do
    # Set exporter to :otel_exporter_pid, which sends spans
    # to the given process - in this case self() - in the format {:span, span}
    :otel_simple_processor.set_exporter(:otel_exporter_pid, self())

    # Call the function to be tested.
    OtelGettingStarted.hello()

    # Use Erlang's `:otel_attributes` module to create attributes to match against.
    # See the `:otel_events` module for testing events.
    attributes = :otel_attributes.new([a_key: "a value"], 128, :infinity)

    # Assert that the span emitted by OtelGettingStarted.hello/0 was received and contains the desired attributes.
    assert_receive {:span,
                    span(
                      name: "operation",
                      attributes: ^attributes
                    )}
  end
end