25 minutes
Enhetsprovningsramverk
Learn how to use Matchstick, a unit testing framework developed by LimeChain. Matchstick enables subgraph developers to test their mapping logic in a sandboxed environment and successfully deploy their subgraphs.
Benefits of Using Matchstick
- It’s written in Rust and optimized for high performance.
- It gives you access to developer features, including the ability to mock contract calls, make assertions about the store state, monitor subgraph failures, check test performance, and many more.
Komma igång
Install Dependencies
In order to use the test helper methods and run tests, you need to install the following dependencies:
yarn add --dev matchstick-as
Install PostgreSQL
graph-node
depends on PostgreSQL, so if you don’t already have it, then you will need to install it.
Note: It’s highly recommended to use the commands below to avoid unexpected errors.
Using MacOS
Installation command:
brew install postgresql
Create a symlink to the latest libpq.5.lib You may need to create this dir first /usr/local/opt/postgresql/lib/
ln -sf /usr/local/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib /usr/local/opt/postgresql/lib/libpq.5.dylib
Using Linux
Installation command (depends on your distro):
sudo apt install postgresql
Using WSL (Windows Subsystem for Linux)
Du kan använda Matchstick i WSL både med Docker-metoden och binärmetoden. Eftersom WSL kan vara lite knepigt, här är några tips om du stöter på problem som
static BYTES = Symbol("Bytes") SyntaxError: Unexpected token =
eller
<PROJECT_PATH>/node_modules/gluegun/build/index.js:13 throw up;
Please make sure you’re on a newer version of Node.js graph-cli doesn’t support v10.19.0 anymore, and that is still the default version for new Ubuntu images on WSL. For instance Matchstick is confirmed to be working on WSL with v18.1.0, you can switch to it either via nvm or if you update your global Node.js. Don’t forget to delete node_modules
and to run npm install
again after updating you nodejs! Then, make sure you have libpq installed, you can do that by running
sudo apt-get install libpq-dev
And finally, do not use graph test
(which uses your global installation of graph-cli and for some reason that looks like it’s broken on WSL currently), instead use yarn test
or npm run test
(that will use the local, project-level instance of graph-cli, which works like a charm). For that you would of course need to have a "test"
script in your package.json
file which can be something as simple as
{ "name": "demo-subgraph", "version": "0.1.0", "scripts": { "test": "graph test", ... }, "dependencies": { "@graphprotocol/graph-cli": "^0.56.0", "@graphprotocol/graph-ts": "^0.31.0", "matchstick-as": "^0.6.0" }}
Using Matchstick
To use Matchstick in your subgraph project just open up a terminal, navigate to the root folder of your project and simply run graph test [options] <datasource>
- it downloads the latest Matchstick binary and runs the specified test or all tests in a test folder (or all existing tests if no datasource flag is specified).
CLI alternativ
Detta kommer att köra alla tester i testmappen:
graph test
Detta kommer att köra en test med namnet gravity.test.ts och/eller alla tester inuti en mapp med namnet gravity:
graph test gravity
Då körs endast den specifika testfilen:
graph test path/to/file.test.ts
Options:
-c, --coverage Run the tests in coverage mode-d, --docker Run the tests in a docker container (Note: Please execute from the root folder of the subgraph)-f, --force Binary: Redownloads the binary. Docker: Redownloads the Dockerfile and rebuilds the docker image.-h, --help Show usage information-l, --logs Logs to the console information about the OS, CPU model and download url (debugging purposes)-r, --recompile Forces tests to be recompiled-v, --version <tag> Choose the version of the rust binary that you want to be downloaded/used
Docker
From graph-cli 0.25.2
, the graph test
command supports running matchstick
in a docker container with the -d
flag. The docker implementation uses bind mount so it does not have to rebuild the docker image every time the graph test -d
command is executed. Alternatively you can follow the instructions from the matchstick repository to run docker manually.
❗ graph test -d
forces docker run
to run with flag -t
. This must be removed to run inside non-interactive environments (like GitHub CI).
❗ If you have previously ran graph test
you may encounter the following error during docker build:
error from sender: failed to xattr node_modules/binary-install-raw/bin/binary-<platform>: permission denied
In this case create a .dockerignore
in the root folder and add node_modules/binary-install-raw/bin
Konfiguration
Matchstick can be configured to use a custom tests, libs and manifest path via matchstick.yaml
config file:
testsFolder: path/to/testslibsFolder: path/to/libsmanifestPath: path/to/subgraph.yaml
Demo undergraf
You can try out and play around with the examples from this guide by cloning the Demo Subgraph repo
Handledning för video
Also you can check out the video series on “How to use Matchstick to write unit tests for your subgraphs”
Tests structure
IMPORTANT: The test structure described below depens on matchstick-as
version >=0.5.0
describe()
describe(name: String , () => {})
- Defines a test group.
Notes:
- Describes are not mandatory. You can still use test() the old way, outside of the describe() blocks
Exempel:
import { describe, test } from "matchstick-as/assembly/index"import { handleNewGravatar } from "../../src/gravity"describe("handleNewGravatar()", () => { test("Should create a new Gravatar entity", () => { ... })})
Nested describe()
example:
import { describe, test } from "matchstick-as/assembly/index"import { handleUpdatedGravatar } from "../../src/gravity"describe("handleUpdatedGravatar()", () => { describe("When entity exists", () => { test("updates the entity", () => { ... }) }) describe("When entity does not exists", () => { test("it creates a new entity", () => { ... }) })})
test()
test(name: String, () =>, should_fail: bool)
- Defines a test case. You can use test() inside of describe() blocks or independently.
Exempel:
import { describe, test } from "matchstick-as/assembly/index"import { handleNewGravatar } from "../../src/gravity"describe("handleNewGravatar()", () => { test("Should create a new Entity", () => { ... })})
eller
test("handleNewGravatar() should create a new entity", () => { ...})
beforeAll()
Runs a code block before any of the tests in the file. If beforeAll
is declared inside of a describe
block, it runs at the beginning of that describe
block.
Exempel:
Code inside beforeAll
will execute once before all tests in the file.
import { describe, test, beforeAll } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"import { Gravatar } from "../../generated/schema"beforeAll(() => { let gravatar = new Gravatar("0x0") gravatar.displayName = “First Gravatar” gravatar.save() ...})describe("When the entity does not exist", () => { test("it should create a new Gravatar with id 0x1", () => { ... })})describe("When entity already exists", () => { test("it should update the Gravatar with id 0x0", () => { ... })})
Code inside beforeAll
will execute once before all tests in the first describe block
import { describe, test, beforeAll } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"import { Gravatar } from "../../generated/schema"describe("handleUpdatedGravatar()", () => { beforeAll(() => { let gravatar = new Gravatar("0x0") gravatar.displayName = “First Gravatar” gravatar.save() ... }) test("updates Gravatar with id 0x0", () => { ... }) test("creates new Gravatar with id 0x1", () => { ... })})
afterAll()
Runs a code block after all of the tests in the file. If afterAll
is declared inside of a describe
block, it runs at the end of that describe
block.
Exempel:
Code inside afterAll
will execute once after all tests in the file.
import { describe, test, afterAll } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"import { store } from "@graphprotocol/graph-ts"afterAll(() => { store.remove("Gravatar", "0x0") ...})describe("handleNewGravatar, () => { test("creates Gravatar with id 0x0", () => { ... })})describe("handleUpdatedGravatar", () => { test("updates Gravatar with id 0x0", () => { ... })})
Code inside afterAll
will execute once after all tests in the first describe block
import { describe, test, afterAll, clearStore } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"describe("handleNewGravatar", () => { afterAll(() => { store.remove("Gravatar", "0x1") ... }) test("It creates a new entity with Id 0x0", () => { ... }) test("It creates a new entity with Id 0x1", () => { ... })})describe("handleUpdatedGravatar", () => { test("updates Gravatar with id 0x0", () => { ... })})
beforeEach()
Runs a code block before every test. If beforeEach
is declared inside of a describe
block, it runs before each test in that describe
block.
Examples: Code inside beforeEach
will execute before each tests.
import { describe, test, beforeEach, clearStore } from "matchstick-as/assembly/index"import { handleNewGravatars } from "./utils"beforeEach(() => { clearStore() // <-- clear the store before each test in the file})describe("handleNewGravatars, () => { test("A test that requires a clean store", () => { ... }) test("Second that requires a clean store", () => { ... })}) ...
Code inside beforeEach
will execute only before each test in the that describe
import { describe, test, beforeEach } from 'matchstick-as/assembly/index'import { handleUpdatedGravatar, handleNewGravatar } from '../../src/gravity'describe('handleUpdatedGravatars', () => { beforeEach(() => { let gravatar = new Gravatar('0x0') gravatar.displayName = 'First Gravatar' gravatar.imageUrl = '' gravatar.save() }) test('Updates the displayName', () => { assert.fieldEquals('Gravatar', '0x0', 'displayName', 'First Gravatar') // code that should update the displayName to 1st Gravatar assert.fieldEquals('Gravatar', '0x0', 'displayName', '1st Gravatar') store.remove('Gravatar', '0x0') }) test('Updates the imageUrl', () => { assert.fieldEquals('Gravatar', '0x0', 'imageUrl', '') // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 assert.fieldEquals('Gravatar', '0x0', 'imageUrl', 'https://www.gravatar.com/avatar/0x0') store.remove('Gravatar', '0x0') })})
afterEach()
Runs a code block after every test. If afterEach
is declared inside of a describe
block, it runs after each test in that describe
block.
Exempel:
Code inside afterEach
will execute after every test.
import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"beforeEach(() => { let gravatar = new Gravatar("0x0") gravatar.displayName = “First Gravatar” gravatar.save()})afterEach(() => { store.remove("Gravatar", "0x0")})describe("handleNewGravatar", () => { ...})describe("handleUpdatedGravatar", () => { test("Updates the displayName", () => { assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") // code that should update the displayName to 1st Gravatar assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") }) test("Updates the imageUrl", () => { assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") })})
Code inside afterEach
will execute after each test in that describe
import { describe, test, beforeEach, afterEach } from "matchstick-as/assembly/index"import { handleUpdatedGravatar, handleNewGravatar } from "../../src/gravity"describe("handleNewGravatar", () => { ...})describe("handleUpdatedGravatar", () => { beforeEach(() => { let gravatar = new Gravatar("0x0") gravatar.displayName = "First Gravatar" gravatar.imageUrl = "" gravatar.save() }) afterEach(() => { store.remove("Gravatar", "0x0") }) test("Updates the displayName", () => { assert.fieldEquals("Gravatar", "0x0", "displayName", "First Gravatar") // code that should update the displayName to 1st Gravatar assert.fieldEquals("Gravatar", "0x0", "displayName", "1st Gravatar") }) test("Updates the imageUrl", () => { assert.fieldEquals("Gravatar", "0x0", "imageUrl", "") // code that should changes the imageUrl to https://www.gravatar.com/avatar/0x0 assert.fieldEquals("Gravatar", "0x0", "imageUrl", "https://www.gravatar.com/avatar/0x0") })})
Asserts
fieldEquals(entityType: string, id: string, fieldName: string, expectedVal: string)equals(expected: ethereum.Value, actual: ethereum.Value)notInStore(entityType: string, id: string)addressEquals(address1: Address, address2: Address)bytesEquals(bytes1: Bytes, bytes2: Bytes)i32Equals(number1: i32, number2: i32)bigIntEquals(bigInt1: BigInt, bigInt2: BigInt)booleanEquals(bool1: boolean, bool2: boolean)stringEquals(string1: string, string2: string)arrayEquals(array1: Array<ethereum.Value>, array2: Array<ethereum.Value>)tupleEquals(tuple1: ethereum.Tuple, tuple2: ethereum.Tuple)assertTrue(value: boolean)assertNull<T>(value: T)assertNotNull<T>(value: T)entityCount(entityType: string, expectedCount: i32)
As of version 0.6.0, asserts support custom error messages as well
assert.fieldEquals('Gravatar', '0x123', 'id', '0x123', 'Id should be 0x123')assert.equals(ethereum.Value.fromI32(1), ethereum.Value.fromI32(1), 'Value should equal 1')assert.notInStore('Gravatar', '0x124', 'Gravatar should not be in store')assert.addressEquals(Address.zero(), Address.zero(), 'Address should be zero')assert.bytesEquals(Bytes.fromUTF8('0x123'), Bytes.fromUTF8('0x123'), 'Bytes should be equal')assert.i32Equals(2, 2, 'I32 should equal 2')assert.bigIntEquals(BigInt.fromI32(1), BigInt.fromI32(1), 'BigInt should equal 1')assert.booleanEquals(true, true, 'Boolean should be true')assert.stringEquals('1', '1', 'String should equal 1')assert.arrayEquals([ethereum.Value.fromI32(1)], [ethereum.Value.fromI32(1)], 'Arrays should be equal')assert.tupleEquals( changetype<ethereum.Tuple>([ethereum.Value.fromI32(1)]), changetype<ethereum.Tuple>([ethereum.Value.fromI32(1)]), 'Tuples should be equal',)assert.assertTrue(true, 'Should be true')assert.assertNull(null, 'Should be null')assert.assertNotNull('not null', 'Should be not null')assert.entityCount('Gravatar', 1, 'There should be 2 gravatars')assert.dataSourceCount('GraphTokenLockWallet', 1, 'GraphTokenLockWallet template should have one data source')assert.dataSourceExists( 'GraphTokenLockWallet', Address.zero().toHexString(), 'GraphTokenLockWallet should have a data source for zero address',)
Skriv en enhetstest
Let’s see how a simple unit test would look like using the Gravatar examples in the Demo Subgraph.
Antag att vi har följande hanteringsfunktion (tillsammans med två hjälpfunktioner för att göra vårt liv enklare):
export function handleNewGravatar(event: NewGravatar): void { let gravatar = new Gravatar(event.params.id.toHex()) gravatar.owner = event.params.owner gravatar.displayName = event.params.displayName gravatar.imageUrl = event.params.imageUrl gravatar.save()}export function handleNewGravatars(events: NewGravatar[]): void { events.forEach((event) => { handleNewGravatar(event) })}export function createNewGravatarEvent( id: i32, ownerAddress: string, displayName: string, imageUrl: string,): NewGravatar { let mockEvent = newMockEvent() let newGravatarEvent = new NewGravatar( mockEvent.address, mockEvent.logIndex, mockEvent.transactionLogIndex, mockEvent.logType, mockEvent.block, mockEvent.transaction, mockEvent.parameters, ) newGravatarEvent.parameters = new Array() let idParam = new ethereum.EventParam('id', ethereum.Value.fromI32(id)) let addressParam = new ethereum.EventParam( 'ownerAddress', ethereum.Value.fromAddress(Address.fromString(ownerAddress)), ) let displayNameParam = new ethereum.EventParam('displayName', ethereum.Value.fromString(displayName)) let imageUrlParam = new ethereum.EventParam('imageUrl', ethereum.Value.fromString(imageUrl)) newGravatarEvent.parameters.push(idParam) newGravatarEvent.parameters.push(addressParam) newGravatarEvent.parameters.push(displayNameParam) newGravatarEvent.parameters.push(imageUrlParam) return newGravatarEvent}
Vi måste först skapa en testfil i vårt projekt. Det här är ett exempel på hur det kan se ut:
import { clearStore, test, assert } from 'matchstick-as/assembly/index'import { Gravatar } from '../../generated/schema'import { NewGravatar } from '../../generated/Gravity/Gravity'import { createNewGravatarEvent, handleNewGravatars } from '../mappings/gravity'test('Can call mappings with custom events', () => { // Create a test entity and save it in the store as initial state (optional) let gravatar = new Gravatar('gravatarId0') gravatar.save() // Create mock events let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') let anotherGravatarEvent = createNewGravatarEvent(3546, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac') // Call mapping functions passing the events we just created handleNewGravatars([newGravatarEvent, anotherGravatarEvent]) // Assert the state of the store assert.fieldEquals('Gravatar', 'gravatarId0', 'id', 'gravatarId0') assert.fieldEquals('Gravatar', '12345', 'owner', '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7') assert.fieldEquals('Gravatar', '3546', 'displayName', 'cap') // Clear the store in order to start the next test off on a clean slate clearStore()})test('Next test', () => { //...})
That’s a lot to unpack! First off, an important thing to notice is that we’re importing things from matchstick-as
, our AssemblyScript helper library (distributed as an npm module). You can find the repository here. matchstick-as
provides us with useful testing methods and also defines the test()
function which we will use to build our test blocks. The rest of it is pretty straightforward - here’s what happens:
- Vi ställer in vår inledande status och lägger till en anpassad Gravatar-entitet;
- We define two
NewGravatar
event objects along with their data, using thecreateNewGravatarEvent()
function; - We’re calling out handler methods for those events -
handleNewGravatars()
and passing in the list of our custom events; - Vi försäkrar oss om statusen för lagringen. Hur fungerar det? - Vi skickar en unik kombination av entitetstyp och id. Sedan kontrollerar vi ett specifikt fält på den entiteten och försäkrar oss om att det har det värde vi förväntar oss. Vi gör detta både för den ursprungliga Gravatar-entiteten vi lade till i lagringen och de två Gravatar-entiteterna som läggs till när hanteringsfunktionen anropas;
- And lastly - we’re cleaning the store using
clearStore()
so that our next test can start with a fresh and empty store object. We can define as many test blocks as we want.
Så där har vi skapat vårt första test! 👏
För att köra våra tester behöver du helt enkelt köra följande i din subgrafs rotmapp:
graph test Gravity
Och om allt går bra bör du hälsas av följande:

Vanliga testscenarier
Fylla på lagringen med en viss status
Användare kan fylla på lagringen med en känd uppsättning entiteter. Här är ett exempel på att initialisera lagringen med en Gravatar-entitet:
let gravatar = new Gravatar('entryId')gravatar.save()
Anropa en mappnings funktion med en händelse
En användare kan skapa en anpassad händelse och skicka den till en mappningsfunktion som är bunden till butiken:
import { store } from 'matchstick-as/assembly/store'import { NewGravatar } from '../../generated/Gravity/Gravity'import { handleNewGravatars, createNewGravatarEvent } from './mapping'let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac')handleNewGravatar(newGravatarEvent)
Anropar alla mappningar med händelsefixturer
Användare kan kalla mappningarna med testfixturer.
import { NewGravatar } from '../../generated/Gravity/Gravity'import { store } from 'matchstick-as/assembly/store'import { handleNewGravatars, createNewGravatarEvent } from './mapping'let newGravatarEvent = createNewGravatarEvent(12345, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac')let anotherGravatarEvent = createNewGravatarEvent(3546, '0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7', 'cap', 'pac')handleNewGravatars([newGravatarEvent, anotherGravatarEvent])
export function handleNewGravatars(events: NewGravatar[]): void { events.forEach(event => { handleNewGravatar(event); });}
Mocka kontraktsanrop
Användare kan simulera kontraktssamtal:
import { addMetadata, assert, createMockedFunction, clearStore, test } from 'matchstick-as/assembly/index'import { Gravity } from '../../generated/Gravity/Gravity'import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts'let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7')let expectedResult = Address.fromString('0x90cBa2Bbb19ecc291A12066Fd8329D65FA1f1947')let bigIntParam = BigInt.fromString('1234')createMockedFunction(contractAddress, 'gravatarToOwner', 'gravatarToOwner(uint256):(address)') .withArgs([ethereum.Value.fromSignedBigInt(bigIntParam)]) .returns([ethereum.Value.fromAddress(Address.fromString('0x90cBa2Bbb19ecc291A12066Fd8329D65FA1f1947'))])let gravity = Gravity.bind(contractAddress)let result = gravity.gravatarToOwner(bigIntParam)assert.equals(ethereum.Value.fromAddress(expectedResult), ethereum.Value.fromAddress(result))
För att kunna simulera ett kontraktsanrop och ett hardcore returvärde måste användaren tillhandahålla en kontraktsadress, funktionsnamn, funktionssignatur, en uppsättning argument och naturligtvis - returvärdet.
Användare kan också simulera funktionsåtergångar:
let contractAddress = Address.fromString('0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7')createMockedFunction(contractAddress, 'getGravatar', 'getGravatar(address):(string,string)') .withArgs([ethereum.Value.fromAddress(contractAddress)]) .reverts()
Simulering av IPFS-filer (från matchstick 0.4.1)
Users can mock IPFS files by using mockIpfsFile(hash, filePath)
function. The function accepts two arguments, the first one is the IPFS file hash/path and the second one is the path to a local file.
NOTE: When testing ipfs.map/ipfs.mapJSON
, the callback function must be exported from the test file in order for matchstck to detect it, like the processGravatar()
function in the test example bellow:
.test.ts
file:
import { assert, test, mockIpfsFile } from 'matchstick-as/assembly/index'import { ipfs } from '@graphprotocol/graph-ts'import { gravatarFromIpfs } from './utils'// Export ipfs.map() callback in order for matchstck to detect itexport { processGravatar } from './utils'test('ipfs.cat', () => { mockIpfsFile('ipfsCatfileHash', 'tests/ipfs/cat.json') assert.entityCount(GRAVATAR_ENTITY_TYPE, 0) gravatarFromIpfs() assert.entityCount(GRAVATAR_ENTITY_TYPE, 1) assert.fieldEquals(GRAVATAR_ENTITY_TYPE, '1', 'imageUrl', 'https://i.ytimg.com/vi/MELP46s8Cic/maxresdefault.jpg') clearStore()})test('ipfs.map', () => { mockIpfsFile('ipfsMapfileHash', 'tests/ipfs/map.json') assert.entityCount(GRAVATAR_ENTITY_TYPE, 0) ipfs.map('ipfsMapfileHash', 'processGravatar', Value.fromString('Gravatar'), ['json']) assert.entityCount(GRAVATAR_ENTITY_TYPE, 3) assert.fieldEquals(GRAVATAR_ENTITY_TYPE, '1', 'displayName', 'Gravatar1') assert.fieldEquals(GRAVATAR_ENTITY_TYPE, '2', 'displayName', 'Gravatar2') assert.fieldEquals(GRAVATAR_ENTITY_TYPE, '3', 'displayName', 'Gravatar3')})
utils.ts
file:
import { Address, ethereum, JSONValue, Value, ipfs, json, Bytes } from "@graphprotocol/graph-ts"import { Gravatar } from "../../generated/schema"...// ipfs.map callbackexport function processGravatar(value: JSONValue, userData: Value): void { // Se JSONValue-dokumentationen för mer information om hur man hanterar // med JSON-värden let obj = value.toObject() let id = obj.get('id') if (!id) { return } // Callbacks kan också skapa enheter let gravatar = new Gravatar(id.toString()) gravatar.displayName = userData.toString() + id.toString() gravatar.save()}// funktion som anropar ipfs.catexport function gravatarFromIpfs(): void { let rawData = ipfs.cat("ipfsCatfileHash") if (!rawData) { return } let jsonData = json.fromBytes(rawData as Bytes).toObject() let id = jsonData.get('id') let url = jsonData.get("imageUrl") if (!id || !url) { return } let gravatar = new Gravatar(id.toString()) gravatar.imageUrl = url.toString() gravatar.save()}
Kontrollera tillståndet för lagret
Användare kan kontrollera det slutgiltiga (eller delvisa) tillståndet för lagret genom att verifiera enheter. För att göra detta måste användaren ange en enhetstyp, den specifika ID: n för en enhet, namnet på ett fält på den enheten och det förväntade värdet på fältet. Här är ett snabbt exempel:
import { assert } from 'matchstick-as/assembly/index'import { Gravatar } from '../generated/schema'let gravatar = new Gravatar('gravatarId0')gravatar.save()assert.fieldEquals('Gravatar', 'gravatarId0', 'id', 'gravatarId0')
Running the assert.fieldEquals() function will check for equality of the given field against the given expected value. The test will fail and an error message will be outputted if the values are NOT equal. Otherwise the test will pass successfully.
Interagera med händelsemetadata
Users can use default transaction metadata, which could be returned as an ethereum.Event by using the newMockEvent()
function. The following example shows how you can read/write to those fields on the Event object:
// Läslet logType = newGravatarEvent.logType// Skrivlet UPDATED_ADDRESS = '0xB16081F360e3847006dB660bae1c6d1b2e17eC2A'newGravatarEvent.address = Address.fromString(UPDATED_ADDRESS)
Påstående om variabelns likhet
assert.equals(ethereum.Value.fromString("hello"); ethereum.Value.fromString("hello"));
Asserting that an Entity is not in the store
Användare kan hävda att en entitet inte finns i butiken. Funktionen tar en entitetstyp och ett id. Om entiteten faktiskt finns i butiken kommer testet att misslyckas med ett relevant felmeddelande. Här är ett snabbt exempel på hur du använder den här funktionen:
assert.notInStore('Gravatar', '23')
Printing the whole store, or single entities from it (for debug purposes)
Du kan skriva ut hela lagret till konsolen med hjälp av denna hjälpfunktion:
import { logStore } from 'matchstick-as/assembly/store'logStore()
As of version 0.6.0, logStore
no longer prints derived fields, instead users can use the new logEntity
function. Of course logEntity
can be used to print any entity, not just ones that have derived fields. logEntity
takes the entity type, entity id and a showRelated
flag to indicate if users want to print the related derived entities.
import { logEntity } from 'matchstick-as/assembly/store'logEntity("Gravatar", 23, true)
Förväntat misslyckande
Användare kan ha förväntade testfel genom att använda flaggan shouldFail på test()-funktionerna:
test( 'Should throw an error', () => { throw new Error() }, true,)
Om testet är markerat med shouldFail = true men INTE misslyckas, kommer det att visas som ett fel i loggarna och testblocket kommer att misslyckas. Om testet är markerat med shouldFail = false (standardtillståndet) kommer testköraren dessutom att krascha.
Loggning
Att ha anpassade loggar i enhetstesterna är exakt samma sak som att logga i mappningarna. Skillnaden är att loggobjektet måste importeras från matchstick-as snarare än graph-ts. Här är ett enkelt exempel med alla icke-kritiska loggtyper:
import { test } from "matchstick-as/assembly/index";import { log } from "matchstick-as/assembly/log";test("Success", () => { log.success("Success!". []);});test("Error", () => { log.error("Error :( ", []);});test("Debug", () => { log.debug("Debugging...", []);});test("Info", () => { log.info("Info!", []);});test("Warning", () => { log.warning("Warning!", []);});
Användare kan också simulera ett kritiskt fel, t.ex:
test('Blow everything up', () => { log.critical('Boom!')})
Loggning av kritiska fel kommer att stoppa utförandet av testerna och orsaka total krasch. Trots allt vill vi säkerställa att din kod inte har kritiska loggar i produktion, och du bör märka det omedelbart om det skulle inträffa.
Testning av härledda fält
Testing derived fields is a feature which allows users to set a field on a certain entity and have another entity be updated automatically if it derives one of its fields from the first entity.
Before version 0.6.0
it was possible to get the derived entities by accessing them as entity fields/properties, like so:
let entity = ExampleEntity.load('id')let derivedEntity = entity.derived_entity
As of version 0.6.0
, this is done by using the loadRelated
function of graph-node, the derived entities can be accessed the same way as in the handlers.
test('Derived fields example test', () => { let mainAccount = GraphAccount.load('12')! assert.assertNull(mainAccount.get('nameSignalTransactions')) assert.assertNull(mainAccount.get('operatorOf')) let operatedAccount = GraphAccount.load('1')! operatedAccount.operators = [mainAccount.id] operatedAccount.save() mockNameSignalTransaction('1234', mainAccount.id) mockNameSignalTransaction('2', mainAccount.id) mainAccount = GraphAccount.load('12')! assert.assertNull(mainAccount.get('nameSignalTransactions')) assert.assertNull(mainAccount.get('operatorOf')) const nameSignalTransactions = mainAccount.nameSignalTransactions.load() const operatorsOfMainAccount = mainAccount.operatorOf.load() assert.i32Equals(2, nameSignalTransactions.length) assert.i32Equals(1, operatorsOfMainAccount.length) assert.stringEquals('1', operatorsOfMainAccount[0].id) mockNameSignalTransaction('2345', mainAccount.id) let nst = NameSignalTransaction.load('1234')! nst.signer = '11' nst.save() store.remove('NameSignalTransaction', '2') mainAccount = GraphAccount.load('12')! assert.i32Equals(1, mainAccount.nameSignalTransactions.load().length)})
Testing loadInBlock
As of version 0.6.0
, users can test loadInBlock
by using the mockInBlockStore
, it allows mocking entities in the block cache.
import { afterAll, beforeAll, describe, mockInBlockStore, test } from 'matchstick-as'import { Gravatar } from '../../generated/schema'describe('loadInBlock', () => { beforeAll(() => { mockInBlockStore('Gravatar', 'gravatarId0', gravatar) }) afterAll(() => { clearInBlockStore() }) test('Can use entity.loadInBlock() to retrieve entity from cache store in the current block', () => { let retrievedGravatar = Gravatar.loadInBlock('gravatarId0') assert.stringEquals('gravatarId0', retrievedGravatar!.get('id')!.toString()) }) test("Returns null when calling entity.loadInBlock() if an entity doesn't exist in the current block", () => { let retrievedGravatar = Gravatar.loadInBlock('IDoNotExist') assert.assertNull(retrievedGravatar) })})
Testning av dynamiska datakällor
Testing dynamic data sources can be be done by mocking the return value of the context()
, address()
and network()
functions of the dataSource namespace. These functions currently return the following: context()
- returns an empty entity (DataSourceContext), address()
- returns 0x0000000000000000000000000000000000000000
, network()
- returns mainnet
. The create(...)
and createWithContext(...)
functions are mocked to do nothing so they don’t need to be called in the tests at all. Changes to the return values can be done through the functions of the dataSourceMock
namespace in matchstick-as
(version 0.3.0+).
Exempel nedan:
Först har vi följande händelsehanterare (som medvetet har ändrats för att visa datasourcemockning):
export function handleApproveTokenDestinations(event: ApproveTokenDestinations): void { let tokenLockWallet = TokenLockWallet.load(dataSource.address().toHexString())! if (dataSource.network() == 'rinkeby') { tokenLockWallet.tokenDestinationsApproved = true } let context = dataSource.context() if (context.get('contextVal')!.toI32() > 0) { tokenLockWallet.setBigInt('tokensReleased', BigInt.fromI32(context.get('contextVal')!.toI32())) } tokenLockWallet.save()}
Och sedan har vi testet som använder en av metoderna i namespace dataSourceMock för att ställa in ett nytt returvärde för alla dataSource-funktioner:
import { assert, test, newMockEvent, dataSourceMock } from 'matchstick-as/assembly/index'import { BigInt, DataSourceContext, Value } from '@graphprotocol/graph-ts'import { handleApproveTokenDestinations } from '../../src/token-lock-wallet'import { ApproveTokenDestinations } from '../../generated/templates/GraphTokenLockWallet/GraphTokenLockWallet'import { TokenLockWallet } from '../../generated/schema'test('Data source simple mocking example', () => { let addressString = '0xA16081F360e3847006dB660bae1c6d1b2e17eC2A' let address = Address.fromString(addressString) let wallet = new TokenLockWallet(address.toHexString()) wallet.save() let context = new DataSourceContext() context.set('contextVal', Value.fromI32(325)) dataSourceMock.setReturnValues(addressString, 'rinkeby', context) let event = changetype<ApproveTokenDestinations>(newMockEvent()) assert.assertTrue(!wallet.tokenDestinationsApproved) handleApproveTokenDestinations(event) wallet = TokenLockWallet.load(address.toHexString())! assert.assertTrue(wallet.tokenDestinationsApproved) assert.bigIntEquals(wallet.tokensReleased, BigInt.fromI32(325)) dataSourceMock.resetValues()})
Observera att dataSourceMock.resetValues() anropas i slutet. Det beror på att värdena kom ihåg när de ändrades och behöver återställas om du vill återgå till standardvärdena.
Testing dynamic data source creation
As of version 0.6.0
, it is possible to test if a new data source has been created from a template. This feature supports both ethereum/contract and file/ipfs templates. There are four functions for this:
assert.dataSourceCount(templateName, expectedCount)
can be used to assert the expected count of data sources from the specified templateassert.dataSourceExists(templateName, address/ipfsHash)
asserts that a data source with the specified identifier (could be a contract address or IPFS file hash) from a specified template was createdlogDataSources(templateName)
prints all data sources from the specified template to the console for debugging purposesreadFile(path)
reads a JSON file that represents an IPFS file and returns the content as Bytes
Testing ethereum/contract
templates
test('ethereum/contract dataSource creation example', () => { // Assert there are no dataSources created from GraphTokenLockWallet template assert.dataSourceCount('GraphTokenLockWallet', 0) // Create a new GraphTokenLockWallet datasource with address 0xA16081F360e3847006dB660bae1c6d1b2e17eC2A GraphTokenLockWallet.create(Address.fromString('0xA16081F360e3847006dB660bae1c6d1b2e17eC2A')) // Assert the dataSource has been created assert.dataSourceCount('GraphTokenLockWallet', 1) // Add a second dataSource with context let context = new DataSourceContext() context.set('contextVal', Value.fromI32(325)) GraphTokenLockWallet.createWithContext(Address.fromString('0xA16081F360e3847006dB660bae1c6d1b2e17eC2B'), context) // Assert there are now 2 dataSources assert.dataSourceCount('GraphTokenLockWallet', 2) // Assert that a dataSource with address "0xA16081F360e3847006dB660bae1c6d1b2e17eC2B" was created // Keep in mind that `Address` type is transformed to lower case when decoded, so you have to pass the address as all lower case when asserting if it exists assert.dataSourceExists('GraphTokenLockWallet', '0xA16081F360e3847006dB660bae1c6d1b2e17eC2B'.toLowerCase()) logDataSources('GraphTokenLockWallet')})
Example logDataSource
output
🛠 { "0xa16081f360e3847006db660bae1c6d1b2e17ec2a": { "kind": "ethereum/contract", "name": "GraphTokenLockWallet", "address": "0xa16081f360e3847006db660bae1c6d1b2e17ec2a", "context": null }, "0xa16081f360e3847006db660bae1c6d1b2e17ec2b": { "kind": "ethereum/contract", "name": "GraphTokenLockWallet", "address": "0xa16081f360e3847006db660bae1c6d1b2e17ec2b", "context": { "contextVal": { "type": "Int", "data": 325 } } }}
Testing file/ipfs
templates
Similarly to contract dynamic data sources, users can test test file data sources and their handlers
Example subgraph.yaml
...templates: - kind: file/ipfs name: GraphTokenLockMetadata network: mainnet mapping: kind: ethereum/events apiVersion: 0.0.6 language: wasm/assemblyscript file: ./src/token-lock-wallet.ts handler: handleMetadata entities: - TokenLockMetadata abis: - name: GraphTokenLockWallet file: ./abis/GraphTokenLockWallet.json
Example schema.graphql
"""Token Lock Wallets which hold locked GRT"""type TokenLockMetadata @entity { "The address of the token lock wallet" id: ID! "Start time of the release schedule" startTime: BigInt! "End time of the release schedule" endTime: BigInt! "Number of periods between start time and end time" periods: BigInt! "Time when the releases start" releaseStartTime: BigInt!}
Example metadata.json
{ "startTime": 1, "endTime": 1, "periods": 1, "releaseStartTime": 1}
Example handler
export function handleMetadata(content: Bytes): void { // dataSource.stringParams() returns the File DataSource CID // stringParam() will be mocked in the handler test // for more info https://thegraph.com/docs/en/developing/creating-a-subgraph/#create-a-new-handler-to-process-files let tokenMetadata = new TokenLockMetadata(dataSource.stringParam()) const value = json.fromBytes(content).toObject() if (value) { const startTime = value.get('startTime') const endTime = value.get('endTime') const periods = value.get('periods') const releaseStartTime = value.get('releaseStartTime') if (startTime && endTime && periods && releaseStartTime) { tokenMetadata.startTime = startTime.toBigInt() tokenMetadata.endTime = endTime.toBigInt() tokenMetadata.periods = periods.toBigInt() tokenMetadata.releaseStartTime = releaseStartTime.toBigInt() } tokenMetadata.save() }}
Example test
import { assert, test, dataSourceMock, readFile } from 'matchstick-as'import { Address, BigInt, Bytes, DataSourceContext, ipfs, json, store, Value } from '@graphprotocol/graph-ts'import { handleMetadata } from '../../src/token-lock-wallet'import { TokenLockMetadata } from '../../generated/schema'import { GraphTokenLockMetadata } from '../../generated/templates'test('file/ipfs dataSource creation example', () => { // Generate the dataSource CID from the ipfsHash + ipfs path file // For example QmaXzZhcYnsisuue5WRdQDH6FDvqkLQX1NckLqBYeYYEfm/example.json const ipfshash = 'QmaXzZhcYnsisuue5WRdQDH6FDvqkLQX1NckLqBYeYYEfm' const CID = `${ipfshash}/example.json` // Create a new dataSource using the generated CID GraphTokenLockMetadata.create(CID) // Assert the dataSource has been created assert.dataSourceCount('GraphTokenLockMetadata', 1) assert.dataSourceExists('GraphTokenLockMetadata', CID) logDataSources('GraphTokenLockMetadata') // Now we have to mock the dataSource metadata and specifically dataSource.stringParam() // dataSource.stringParams actually uses the value of dataSource.address(), so we will mock the address using dataSourceMock from matchstick-as // First we will reset the values and then use dataSourceMock.setAddress() to set the CID dataSourceMock.resetValues() dataSourceMock.setAddress(CID) // Now we need to generate the Bytes to pass to the dataSource handler // For this case we introduced a new function readFile, that reads a local json and returns the content as Bytes const content = readFile(`path/to/metadata.json`) handleMetadata(content) // Now we will test if a TokenLockMetadata was created const metadata = TokenLockMetadata.load(CID) assert.bigIntEquals(metadata!.endTime, BigInt.fromI32(1)) assert.bigIntEquals(metadata!.periods, BigInt.fromI32(1)) assert.bigIntEquals(metadata!.releaseStartTime, BigInt.fromI32(1)) assert.bigIntEquals(metadata!.startTime, BigInt.fromI32(1))})
Testtäckning
Using Matchstick, subgraph developers are able to run a script that will calculate the test coverage of the written unit tests.
The test coverage tool takes the compiled test wasm
binaries and converts them to wat
files, which can then be easily inspected to see whether or not the handlers defined in subgraph.yaml
have been called. Since code coverage (and testing as whole) is in very early stages in AssemblyScript and WebAssembly, Matchstick cannot check for branch coverage. Instead we rely on the assertion that if a given handler has been called, the event/function for it have been properly mocked.
Prerequisites
To run the test coverage functionality provided in Matchstick, there are a few things you need to prepare beforehand:
Exportera dina hanterare
In order for Matchstick to check which handlers are being run, those handlers need to be exported from the test file. So for instance in our example, in our gravity.test.ts file we have the following handler being imported:
import { handleNewGravatar } from '../../src/gravity'
In order for that function to be visible (for it to be included in the wat
file by name) we need to also export it, like this:
export { handleNewGravatar }
Usage
När allt är klart kör du bara testtäckningsverktyget:
graph test -- -c
You could also add a custom coverage
command to your package.json
file, like so:
"scripts": { /.../ "coverage": "graph test -- -c" },
Det kommer att köra täckningsverktyget och du bör se något liknande i terminalen:
$ graph test -cSkipping download/install step because binary already exists at /Users/petko/work/demo-subgraph/node_modules/binary-install-raw/bin/0.4.0___ ___ _ _ _ _ _| \/ | | | | | | | (_) | || . . | __ _| |_ ___| |__ ___| |_ _ ___| | __| |\/| |/ _` | __/ __| '_ \/ __| __| |/ __| |/ /| | | | (_| | || (__| | | \__ \ |_| | (__| <\_| |_/\__,_|\__\___|_| |_|___/\__|_|\___|_|\_\Compiling...Running in coverage report mode. ️Reading generated test modules... 🔎️Generating coverage report 📝Handlers for source 'Gravity':Handler 'handleNewGravatar' is tested.Handler 'handleUpdatedGravatar' is not tested.Handler 'handleCreateGravatar' is tested.Test coverage: 66.7% (2/3 handlers).Handlers for source 'GraphTokenLockWallet':Handler 'handleTokensReleased' is not tested.Handler 'handleTokensWithdrawn' is not tested.Handler 'handleTokensRevoked' is not tested.Handler 'handleManagerUpdated' is not tested.Handler 'handleApproveTokenDestinations' is not tested.Handler 'handleRevokeTokenDestinations' is not tested.Test coverage: 0.0% (0/6 handlers).Global test coverage: 22.2% (2/9 handlers).
Testkörningens varaktighet i loggutmatningen
Loggutmatningen innehåller testkörningens varaktighet. Här är ett exempel:
[Thu, 31 Mar 2022 13:54:54 +0300] Program executed in: 42.270ms.
Vanliga kompilatorfel
Critical: Could not create WasmInstance from valid module with context: unknown import: wasi_snapshot_preview1::fd_write has not been defined
This means you have used console.log
in your code, which is not supported by AssemblyScript. Please consider using the Logging API
ERROR TS2554: Expected ? arguments, but got ?.
return new ethereum.Block(defaultAddressBytes, defaultAddressBytes, defaultAddressBytes, defaultAddress, defaultAddressBytes, defaultAddressBytes, defaultAddressBytes, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt, defaultBigInt);
in ~lib/matchstick-as/assembly/defaults.ts(18,12)
ERROR TS2554: Expected ? arguments, but got ?.
return new ethereum.Transaction(defaultAddressBytes, defaultBigInt, defaultAddress, defaultAddress, defaultBigInt, defaultBigInt, defaultBigInt, defaultAddressBytes, defaultBigInt);
in ~lib/matchstick-as/assembly/defaults.ts(24,12)
The mismatch in arguments is caused by mismatch in graph-ts
and matchstick-as
. The best way to fix issues like this one is to update everything to the latest released version.
Ytterligare resurser
For any additional support, check out this demo subgraph repo using Matchstick.
Respons
Om du har några frågor, feedback, funktionsförfrågningar eller bara vill nå ut, är det bästa stället The Graph Discord där vi har en dedikerad kanal för Matchstick, kallad 🔥| unit-testing.