为什么当我运行以下代码时没有错误消息?
main.py
def main():
# load config
envConfig.init()
# init mongodb
mongodb.init()
# start mqtt client
sensor_data_mqtt_client.listening()
if __name__ == "__main__":
main()
sensor_data_mqtt_client.py
def on_connect(client, userdata, flags, rc):
logger.info("Connected mqtt with result code:{} ", str(rc))
def on_message(client, userdata, msg):
topic = msg.topic
incoming_message = json.loads(msg.payload.decode('utf-8'))
logger.info("message received. topic:{}, message:{}", topic, incoming_message)
unify_service.update_warning(incoming_message)
logger.info("updated warning_history")
def connect():
# envConfig.init()
evn_config = envConfig.get_config()
# mongodb.init()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username='admin', password='public')
client.connect(evn_config['mqtt']['host'], evn_config['mqtt']['port'], 60)
logger.info('connected to mqtt, host:{}, port:{}', evn_config['mqtt']['host'], str(evn_config['mqtt']['port']))
return client
def subscribe(client, topic):
client.subscribe(topic)
logger.info('subscribed to topic:{}', topic)
def publish(client, topic, message):
client.publish(topic, message, 0)
def listening():
client = connect()
for topic in DeviceType.get_topic_names():
client.subscribe(topic)
logger.info('subscribed to topic:{}', topic)
client.loop_forever()
unify_service.py
SIZE_LIMIT = 256
def update_warning(sensor_message):
warning_history_collection = 'warning_history'
device_name = sensor_message['deviceName']
device_eui = sensor_message['eui']
device_type = sensor_message['type']
device_district = sensor_message['district']
device_floor = sensor_message['floor']
device_location = sensor_message['location']
filter_json = {
'name': device_name,
'eui': device_eui,
'type': device_type,
'district': device_district,
'size': {
'$lt': SIZE_LIMIT
},
'day': dateutil.get_today_start()
}
current_time = dateutil.get_current_time()
update_json = {
'$push': {'records': {'floor': device_floor, 'location': device_location,
'warning_time': current_time}},
'$min': {"first", current_time},
'$max': {"last", current_time},
'$inc': {'size': 1}
}
mongodb_wrapper.update_one(warning_history_collection, filter_json, update_json, upsert=True)
运行代码时,有一条记录器消息
收到的消息。主题:xxx,消息:xxx
在控制台中,但不会引发任何错误消息。
如何使代码抛出错误消息?任何建议表示赞赏。
在单元测试中调用unify_service.update_warning时。它给出错误信息:
FAILED (errors=1)
Error
Traceback (most recent call last):
File "D:\python3.7\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "D:\python3.7\lib\unittest\case.py", line 628, in run
testMethod()
File "F:\workspaces\PythonWorkspace\unify-service\service\unify_service_test.py", line 13, in test_update_warning
unify_service.update_warning(sensor_message)
File "F:\workspaces\PythonWorkspace\unify-service\service\unify_service.py", line 37, in update_warning
mongodb_wrapper.update_one(warning_history_collection, filter_json, update_json, upsert=True)
File "F:\workspaces\PythonWorkspace\unify-service\common\mongo\mongodb_wrapper.py", line 20, in update_one
mongodb.get_db()[collection].update_one(condition, data, upsert)
File "D:\python3.7\lib\site-packages\pymongo\collection.py", line 1003, in update_one
session=session),
File "D:\python3.7\lib\site-packages\pymongo\collection.py", line 856, in _update_retryable
_update, session)
File "D:\python3.7\lib\site-packages\pymongo\mongo_client.py", line 1492, in _retryable_write
return self._retry_with_session(retryable, func, s, None)
File "D:\python3.7\lib\site-packages\pymongo\mongo_client.py", line 1385, in _retry_with_session
return func(session, sock_info, retryable)
File "D:\python3.7\lib\site-packages\pymongo\collection.py", line 852, in _update
retryable_write=retryable_write)
File "D:\python3.7\lib\site-packages\pymongo\collection.py", line 822, in _update
retryable_write=retryable_write).copy()
File "D:\python3.7\lib\site-packages\pymongo\pool.py", line 618, in command
self._raise_connection_failure(error)
File "D:\python3.7\lib\site-packages\pymongo\pool.py", line 613, in command
user_fields=user_fields)
File "D:\python3.7\lib\site-packages\pymongo\network.py", line 129, in command
codec_options, ctx=compression_ctx)
File "D:\python3.7\lib\site-packages\pymongo\message.py", line 704, in _op_msg
flags, command, identifier, docs, check_keys, opts)
bson.errors.InvalidDocument: cannot encode object: {'first', 1594177547129}, of type: <class 'set'>
TestUnifyService.py
class TestUnifyService(unittest.TestCase):
def test_update_warning(self):
envConfig.init()
mongodb.init()
sensor_message = {'isAlarm': 'true', 'isDemolition': 'false', 'isLowVoltage': 'false', 'voltage': '3.6', 'applicationName': 'winext-application', 'deviceName': 'seal-01', 'eui': 'ffffff10000118c0', 'type': 'seal', 'district': 'New York', 'floor': '6', 'location': 'New York'}
unify_service.update_warning(sensor_message)
mongodb_wrapper.py
def insert_one(collection, data):
return mongodb.get_db()[collection].insert_one(data)
def insert_many(collection, data):
mongodb.get_db()[collection].insert_many(data)
def update_one(collection, condition, data, upsert):
mongodb.get_db()[collection].update_one(condition, data, upsert)
def update_many(collection, condition, data, upsert):
mongodb.get_db()[collection].update_many(condition, data, upsert)
def find_one(collection, query):
return mongodb.get_db()[collection].find_one(query)
def find_all(collection):
return mongodb.get_db()[collection].find()
def find_all_without_id(collection):
return mongodb.get_db()[collection].find({}, {'_id': False})
def find_all_condition(collection, condition):
return mongodb.get_db()[collection].find(condition)
def find_all_condition_order(collection, condition, field):
order = [(field, pymongo.ASCENDING)]
return mongodb.get_db()[collection].find(condition).sort(order)
def count(collection, condition):
return mongodb.get_db()[collection].find(condition).count()
def find_all_limit(collection, limit):
return mongodb.get_db()[collection].find().limit(limit)
def find_with_desc_order(collection, condition, field, limit):
order = [(field, pymongo.DESCENDING)]
return mongodb.get_db()[collection].find(condition).sort(order).limit(limit)
def aggregate(collection, pipeline):
return mongodb.get_db()[collection].aggregate(pipeline)
def remove_all(collection):
return mongodb.get_db()[collection].delete_many({})
def remove_all_condition(collection, condition):
return mongodb.get_db()[collection].delete_many(condition)
def remove_one(collection, data):
return mongodb.get_db()[collection].remove(data)
def create_indexes(collection, tuple_indexes):
mongodb.get_db()[collection].create_indexes(tuple_indexes)
def create_index(collection, tuple_index):
mongodb.get_db()[collection].create_index(tuple_index, unique=True)
def get_indexes(collection):
return mongodb.get_db()[collection].list_indexes()
unitTest.py-> unify_service.update_warning给出错误消息。
main.py-> mqtt.on_message-> unify_service.update_warning没有给出错误消息。
如何使main.py-> mqtt.on_message-> unify_service.update_warning给出错误消息?任何建议表示赞赏。
答案 0 :(得分:0)
如果收到bson.errors.InvalidDocument: cannot encode object: ... of type: <class 'set'>
消息,则可能是您不小心构造了一个集合而不是一个字典,确实如此。
您的问题在这里:
'$min': {"first", current_time},
'$max': {"last", current_time},
可能应该是:
'$min': {"first": current_time},
'$max': {"last": current_time},