Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cli: init rust test #2805

Merged
merged 29 commits into from
Feb 14, 2024

Conversation

aoikurokawa
Copy link
Contributor

@aoikurokawa aoikurokawa commented Feb 1, 2024

Problem

close #2680

Summary of Changes

  • Add an option rust-template in anchor init -t command.
  • Add rust test templates.

I am submitting this pull request for review. As I am not entirely confident about my implementation, I would greatly appreciate any advice or suggestions. I am open to feedback and happy to make any necessary adjustments.

Copy link

vercel bot commented Feb 1, 2024

@aoikurokawa is attempting to deploy a commit to the coral-xyz Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Collaborator

@acheroncrypto acheroncrypto left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for starting on this!

I am submitting this pull request for review. As I am not entirely confident about my implementation, I would greatly appreciate any advice or suggestions. I am open to feedback and happy to make any necessary adjustments.

Can we add this as a template instead of a separate flag? It would also be much easier to add it that way since you can just specify all the necessary files in one place similar to

fn create_program_template_multiple(name: &str, program_path: &Path) -> Files {

@aoikurokawa aoikurokawa marked this pull request as ready for review February 4, 2024 01:41
@aoikurokawa
Copy link
Contributor Author

Thank you for the review.
Following your advice, I've added a new option to the --template rust-test.
I welcome any further advice or suggestions you might have.

cli/src/rust_template.rs Outdated Show resolved Hide resolved
cli/src/test_template.rs Outdated Show resolved Hide resolved
Copy link
Collaborator

@acheroncrypto acheroncrypto left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome work, thanks! A few more things and it should be good to merge.

cli/src/rust_template.rs Outdated Show resolved Hide resolved
cli/src/lib.rs Outdated Show resolved Hide resolved
CHANGELOG.md Outdated Show resolved Hide resolved
@aoikurokawa
Copy link
Contributor Author

@acheroncrypto
Thank you for reviewing. I relocated the code associated with testing to pub fn create_test_files function.

Copy link
Collaborator

@acheroncrypto acheroncrypto left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@acheroncrypto acheroncrypto merged commit 8eee184 into coral-xyz:master Feb 14, 2024
48 of 49 checks passed
@esemeniuc
Copy link

esemeniuc commented Oct 7, 2024

For anyone wishing to try this, use

anchor init --test-template rust aaa

Look inside tests/src/test_initialize.rs

You'll see a file with the contents:

use std::str::FromStr;

use anchor_client::{
    solana_sdk::{
        commitment_config::CommitmentConfig, pubkey::Pubkey, signature::read_keypair_file,
    },
    Client, Cluster,
};

#[test]
fn test_initialize() {
    let program_id = "ALBsctEzCR2MuZ65KczywWQYEyhjdbq7B5LnkuYg1sie";
    let anchor_wallet = std::env::var("ANCHOR_WALLET").unwrap();
    let payer = read_keypair_file(&anchor_wallet).unwrap();

    let client = Client::new_with_options(Cluster::Localnet, &payer, CommitmentConfig::confirmed());
    let program_id = Pubkey::from_str(program_id).unwrap();
    let program = client.program(program_id).unwrap();

    let tx = program
        .request()
        .accounts(aaa::accounts::Initialize {})
        .args(aaa::instruction::Initialize {})
        .send()
        .expect("");

    println!("Your transaction signature {}", tx);
}

Then run anchor test

@kodmanyagha
Copy link

Hi, this feature is so good, we want use only rust when developing smart contracts. But this feature isn't well documented. For this reason I want to ask my question in here.

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        payer = signer,
        space = Counter::SPACE
    )]
    pub counter: Account<'info, Counter>,

    #[account(mut)]
    pub signer: Signer<'info>,

    pub system_program: Program<'info, System>,
}

// ....
// test code:

    let tx = program
        .request()
        .accounts(anchor_tutor_1::accounts::Initialize {
            counter: payer.pubkey(),
            signer: payer.pubkey(),
            system_program: system_program::ID,
        })
        .args(anchor_tutor_1::instruction::Initialize {})
        .send()
        .expect("Transaction failed");

This code isn't working. The error message:

thread 'test_initialize::test_initialize' panicked at tests/src/test_initialize.rs:31:10:
Transaction failed: SolanaClientError(Error { request: Some(SendTransaction), kind: RpcError(RpcResponseError { code: -32002, message: "Transaction simulation failed: Error processing Instruction 0: custom program error: 0x1005", data: SendTransactionPreflightFailure(RpcSimulateTransactionResult { err: Some(InstructionError(0, Custom(4101))), logs: Some(["Program 3CobDehW5cufiguMpJD75msFSngrerxat9znyCFUX3gR invoke [1]", "Program log: Instruction: Initialize", "Program log: AnchorError thrown in programs/anchor-tutor-1/src/instructions/initialize.rs:7. Error Code: TryingToInitPayerAsProgramAccount. Error Number: 4101. Error Message: You cannot/should not initialize the payer account as a program account.", "Program log: Left:", "Program log: FRiw3PmZ72ETSsESjUUAEhi93EhQeFfuwZb5zuU5KKJz", "Program log: Right:", "Program log: FRiw3PmZ72ETSsESjUUAEhi93EhQeFfuwZb5zuU5KKJz", "Program 3CobDehW5cufiguMpJD75msFSngrerxat9znyCFUX3gR consumed 4154 of 200000 compute units", "Program 3CobDehW5cufiguMpJD75msFSngrerxat9znyCFUX3gR failed: custom program error: 0x1005"]), accounts: None, units_consumed: Some(4154), return_data: None, inner_instructions: None }) }) })

So how can I sovle this? Thanks.

@aoikurokawa
Copy link
Contributor Author

aoikurokawa commented Nov 6, 2024

I think the account of counter should not be payer.

let counter = Keypair::new();

    let tx = program
        .request()
        .accounts(anchor_tutor_1::accounts::Initialize {
            counter: counter.pubkey(),
            signer: payer.pubkey(),
            system_program: system_program::ID,
        })
        .args(anchor_tutor_1::instruction::Initialize {})
        .send()
        .expect("Transaction failed");

@aoikurokawa aoikurokawa deleted the feature/rust-boilerplate branch November 6, 2024 23:20
@kodmanyagha
Copy link

@aoikurokawa thanks for your response. I searched in google but I didn't find information about writing tests inside of rust. Do you have any suggestion about documentation, example code etc? Thanks.

@aoikurokawa
Copy link
Contributor Author

@kevinrodriguez-io
I think you can refer solana program library code.
https://github.com/solana-labs/solana-program-library/blob/master/stake-pool/program/tests/initialize.rs

Most test codes are written in Rust. So I think you can take some hints from it.

@kevinrodriguez-io
Copy link
Contributor

@kevinrodriguez-io

I think you can refer solana program library code.

https://github.com/solana-labs/solana-program-library/blob/master/stake-pool/program/tests/initialize.rs

Most test codes are written in Rust. So I think you can take some hints from it.

OwO ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Rust Boilerplate
5 participants