|
| 1 | +const { ethers } = require('hardhat'); |
| 2 | +const { expect } = require('chai'); |
| 3 | +const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); |
| 4 | +const { PANIC_CODES } = require('@nomicfoundation/hardhat-chai-matchers/panic'); |
| 5 | + |
| 6 | +const { generators } = require('../../helpers/random'); |
| 7 | + |
| 8 | +const LENGTH = 4; |
| 9 | + |
| 10 | +async function fixture() { |
| 11 | + const mock = await ethers.deployContract('$CircularBuffer'); |
| 12 | + await mock.$setup(0, LENGTH); |
| 13 | + return { mock }; |
| 14 | +} |
| 15 | + |
| 16 | +describe('CircularBuffer', function () { |
| 17 | + beforeEach(async function () { |
| 18 | + Object.assign(this, await loadFixture(fixture)); |
| 19 | + }); |
| 20 | + |
| 21 | + it('starts empty', async function () { |
| 22 | + expect(await this.mock.$count(0)).to.equal(0n); |
| 23 | + expect(await this.mock.$size(0)).to.equal(LENGTH); |
| 24 | + await expect(this.mock.$last(0, 0)).to.be.revertedWithPanic(PANIC_CODES.ARRAY_ACCESS_OUT_OF_BOUNDS); |
| 25 | + }); |
| 26 | + |
| 27 | + it('push', async function () { |
| 28 | + const values = Array.from({ length: LENGTH + 3 }, generators.bytes32); |
| 29 | + |
| 30 | + for (const [i, value] of values.map((v, i) => [i, v])) { |
| 31 | + // push value |
| 32 | + await this.mock.$push(0, value); |
| 33 | + |
| 34 | + // view of the values |
| 35 | + const pushed = values.slice(0, i + 1); |
| 36 | + const stored = pushed.slice(-LENGTH); |
| 37 | + const dropped = pushed.slice(0, -LENGTH); |
| 38 | + |
| 39 | + // check count |
| 40 | + expect(await this.mock.$size(0)).to.equal(LENGTH); |
| 41 | + expect(await this.mock.$count(0)).to.equal(stored.length); |
| 42 | + |
| 43 | + // check last |
| 44 | + for (const i in stored) { |
| 45 | + expect(await this.mock.$last(0, i)).to.equal(stored.at(-i - 1)); |
| 46 | + } |
| 47 | + |
| 48 | + // check included and non-included values |
| 49 | + for (const v of stored) { |
| 50 | + expect(await this.mock.$includes(0, v)).to.be.true; |
| 51 | + } |
| 52 | + for (const v of dropped) { |
| 53 | + expect(await this.mock.$includes(0, v)).to.be.false; |
| 54 | + } |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + it('clear', async function () { |
| 59 | + await this.mock.$push(0, generators.bytes32()); |
| 60 | + |
| 61 | + expect(await this.mock.$count(0)).to.equal(1n); |
| 62 | + expect(await this.mock.$size(0)).to.equal(LENGTH); |
| 63 | + await this.mock.$last(0, 0); // not revert |
| 64 | + |
| 65 | + await this.mock.$clear(0); |
| 66 | + |
| 67 | + expect(await this.mock.$count(0)).to.equal(0n); |
| 68 | + expect(await this.mock.$size(0)).to.equal(LENGTH); |
| 69 | + await expect(this.mock.$last(0, 0)).to.be.revertedWithPanic(PANIC_CODES.ARRAY_ACCESS_OUT_OF_BOUNDS); |
| 70 | + }); |
| 71 | +}); |
0 commit comments