【问题标题】:Make the runserver command run with code使 runserver 命令与代码一起运行
【发布时间】:2015-09-15 12:15:35
【问题描述】:

我想用 manage.py runserver 命令启动一个服务器,我正在尝试一段时间,但没有真正找到正确的方法。

from subprocess import Popen, PIPE
from django.test import TestCase
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class ExampleClass(TestCase):

  def startServer(self):
    process = Popen(['cd C:\mypath'], stdin=PIPE, stdout=PIPE)
    process.stdin.write(['python', 'manage.py runserver'])

.
.
.
  def test_examplename(self):
    self.browser.get('http://localhost:8000')

每次我开始测试时,似乎该过程都在后台启动,但只要浏览器窗口弹出,它就会显示“无法连接”错误。 所以服务器没有运行。

请注意,当我自己启动服务器时,测试工作正常。

【问题讨论】:

    标签: python django python-3.x testing


    【解决方案1】:

    这东西

    process = Popen(['cd C:\mypath'], stdin=PIPE, stdout=PIPE)
    process.stdin.write(['python', 'manage.py runserver'])
    

    因为您在 Popen 中运行 shell 命令,所以将无法正常工作。 当您执行 Popen 时,它会尝试运行使用给定参数指定的程序。 您尝试运行 cd 但在它完成后(它可能失败,因为您在调用 Popen 时缺少 shell=True)进程已关闭,您无法写入其标准输入,Popen 不会打开 shell(或Windows 中的 cmd 实例)它只是运行一个程序

    如果你想直接运行你的服务器:

    process = Popen(['python, 'C:\mypath\manage.py', 'runserver'], stdin=PIPE, stdout=PIPE)
    

    【讨论】:

    • 现在我更了解 Popen,谢谢。但即使使用您的解决方案,它也不起作用。 Popen 调用的程序是否在整个测试运行时保持活动状态?
    • 是的,进程应该保持运行,除非它自己关闭(例如,如果你有语法错误,那么 python 将输出错误然后退出)。你可以在打开它后执行 process.poll() ,它返回 None 比进程启动,如果它返回一个数字,它是该进程的返回码(一个数字不是 0 表示有错误)
    【解决方案2】:

    对于使用 Selenium 的测试,我建议您使用 LiveServerTestCase 而不是 TestCase。 Django 将负责启动和停止服务器,因此您不必担心。

    有关更多信息和使用 Selenium 的测试用例示例,请参阅the docs

    【讨论】:

    • 更简单,更容易使用,谢谢。由于我对 StackOverflow 很陌生,我不确定是否应该将您的问题标记为正确,因为它不是问题的解决方案,而是更好的解决方法。
    • 勾选框表示接受“如果它解决了您的问题”的答案。如果它以与您最初预期不同的方式解决了您的问题,则可以接受答案。话虽如此,完全取决于您接受哪个答案,如果您想接受一个更接近您最初问题的答案,我不会被冒犯。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2010-10-29
    • 1970-01-01
    • 2014-02-11
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多