cache_test.go 1.68 KB
Newer Older
1 2 3 4 5 6 7
package l2

import (
	"math/rand"
	"testing"

	"github.com/ethereum-optimism/optimism/op-node/testutils"
8
	"github.com/ethereum-optimism/optimism/op-program/client/l2/test"
9 10 11 12 13 14 15 16
	"github.com/ethereum/go-ethereum/common"
	"github.com/stretchr/testify/require"
)

// Should be an Oracle implementation
var _ Oracle = (*CachingOracle)(nil)

func TestBlockByHash(t *testing.T) {
17
	stub, _ := test.NewStubOracle(t)
18 19 20 21 22 23
	oracle := NewCachingOracle(stub)

	rng := rand.New(rand.NewSource(1))
	block, _ := testutils.RandomBlock(rng, 1)

	// Initial call retrieves from the stub
24
	stub.Blocks[block.Hash()] = block
25 26 27 28
	actual := oracle.BlockByHash(block.Hash())
	require.Equal(t, block, actual)

	// Later calls should retrieve from cache
29
	delete(stub.Blocks, block.Hash())
30 31 32 33 34
	actual = oracle.BlockByHash(block.Hash())
	require.Equal(t, block, actual)
}

func TestNodeByHash(t *testing.T) {
35
	stub, stateStub := test.NewStubOracle(t)
36 37 38 39 40 41
	oracle := NewCachingOracle(stub)

	node := []byte{12, 3, 4}
	hash := common.Hash{0xaa}

	// Initial call retrieves from the stub
42
	stateStub.Data[hash] = node
43 44 45 46
	actual := oracle.NodeByHash(hash)
	require.Equal(t, node, actual)

	// Later calls should retrieve from cache
47
	delete(stateStub.Data, hash)
48 49 50 51 52
	actual = oracle.NodeByHash(hash)
	require.Equal(t, node, actual)
}

func TestCodeByHash(t *testing.T) {
53
	stub, stateStub := test.NewStubOracle(t)
54 55 56 57 58 59
	oracle := NewCachingOracle(stub)

	node := []byte{12, 3, 4}
	hash := common.Hash{0xaa}

	// Initial call retrieves from the stub
60
	stateStub.Code[hash] = node
61 62 63 64
	actual := oracle.CodeByHash(hash)
	require.Equal(t, node, actual)

	// Later calls should retrieve from cache
65
	delete(stateStub.Code, hash)
66 67 68
	actual = oracle.CodeByHash(hash)
	require.Equal(t, node, actual)
}