繁体   English   中英

使用代码运行 runserver 命令

[英]Make the runserver command run with code

我想用 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')

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

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

这东西

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(或一个 cmd 实例) windows)它只是运行一个程序

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

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

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

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM