Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django TransactionTestCase-主线程可以';看不到在子线程中创建的模型对象_Django_Multithreading_Django Rest Framework_Python Multithreading_Django Testing - Fatal编程技术网

Django TransactionTestCase-主线程可以';看不到在子线程中创建的模型对象

Django TransactionTestCase-主线程可以';看不到在子线程中创建的模型对象,django,multithreading,django-rest-framework,python-multithreading,django-testing,Django,Multithreading,Django Rest Framework,Python Multithreading,Django Testing,我正在尝试在Django应用程序中运行一些测试。我基本上是在用我的视图测试paho mqtt发布者和订阅者 订阅者需要无限期地运行以侦听发布者的消息,因此我在另一个线程中运行订阅者,它侦听主题并相应地保存对象。但问题是,我的测试是在主线程中运行的,即使我正在将TransactionTestCase子类化(正如许多答案中建议的那样),我仍然没有在主线程中获取对象。对子线程中的对象进行计数得到6,而对主线程中的对象进行计数得到0 代码如下: # The callback for when t

我正在尝试在Django应用程序中运行一些测试。我基本上是在用我的视图测试paho mqtt发布者和订阅者

订阅者需要无限期地运行以侦听发布者的消息,因此我在另一个线程中运行订阅者,它侦听主题并相应地保存对象。但问题是,我的测试是在主线程中运行的,即使我正在将TransactionTestCase子类化(正如许多答案中建议的那样),我仍然没有在主线程中获取对象。对子线程中的对象进行计数得到6,而对主线程中的对象进行计数得到0

代码如下:

    # The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    topic = 'SENSOR/+'

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    
    client.subscribe(topic)




class SensorReadingAPITest(TransactionTestCase):
    """
    A class to test API endpoints of creation, updating, and retriving sensor readings.
    """
    def setUp(self):
        self.api_client = APIClient()
        sensor = Sensor(name="test_sensor",threshold=28,alarm_systems="EM")
        sensor.save()
        self.sensor = Sensor.objects.get(name="test_sensor")
        print(self.sensor)
        #Connection to the client is established here
        self.client = mqtt.Client()
        self.client.on_connect = on_connect
        self.client.on_message = self.on_message
        self.client.connect("my_client_ip",port=1883)
        self.count = 0
        #_thread.start_new_thread(self.client.loop_forever)
        self.client.loop_start()   

    def test_publish_reading(self):
        mqttBroker = "my_broker_ip"
        client = mqtt.Client()

        client.connect(mqttBroker,port=1883)
        i=0
        id = Sensor.objects.all()[0].id
        while i < 6:
            j = randint(1,361)
            num = math.sin(j)
            #id = randrange(1,5)
            client.publish(f"SENSOR/{id}",num)
            print(f"Just published {num} to topic SENSOR/{id} with count {i} and sine({j})")
            i = i+1
            self.count = self.count+1
            time.sleep(1)

    # The callback for when a PUBLISH message is received from the server.
    def on_message(self,client, userdata, msg):
        cursor = connection.cursor()
        print(msg.topic+" "+str(msg.payload))
        url = "http://localhost:8000/sensors/readings/"
        id = int(msg.topic.split("/")[1])
        print(id)

        data = {
            "sensor" : id,
            "reading" : msg.payload
        }

        self.api_client.post(url,data)
        print()
        connection.close()



        # We need to make sure that we have 6 new readings (i < 6) in our datbase

    def test_readings_exist(self):  
        self.client.loop_stop()
        self.assertEqual(len(SensorReading.objects.all()),6)
