contract TestAdoption { // The address of the adoption contract to be tested Adoption adoption = Adoption(DeployedAddresses.Adoption());
// The id of the pet that will be used for testing uint expectedPetId = 8;
//The expected owner of adopted pet is this contract address expectedAdopter = address(this);
// Testing the adopt() function function testUserCanAdoptPet() public { uint returnedId = adoption.adopt(expectedPetId); Assert.equal( returnedId, expectedPetId, "Adoption of the expected pet should match what is returned." ); }
// Testing retrieval of a single pet's owner function testGetAdopterAddressByPetId() public { address adopter = adoption.adopters(expectedPetId);
Assert.equal( adopter, expectedAdopter, "Owner of the expected pet should be this contract" ); }
// Testing retrieval of all pet owners function testGetAdopterAddressByPetIdInArray() public { // Store adopters in memory rather than contract's storage address[16] memory adopters = adoption.getAdopters();
Assert.equal( adopters[expectedPetId], expectedAdopter, "Owner of the expected pet should be this contract" ); } }
init: asyncfunction () { // 加载前端视图需要展示的16个模拟宠物数据 $.getJSON('../pets.json', function (data) { var petsRow = $('#petsRow'); var petTemplate = $('#petTemplate');
for (i = 0; i < data.length; i++) { petTemplate.find('.panel-title').text(data[i].name); petTemplate.find('img').attr('src', data[i].picture); petTemplate.find('.pet-breed').text(data[i].breed); petTemplate.find('.pet-age').text(data[i].age); petTemplate.find('.pet-location').text(data[i].location); petTemplate.find('.btn-adopt').attr('data-id', data[i].id);
petsRow.append(petTemplate.html()); } });
returnawaitApp.initWeb3(); },
initWeb3: asyncfunction () { // 该方式是web3.js中用于创建区块链连接的 // 版本较新的现代浏览器,这个条件分支会调用MetaMask插件 if (window.ethereum) { App.web3Provider = window.ethereum; try { // Request account access awaitwindow.ethereum.enable(); } catch (error) { // User denied account access... console.error("User denied account access") } } // 废弃的旧时代浏览器,没测试 elseif (window.web3) { App.web3Provider = window.web3.currentProvider; } // If no injected web3 instance is detected, fall back to Ganache // 如果没有检测到MetaMask插件注入的实例,就会通过http协议与区块链通信,但是官方不建议: // If no injected web3 instance is present, we create our web3 object based on our local provider. (This fallback is fine for development environments, but insecure and not suitable for production.) else { App.web3Provider = newWeb3.providers.HttpProvider('http://10.10.5.197:7545'); } web3 = newWeb3(App.web3Provider);
returnApp.initContract(); },
initContract: function () { //Adoption.json文件是通过执行truffle compile编译完得到的编译产物 //该文件通常包含以下几个重要部分: //合约 ABI (Application Binary Interface):ABI 是一个 JSON 数组,描述了合约的函数、事件和状态变量。它定义了与合约交互所需的信息,包括每个函数的名称、输入参数类型、输出参数类型等。通过 ABI,前端应用或其他合约可以调用这个合约的函数。 //合约字节码 (Bytecode):这是合约的编译结果,以字节形式表示。它是部署到以太坊区块链上的代码。 //合约地址、编译版本、网络信息、合约名称 $.getJSON('Adoption.json', function (data) {