| 1 | // SPDX-License-Identifier: MIT |
| 2 | pragma solidity >=0.7.0 <0.9.0; |
| 3 | |
| 4 | import {Test, stdJson} from "../src/Test.sol"; |
| 5 | |
| 6 | contract StdJsonTest is Test { |
| 7 | using stdJson for string; |
| 8 | |
| 9 | string root; |
| 10 | string path; |
| 11 | |
| 12 | function setUp() public { |
| 13 | root = vm.projectRoot(); |
| 14 | path = string.concat(root, "/test/fixtures/test.json"); |
| 15 | } |
| 16 | |
| 17 | struct SimpleJson { |
| 18 | uint256 a; |
| 19 | string b; |
| 20 | } |
| 21 | |
| 22 | struct NestedJson { |
| 23 | uint256 a; |
| 24 | string b; |
| 25 | SimpleJson c; |
| 26 | } |
| 27 | |
| 28 | function test_readJson() public view { |
| 29 | string memory json = vm.readFile(path); |
| 30 | assertEq(json.readUint(".a"), 123); |
| 31 | } |
| 32 | |
| 33 | function test_writeJson() public { |
| 34 | string memory json = "json"; |
| 35 | json.serialize("a", uint256(123)); |
| 36 | string memory semiFinal = json.serialize("b", string("test")); |
| 37 | string memory finalJson = json.serialize("c", semiFinal); |
| 38 | finalJson.write(path); |
| 39 | |
| 40 | string memory json_ = vm.readFile(path); |
| 41 | bytes memory data = json_.parseRaw("$"); |
| 42 | NestedJson memory decodedData = abi.decode(data, (NestedJson)); |
| 43 | |
| 44 | assertEq(decodedData.a, 123); |
| 45 | assertEq(decodedData.b, "test"); |
| 46 | assertEq(decodedData.c.a, 123); |
| 47 | assertEq(decodedData.c.b, "test"); |
| 48 | } |
| 49 | } |