【问题标题】:Django - Timestamp Unit TestDjango - 时间戳单元测试
【发布时间】:2012-06-25 20:30:03
【问题描述】:

我的应用程序根据作为自定义 URL 输入提供的日期和时间提供状态。通常它会使用当前时间(datetime.now()),但我想创建单元测试来验证未来的时间。但是,我在使用时间戳作为测试变量时遇到了问题。想法?到目前为止的代码如下:

urls.py:

urlpatterns = patterns('',
   (r'^/(\w+)/status/$', 'app.views.fetch_status'),
   # Normally:
   #(r'^/(\w+)/status/$', 'app.views.fetch_status', {'timestamp': datetime.now() }),
   ...

views.py:

def fetch_status(request, slug, timestamp):
    ...

tests.py:

class TimeTests(TestCase):
    fixtures = ['hours.json']

    def testSchedule(self):
        timestamp = datetime(2012, 6, 19, 5, 0)
        client = Client()
        response = client.get('/service/status/', {'timestamp': timestamp})
        self.assertEqual(response.context['status'], 'closed')

结果:

TypeError: fetch_status() takes exactly 2 arguments (1 given)

【问题讨论】:

    标签: django unit-testing django-unittest


    【解决方案1】:

    为什么您将模式更改为不包含时间戳参数?从它的外观来看,并且根据您的错误,该函数需要一个参数,而您并没有真正提供该参数,因为您更改了模式。

    【讨论】:

    • 我想在我的单元测试中覆盖时间戳。如果我不注释该行,它将使用 datetime.now() 而不是覆盖。
    • 为什么不创建一个空的 datetime 对象,然后你可以传入呢?或更改fetch_status 函数以减少参数,并将测试日期时间视为有效负载的一部分
    • 我创建了一个可选参数,它通过 URL 接受 unix 时间戳。谢谢!
    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多