根据Pact-Python 中的文档,您实际完成此操作的方式有点开放。就个人而言,我会怎么做,因为我通常不使用 Python 的节点提供程序在我的提供程序测试中,我会在未使用的端口上创建一个服务器,其目的是从协议接收状态并设置它们适当地。一旦你运行测试,这个小型服务器就会受到包含消费者、提供者和状态的 JSON 文件的影响。
例如,这是一个节点示例:
var http = require('http');
beforeAll(function(){
// PROVIDER STATE LISTENER
http.createServer(function (req, res) {
var body = [];
// Ignore this bit, this is just how node does server request/response
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// Get body, parse JSON. JSON includes 'consumer' string and 'states' array of string
var json = JSON.parse(Buffer.concat(body).toString());
// THIS IS WHERE YOU NEED TO SETUP YOUR STATE
res.status = 200;
switch(json.state) {
case "When User does something": // this is the actual name of the state that's specified by your consumer, which is found in the contract
// Setup any data that relates to your state here, like adding rows to a DB, setting environment variables, etc
break;
// Add another states that are used in your provider tests
default:
res.status = 500;
res.statusMessage = "Missing state '" + json.state + "'";
}
res.end(); // Send the response back
});
}).listen(9001);
})
// Run your tests
it("Test Pact Interactions", function() {
return pact.verifyPacts({
// options here
providerStatesSetupUrl: "http://localhost:9001"
});
});
我希望这是有道理的。