用于Robot Framework的Mongo Db扩展库返回错误记录

时间:2015-08-06 08:33:07

标签: python mongodb python-2.7 robotframework

我已经扩展了MongoDbLibrary for Robot Framework,可以使用.skip(),。take()和.order()

def _retrieve_mongodb_records_ex(self, dbName, dbCollName, recordJSON, sorting, skip=0, take=None, fields=[], returnDocuments=False):
    db = None
    try:
        dbName = str(dbName)
        dbCollName = str(dbCollName)
        criteria = dict(json.loads(recordJSON))
        db = self._dbconnection['%s' % (dbName,)]
        coll = db['%s' % (dbCollName)]
        if fields:
            results = coll.find(criteria, fields)
        else:
            results = coll.find(criteria)
        if sorting:
            results = results.sort(sorting)
        if (skip):
            skip = int(skip)
        if skip > 0:
            results = results.skip(skip)
        if take:
            results = results.limit(int(take))
        if returnDocuments:
            return list(results)
        else:
            response = ''
            for d in results:
                response = '%s%s' % (response, d.items())
            return response
    finally :
        if db :
            self._dbconnection.end_request()

我对python进行了测试:

mongo.connect_to_mongodb("mongodb://somehost", 27017)
result = mongo.retrieve_some_records("MMMongoDB", "importjob", "{\"Status\" : 9}", [("DateCreated", -1)], "0", "1", True)

此测试返回正确的数据

在机器人框架中,我在我的关键字中使用此方法:

Get Some Mongo Records With Order And Limit
[Arguments]    ${MongoHostProp}    ${MongoPortProp}    ${MongoDbNameProp}    ${MongoCollProp}    ${QueryProp}    ${Sorting}
...    ${Skip}    ${Take}
Connect To MongoDB    ${MongoHostProp}    ${MongoPortProp}
${records}=    Retrieve Some Records    ${VAR_ImportMongoDbName}    ${VAR_ImportJobMongoCollName}    ${QueryProp}    ${Sorting}    ${Skip}
...    ${Take}    true
Disconnect From Mongodb
[Return]    ${records}

但是此关键字会返回与$ {QueryProp}匹配的第一个项目,而忽略$ {Sorting}。

我比较了我发送给这个python方法的参数 - 它们是相同的。有谁知道这是什么问题?

1 个答案:

答案 0 :(得分:1)

我认为pymongo不将排序参数视为键值对的原因是RobotFramework,它倾向于将每个值都转换为字符串。

您的Python代码应检查该值是否为字符串并对其进行评估以将其重新转换为键值对列表。

    if isinstance(sorting, string_types):
                    sorting = eval(sorting)

Pymongo将字符串解释为单个排序键,并通过添加'pymongo.ASCENDING'将其转换为对,这是默认方向。