本文介绍了每次单元测试后重置 Prometheus lib 的 CollectorRegistry的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 A 类,它在它的 init

I have a class A that initializes a Counter in its init

from prometheus_client import Counter
class A:
    def __init__(self):
        self.my_counter = Counter('an_awesome_counter')
    def method_1(self):
        return 1
    def method_2(self):
        return 2

然后我写测试类:

import unittest
import A

class ATests(unittest.TestCase):
    def setUp(self):
        self.a = A()
    def tearDown(self):
        self.a = None
    def method_1_test(self):
        ....
    def method_2_test(self):
        ....

事情是,如果我单独运行测试,它们很好.但是,当我将它们一起运行时(运行整个 ATests 类),出现以下错误:

Thing is, if I run the test separately, they are fine. Yet when I run them together (Run the whole ATests class), I have the error as:

ValueError: CollectorRegistry 中的重复时间序列:{'an_awesome_counter'}

所以似乎每次测试运行后都没有重置python环境.我检查了 CollectorRegistry 并且有一种取消注册收集器的方法,但这样做似乎有点难看.

So it seems that the python environment isn't reset after each test run. I check the CollectorRegistry and there is a method to unregister collector, but it seems a bit ugly to do that.

不知道有没有其他方法可以解决这个问题?比如每次都强制测试在新环境下运行..

I wonder if there is another way to solve this problem? Like forcing the test to run with new environment every time for example..

谢谢.

推荐答案

目前,我将 a = A() 移出 setup(self) 并将其变成类变量作为解决方案

For the moment, I moved a = A() out of setup(self) and turned it into a class variable as a workaround solution

这篇关于每次单元测试后重置 Prometheus lib 的 CollectorRegistry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 00:27