TypeError: list indices must be integers or slices, not str on Unit Testing

◇◆丶佛笑我妖孽 提交于 2020-06-29 03:33:28

问题


I have the error as "TypeError: list indices must be integers or slices, not str " while running a unit test on the following function. The following function is used to call the model that is saved in Google AI Platform. However, the data input has to be base64 serialized, hence, I include the get_serialized_example(raw) function within the tfx_test(request). Any help and advice are appreciated. Thanks in advance!

def tfx_test(request):
    
    #User Inputs
    project = request.project
    model = request.model
    signature = request.signature
    version = request.version
    
    #Data inputs Base64 encoder 
    
    def get_serialized_example(raw):
        return tf.train.Example(
                features=tf.train.Features(
                  feature={"value":
                              tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw]))
                          }
                    )
                ).SerializeToString()


    b64_country_code = base64.b64encode(get_serialized_example(request.country_code)).decode('utf-8')
    
    b64_project_type = base64.b64encode(get_serialized_example(request.project_type)).decode('utf-8')
    
    # ml.googleapis.com
    service = googleapiclient.discovery.build('ml', 'v1')
    name = 'projects/{}/models/{}'.format(project, model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,
        body={
            'signature_name': signature,
            'instances': [
                    {
                       "examples":{"b64": b64_country_code,
                                   "b64": b64_project_type}
                    }]
        }
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']

UNIT TESTING

def test_safety_kfp_custom(self):

self.request = TestScenario.populated_request(Test.test1)
self.response = tfx_test(self.request)

self.assertEqual(0.35915321111679077, self.response["predictions"])

Data Input for tfx_test function

class request():
    project = "xxx"
    model = "xxx"
    signature = "xxx"
    country_code = b"UK"
    project_type = b"PT"
    version = 'xxx'

回答1:


As Zenith mentioned in the comment, I should return the response instead of response['predictions'] on the return of the function. Thanks,



来源:https://stackoverflow.com/questions/62549037/typeerror-list-indices-must-be-integers-or-slices-not-str-on-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!