怎么用MockStub调试fabric 2.4的contractapi链码?
时间: 2023-05-28 14:02:35 浏览: 87
MockStub是一个功能强大的工具,它可以帮助我们在不需要实际运行fabric网络的情况下测试和调试链码。
以下是在fabric 2.4中使用MockStub调试链码的步骤:
1. 导入所需的包
```python
import pytest
from unittest.mock import Mock
from contract_api.contracts.my_contract import MyContract
from contract_api.utils import decode_response
from contract_api.constants import HTTPStatusCodes
from contract_api.exceptions import OperationError
from contract_api.models.response import Response
from contract_api.models.operation import Operation
```
2. 创建MockStub实例
```python
chaincode_name = "my_chaincode"
channel_name = "my_channel"
mock = Mock()
mock.name = f"{chaincode_name}:{channel_name}"
contract_stub = MyContract(stub=mock)
```
3. 模拟链码调用
以调用initLedger函数为例:
```python
# 构造函数参数
args = ["1", "张三", "李四", "200", "2021.5.6"]
# 模拟初始化调用
mock.invokeChaincode.return_value = ('{"status": "Success"}', None)
result = contract_stub.initLedger(*args)
# 检查返回结果是否正确
assert result is not None
assert result.status == HTTPStatusCodes.OK
assert result.body == "Ledger initialized successfully"
```
4. 模拟查询调用
以调用getAsset函数为例:
```python
# 构造函数参数
asset_id = "1"
# 模拟查询调用
result_bytes = b'{"id": "1", "owner": "张三", "holder": "李四", "value": "200", "date": "2021.5.6"}'
mock.getState.return_value = result_bytes
result = contract_stub.getAsset(asset_id)
# 检查返回结果是否正确
assert result is not None
assert result.status == HTTPStatusCodes.OK
assert result.body == decode_response(result_bytes)
```
5. 模拟交易调用
以调用transferAsset函数为例:
```python
# 构造函数参数
args = ["1", "李四"]
# 模拟查询调用
transaction_id = "123456"
response = Response(HTTPStatusCodes.OK, "Asset transferred successfully")
operation = Operation(transaction_id, response)
mock.invokeChaincode.return_value = (b"", b"", operation)
result = contract_stub.transferAsset(*args)
# 检查返回结果是否正确
assert result is not None
assert result.status == HTTPStatusCodes.OK
assert result.body == response
```
阅读全文