#客户端从服务器接收CONNACK响应时的回调。
连接上的def(客户端、用户数据、标志、rc):
打印(“与结果代码连接”+str(rc))
主题='传感器/+'
#在_connect()上订阅意味着如果我们失去连接
#重新连接,然后将续订订阅。
client.subscribe(主题)
类SensorReadingAPITest(TransactionTestCase):
"""
用于测试创建、更新和检索传感器读数的API端点的类。
"""
def设置(自):
self.api_client=APIClient()
传感器=传感器(名称=“测试传感器”,阈值=28,报警系统=“EM”)
sensor.save()
self.sensor=sensor.objects.get(name=“test\u sensor”)
打印(自动传感器)
#在此处建立与客户端的连接
self.client=mqtt.client()
self.client.on_connect=on_connect
self.client.on_message=self.on_message
self.client.connect(“我的客户机ip”,端口=1883)
self.count=0
#_thread.start\u new\u线程(self.client.loop\u forever)
self.client.loop_start()
def测试_发布_读数(自):
mqttBroker=“我的经纪人”
client=mqtt.client()
connect(mqttBroker,端口=1883)
i=0
id=Sensor.objects.all()[0].id
而我<6:
j=randint(1361)
num=math.sin(j)
#id=随机范围(1,5)
client.publish(f“SENSOR/{id}”,num)
打印(f“刚刚发布{num}到主题传感器/{id},带有计数{i}和正弦({j})”的)
i=i+1
self.count=self.count+1
时间。睡眠(1)
#从服务器接收发布消息时的回调。
def on_消息(self、client、userdata、msg):
cursor=connection.cursor()
打印(msg.topic+“”+str(msg.payload))
url=”http://localhost:8000/sensors/readings/"
id=int(msg.topic.split(“/”[1])
打印(id)
数据={
“传感器”:id,
“读取”:msg.payload
}
self.api_client.post(url、数据)
打印()
连接。关闭()
#我们需要确保数据库中有6个新读数(i<6)
def测试读数存在(自身):
self.client.loop_stop()
self.assertEqual(len(SensorReading.objects.all()),6)
下面是我运行代码时得到的输出。如您所见,我的数据库中确实有SensorReading对象,但它们没有显示在我的测试中

(iot_env) PS D:\IOT_Portal\iot_project> python manage.py test --settings=iot_project.settings.dev
D:\IOT_Portal\iot_project\iot_project
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.......test_sensor
Connected with result code 0
Just published -0.8116033871367005 to topic SENSOR/20 with count 0 and sine(131)
SENSOR/20 b'-0.8116033871367005'
20
<TimescaleQuerySet [<SensorReading: 53.0>]>
Just published 0.6229886314423488 to topic SENSOR/20 with count 1 and sine(103)
SENSOR/20 b'0.6229886314423488'
20
<TimescaleQuerySet [<SensorReading: 53.0>, <SensorReading: 56.0>]>
Just published -0.5365729180004349 to topic SENSOR/20 with count 2 and sine(12)
SENSOR/20 b'-0.5365729180004349'
20
<TimescaleQuerySet [<SensorReading: 53.0>, <SensorReading: 56.0>, <SensorReading: 57.0>]>
Just published -0.997171023392149 to topic SENSOR/20 with count 3 and sine(187)
SENSOR/20 b'-0.997171023392149'
20
<TimescaleQuerySet [<SensorReading: 53.0>, <SensorReading: 56.0>, <SensorReading: 57.0>, <SensorReading: 57.0>]>
Just published 0.5139784559875352 to topic SENSOR/20 with count 4 and sine(78)
SENSOR/20 b'0.5139784559875352'
20
<TimescaleQuerySet [<SensorReading: 53.0>, <SensorReading: 56.0>, <SensorReading: 57.0>, <SensorReading: 57.0>, <SensorReading: 50.0>]>
Just published -0.8116033871367005 to topic SENSOR/20 with count 5 and sine(131)
SENSOR/20 b'-0.8116033871367005'
20
<TimescaleQuerySet [<SensorReading: 53.0>, <SensorReading: 56.0>, <SensorReading: 57.0>, <SensorReading: 57.0>, <SensorReading: 50.0>, <SensorReading: 53.0>]>
.test_sensor
F
======================================================================
FAIL: test_readings_exist (sensors.tests.test_sensors.SensorReadingAPITest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\IOT_Portal\iot_project\sensors\tests\test_sensors.py", line 103, in test_readings_exist
    self.assertEqual(len(SensorReading.objects.all()),6)
AssertionError: 0 != 6

----------------------------------------------------------------------
Ran 9 tests in 7.407s

FAILED (failures=1)
Destroying test database for alias 'default'...
(iot\u env)PS D:\iot\u Portal\iot\u project>python manage.py测试--settings=iot\u project.settings.dev
D:\IOT\U门户\IOT\U项目\IOT\U项目
正在为别名“default”创建测试数据库。。。
系统检查未发现任何问题(0静音)。
……测试传感器
已与结果代码0连接
刚刚发布-0.8116033871367005至主题传感器/20,计数为0,正弦(131)
传感器/20 b'-0.8116033871367005'
20
刚刚将0.6229886314423488发布到主题传感器/20,带有计数1和正弦(103)
传感器/20 b'0.6229886314423488'
20
刚刚发布-0.5365729180004349至主题传感器/20,带有计数2和正弦(12)
传感器/20 b'-0.5365729180004349'
20
刚刚发布-0.997171023392149至主题传感器/20,带有计数3和正弦(187)
传感器/20 b'-0.997171023392149'
20
刚刚将0.513978459875352发布到主题传感器/20,带有计数4和正弦(78)
传感器/20 b'0.513978459875352'
20
刚刚发布-0.8116033871367005至主题传感器/20,带有计数5和正弦(131)
传感器/20 b'-0.8116033871367005'
20
.测试传感器
F
======================================================================
失败:测试读数存在(传感器。测试。测试传感器。传感器读数测试)
----------------------------------------------------------------------
回溯(最近一次呼叫最后一次):
文件“D:\IOT\U门户\IOT\U项目\sensors\tests\test\u sensors.py”,第103行,位于测试读数中
self.assertEqual(len(SensorReading.objects.all()),6)
断言错误:0!=6.
----------------------------------------------------------------------
在7.407秒内运行了9个测试
失败(失败=1)
正在销毁别名“default”的测试数据库。。。