简体   繁体   English

Python 单元测试在本地通过,但在比较日期时在 Jenkins 中失败

[英]Python unit test passes locally, but fails in Jenkins when comparing dates

The following test passes locally, because Locally it's EST:以下测试在本地通过,因为本地是 EST:

    def test_get_local_ts(self):
        dt = Utils.get_local_ts().strftime('%Y-%m-%d')
        dt1 = datetime.now().strftime('%Y-%m-%d')
        self.assertEqual(dt, dt1)

But fails when running in a Jenkins pipeline.但在 Jenkins 管道中运行时失败。

Because Jenkins server is running on UTC time, but the method get_local_ts is returning the local time.因为 Jenkins 服务器在 UTC 时间运行,但get_local_ts方法返回的是本地时间。

And so this error happens:所以这个错误发生了:

self.assertEqual(dt, dt1) self.assertEqual(dt, dt1)

AssertionError: '2021-12-16' != '2021-12-17'断言错误:“2021-12-16”!=“2021-12-17”

Also, this will only fail when running it after 7 PM EST, when UTC rolls over to next day.此外,这只会在美国东部标准时间晚上 7 点之后运行它时失败,此时 UTC 会滚动到第二天。

How can I get this to pass locally and in Jenkins at any time?我怎样才能让它随时在本地和 Jenkins 中通过?

Thanks!谢谢!

If your unit tests involve datetime objects, then you should probably set the time zone as part of your test setup.如果您的单元测试涉及 datetime 对象,那么您可能应该将时区设置为测试设置的一部分。 A unit test should run under controlled conditions without depending on external factors.单元测试应该在受控条件下运行,而不依赖于外部因素。

https://docs.python.org/3/library/time.html#time.tzset https://docs.python.org/3/library/time.html#time.tzset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 测试在 ubuntu 上本地运行,但在通过 Jenkins 运行时失败,并出现错误“导入测试模块'/var/lib/jenkins/workspace 时导入错误” - Python tests run locally on ubuntu but fails when run through Jenkins with error "ImportError while importing test module '/var/lib/jenkins/workspace" 在 Python 的单元测试中比较 XML - Comparing XML in a unit test in Python Django:第一次测试通过,但在第二次测试添加时失败 - Django: first test passes, but fails when second test added Python 单元测试:测试失败时自动运行调试器 - Python Unit Testing: Automatically Running the Debugger when a test fails 在目录级别运行时,Python 3 单元测试失败 - Python 3 unit test fails when running at directory level Python单元测试比较列表值 - Python unit test comparing list values Python 和 pytest - 检查测试是否通过或失败并执行代码 - Python and pytest - check if a test passes or fails and execute code 是否有一个python单元测试框架,在比较字符串时提供紧凑的错误输出 - Is there a python unit test framework that gives compact error output when comparing strings 尽管满足要求,Python单元测试仍失败 - Python unit test fails despite meeting requirement 单元测试使用python运行,但由于鼻子测试失败 - unit test runs with python but fails with nosetests
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM