Skip to content

Commit

Permalink
Test storing custom types (#112)
Browse files Browse the repository at this point in the history
* feat: Tests for storing_custom_types

* nit

* fix: using embed_v0

* fix: StoringCustomTypes tests

* nit: removing the get_person method

---------

Co-authored-by: julio4 <jules.doumeche@gmail.com>
  • Loading branch information
julienbrs and julio4 authored Nov 16, 2023
1 parent 25e9345 commit ea2ba4e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
#[starknet::interface]
trait IStoringCustomType<TContractState> {
fn set_person(ref self: TContractState, person: Person);
}

// Deriving the starknet::Store trait
// allows us to store the `Person` struct in the contract's storage.
#[derive(Drop, Serde, Copy, starknet::Store)]
struct Person {
age: u8,
name: felt252
}

#[starknet::contract]
mod StoringCustomType {
use super::Person;

#[storage]
struct Storage {
person: Person
}

// Deriving the starknet::Store trait
// allows us to store the `Person` struct in the contract's storage.
#[derive(Drop, starknet::Store)]
struct Person {
age: u8,
name: felt252
}

#[abi(per_item)]
#[generate_trait]
impl StoringCustomType of IStoringCustomType {
#[external(v0)]
fn set_person(ref self: ContractState) {
self.person.write(Person { age: 10, name: 'Joe' });
}

#[external(v0)]
fn get_person(self: @ContractState) {
self.person.read();
#[abi(embed_v0)]
impl StoringCustomType of super::IStoringCustomType<ContractState> {
fn set_person(ref self: ContractState, person: Person) {
self.person.write(person);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,2 +1,32 @@
mod tests { // TODO
// The purpose of these tests is to demonstrate the capability to store custom types in the contract's state.

mod tests {
use storing_custom_types::{
contract::{
IStoringCustomType, StoringCustomType,
StoringCustomType::{Person, person::InternalContractMemberStateTrait}
}
};

use starknet::{ContractAddress, contract_address_const, testing::{set_contract_address}};

fn setup() -> StoringCustomType::ContractState {
let mut state = StoringCustomType::contract_state_for_testing();
let contract_address = contract_address_const::<0x1>();
set_contract_address(contract_address);
state
}

#[test]
#[available_gas(2000000000)]
fn can_call_set_person() {
let mut state = setup();
let person = Person { age: 10, name: 'Joe' };

state.set_person(person);
let read_person = state.person.read();

assert(person.age == read_person.age, 'wrong age');
assert(person.name == read_person.name, 'wrong name');
}
}

0 comments on commit ea2ba4e

Please sign in to comment.