|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +#include <gtest/gtest.h> |
| 5 | +#include <cstdio> |
| 6 | +#include <fstream> |
| 7 | +#include <string> |
| 8 | + |
| 9 | +#include "opentelemetry/nostd/string_view.h" |
| 10 | +#include "opentelemetry/resource_detectors/container_detector_utils.h" |
| 11 | + |
| 12 | +TEST(ContainerIdDetectorTest, ExtractValidContainerIdFromLine) |
| 13 | +{ |
| 14 | + std::string line = |
| 15 | + "13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23.aaaa"; |
| 16 | + std::string extracted_id = |
| 17 | + opentelemetry::resource_detector::detail::ExtractContainerIDFromLine(line); |
| 18 | + EXPECT_EQ(std::string{"ac679f8a8319c8cf7d38e1adf263bc08d23"}, extracted_id); |
| 19 | +} |
| 20 | + |
| 21 | +TEST(ContainerIdDetectorTest, ExtractIdFromMockUpCGroupFile) |
| 22 | +{ |
| 23 | + const char *filename = "test_cgroup.txt"; |
| 24 | + |
| 25 | + { |
| 26 | + std::ofstream outfile(filename); |
| 27 | + outfile << "13:name=systemd:/kuberuntime/containerd" |
| 28 | + "/kubepods-pod872d2066_00ef_48ea_a7d8_51b18b72d739:cri-containerd:" |
| 29 | + "e857a4bf05a69080a759574949d7a0e69572e27647800fa7faff6a05a8332aa1\n"; |
| 30 | + outfile << "9:cpu:/not-a-container\n"; |
| 31 | + } |
| 32 | + |
| 33 | + std::string container_id = |
| 34 | + opentelemetry::resource_detector::detail::GetContainerIDFromCgroup(filename); |
| 35 | + EXPECT_EQ(container_id, |
| 36 | + std::string{"e857a4bf05a69080a759574949d7a0e69572e27647800fa7faff6a05a8332aa1"}); |
| 37 | + |
| 38 | + std::remove(filename); |
| 39 | +} |
| 40 | + |
| 41 | +TEST(ContainerIdDetectorTest, DoesNotExtractInvalidLine) |
| 42 | +{ |
| 43 | + std::string line = "this line does not contain a container id"; |
| 44 | + std::string id = opentelemetry::resource_detector::detail::ExtractContainerIDFromLine(line); |
| 45 | + EXPECT_EQ(id, std::string{""}); |
| 46 | +} |
| 47 | + |
| 48 | +TEST(ContainerIdDetectorTest, ReturnsEmptyOnNoMatch) |
| 49 | +{ |
| 50 | + const char *filename = "test_empty_cgroup.txt"; |
| 51 | + |
| 52 | + { |
| 53 | + std::ofstream outfile(filename); |
| 54 | + outfile << "no container id here\n"; |
| 55 | + } |
| 56 | + |
| 57 | + std::string id = opentelemetry::resource_detector::detail::GetContainerIDFromCgroup(filename); |
| 58 | + EXPECT_EQ(id, std::string{""}); |
| 59 | + |
| 60 | + std::remove(filename); // cleanup |
| 61 | +} |
| 62 | + |
| 63 | +TEST(ContainerIdDetectorTest, ReturnsEmptyOnFileFailingToOpen) |
| 64 | +{ |
| 65 | + const char *filename = "test_invalid_cgroup.txt"; |
| 66 | + |
| 67 | + std::string id = opentelemetry::resource_detector::detail::GetContainerIDFromCgroup(filename); |
| 68 | + EXPECT_EQ(id, std::string{""}); |
| 69 | +} |
0 commit comments