| 1 | Mark an `async fn` as a test with SQLx support. |
| 2 | |
| 3 | The test will automatically be executed in the async runtime according to the chosen |
| 4 | `runtime-{async-std, tokio}` feature. If more than one runtime feature is enabled, `runtime-tokio` is preferred. |
| 5 | |
| 6 | By default, this behaves identically to `#[tokio::test]`<sup>1</sup> or `#[async_std::test]`: |
| 7 | |
| 8 | ```rust |
| 9 | # // Note if reading these examples directly in `test.md`: |
| 10 | # // lines prefixed with `#` are not meant to be shown; |
| 11 | # // they are supporting code to help the examples to compile successfully. |
| 12 | # #[cfg(feature = "_rt-tokio")] |
| 13 | #[sqlx::test] |
| 14 | async fn test_async_fn() { |
| 15 | tokio::task::yield_now().await; |
| 16 | } |
| 17 | ``` |
| 18 | |
| 19 | However, several advanced features are also supported as shown in the next section. |
| 20 | |
| 21 | <sup>1</sup>`#[sqlx::test]` does not recognize any of the control arguments supported by `#[tokio::test]` |
| 22 | as that would have complicated the implementation. If your use case requires any of those, feel free to open an issue. |
| 23 | |
| 24 | ### Automatic Test Database Management (requires `migrate` feature) |
| 25 | |
| 26 | `#[sqlx::test]` can automatically create test databases for you and provide live connections to your test. |
| 27 | |
| 28 | For every annotated function, a new test database is created so tests can run against a live database |
| 29 | but are isolated from each other. |
| 30 | |
| 31 | This feature is activated by changing the signature of your test function. The following signatures are supported: |
| 32 | |
| 33 | * `async fn(Pool<DB>) -> Ret` |
| 34 | * the `Pool`s used by all running tests share a single connection limit to avoid exceeding the server's limit. |
| 35 | * `async fn(PoolConnection<DB>) -> Ret` |
| 36 | * `PoolConnection<Postgres>`, etc. |
| 37 | * `async fn(PoolOptions<DB>, impl ConnectOptions<DB>) -> Ret` |
| 38 | * Where `impl ConnectOptions` is, e.g, `PgConnectOptions`, `MySqlConnectOptions`, etc. |
| 39 | * If your test wants to create its own `Pool` (for example, to set pool callbacks or to modify `ConnectOptions`), |
| 40 | you can use this signature. |
| 41 | |
| 42 | Where `DB` is a supported `Database` type and `Ret` is `()` or `Result<_, _>`. |
| 43 | |
| 44 | ##### Supported Databases |
| 45 | |
| 46 | Most of these will require you to set `DATABASE_URL` as an environment variable |
| 47 | or in a `.env` file like `sqlx::query!()` _et al_, to give the test driver a superuser connection with which |
| 48 | to manage test databases. |
| 49 | |
| 50 | |
| 51 | | Database | Requires `DATABASE_URL` | |
| 52 | | --- | --- | |
| 53 | | Postgres | Yes | |
| 54 | | MySQL | Yes | |
| 55 | | SQLite | No<sup>2</sup> | |
| 56 | |
| 57 | Test databases are automatically cleaned up as tests succeed, but failed tests will leave their databases in-place |
| 58 | to facilitate debugging. Note that to simplify the implementation, panics are _always_ considered to be failures, |
| 59 | even for `#[should_panic]` tests. |
| 60 | |
| 61 | To limit disk space usage, any previously created test databases will be deleted the next time a test binary using |
| 62 | `#[sqlx::test]` is run. |
| 63 | |
| 64 | ```rust,no_run |
| 65 | # #[cfg(all(feature = "migrate", feature = "postgres"))] |
| 66 | # mod example { |
| 67 | use sqlx::{PgPool, Row}; |
| 68 | |
| 69 | #[sqlx::test] |
| 70 | async fn basic_test(pool: PgPool) -> sqlx::Result<()> { |
| 71 | let mut conn = pool.acquire().await?; |
| 72 | |
| 73 | let foo = sqlx::query("SELECT * FROM foo") |
| 74 | .fetch_one(&mut conn) |
| 75 | .await?; |
| 76 | |
| 77 | assert_eq!(foo.get::<String, _>("bar"), "foobar!"); |
| 78 | |
| 79 | Ok(()) |
| 80 | } |
| 81 | # } |
| 82 | ``` |
| 83 | |
| 84 | <sup>2</sup> SQLite defaults to `target/sqlx/test-dbs/<path>.sqlite` where `<path>` is the path of the test function |
| 85 | converted to a filesystem path (`::` replaced with `/`). |
| 86 | |
| 87 | ### Automatic Migrations (requires `migrate` feature) |
| 88 | |
| 89 | To ensure a straightforward test implementation against a fresh test database, migrations are automatically applied if a |
| 90 | `migrations` folder is found in the same directory as `CARGO_MANIFEST_DIR` (the directory where the current crate's |
| 91 | `Cargo.toml` resides). |
| 92 | |
| 93 | You can override the resolved path relative to `CARGO_MANIFEST_DIR` in the attribute (global overrides are not currently |
| 94 | supported): |
| 95 | |
| 96 | ```rust,ignore |
| 97 | # #[cfg(all(feature = "migrate", feature = "postgres"))] |
| 98 | # mod example { |
| 99 | use sqlx::{PgPool, Row}; |
| 100 | |
| 101 | #[sqlx::test(migrations = "foo_migrations")] |
| 102 | async fn basic_test(pool: PgPool) -> sqlx::Result<()> { |
| 103 | let mut conn = pool.acquire().await?; |
| 104 | |
| 105 | let foo = sqlx::query("SELECT * FROM foo") |
| 106 | .fetch_one(&mut conn) |
| 107 | .await?; |
| 108 | |
| 109 | assert_eq!(foo.get::<String, _>("bar"), "foobar!"); |
| 110 | |
| 111 | Ok(()) |
| 112 | } |
| 113 | # } |
| 114 | ``` |
| 115 | |
| 116 | Or if you're already embedding migrations in your main crate, you can reference them directly: |
| 117 | |
| 118 | `foo_crate/lib.rs` |
| 119 | ```rust,ignore |
| 120 | pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("foo_migrations"); |
| 121 | ``` |
| 122 | |
| 123 | `foo_crate/tests/foo_test.rs` |
| 124 | ```rust,no_run |
| 125 | # #[cfg(all(feature = "migrate", feature = "postgres"))] |
| 126 | # mod example { |
| 127 | use sqlx::{PgPool, Row}; |
| 128 | |
| 129 | # // This is standing in for the main crate since doc examples don't support multiple crates. |
| 130 | # mod foo_crate { |
| 131 | # use std::borrow::Cow; |
| 132 | # static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate::Migrator { |
| 133 | # migrations: Cow::Borrowed(&[]), |
| 134 | # ignore_missing: false, |
| 135 | # locking: true, |
| 136 | # no_tx: false |
| 137 | # }; |
| 138 | # } |
| 139 | |
| 140 | // You could also do `use foo_crate::MIGRATOR` and just refer to it as `MIGRATOR` here. |
| 141 | #[sqlx::test(migrator = "foo_crate::MIGRATOR")] |
| 142 | async fn basic_test(pool: PgPool) -> sqlx::Result<()> { |
| 143 | let mut conn = pool.acquire().await?; |
| 144 | |
| 145 | let foo = sqlx::query("SELECT * FROM foo") |
| 146 | .fetch_one(&mut conn) |
| 147 | .await?; |
| 148 | |
| 149 | assert_eq!(foo.get::<String, _>("bar"), "foobar!"); |
| 150 | |
| 151 | Ok(()) |
| 152 | } |
| 153 | # } |
| 154 | ``` |
| 155 | |
| 156 | Or disable migrations processing entirely: |
| 157 | |
| 158 | ```rust,no_run |
| 159 | # #[cfg(all(feature = "migrate", feature = "postgres"))] |
| 160 | # mod example { |
| 161 | use sqlx::{PgPool, Row}; |
| 162 | |
| 163 | #[sqlx::test(migrations = false)] |
| 164 | async fn basic_test(pool: PgPool) -> sqlx::Result<()> { |
| 165 | let mut conn = pool.acquire().await?; |
| 166 | |
| 167 | conn.execute("CREATE TABLE foo(bar text)").await?; |
| 168 | |
| 169 | let foo = sqlx::query("SELECT * FROM foo") |
| 170 | .fetch_one(&mut conn) |
| 171 | .await?; |
| 172 | |
| 173 | assert_eq!(foo.get::<String, _>("bar"), "foobar!"); |
| 174 | |
| 175 | Ok(()) |
| 176 | } |
| 177 | # } |
| 178 | ``` |
| 179 | |
| 180 | ### Automatic Fixture Application (requires `migrate` feature) |
| 181 | |
| 182 | Since tests are isolated from each other but may require data to already exist in the database to keep from growing |
| 183 | exponentially in complexity, `#[sqlx::test]` also supports applying test fixtures, which are SQL scripts that function |
| 184 | similarly to migrations but are solely intended to insert test data and be arbitrarily composable. |
| 185 | |
| 186 | Imagine a basic social app that has users, posts and comments. To test the comment routes, you'd want |
| 187 | the database to already have users and posts in it so the comments tests don't have to duplicate that work. |
| 188 | |
| 189 | You can either pass a list of fixture to the attribute `fixtures` in three different operating modes: |
| 190 | |
| 191 | 1) Pass a list of references files in `./fixtures` (resolved as `./fixtures/{name}.sql`, `.sql` added only if extension is missing); |
| 192 | 2) Pass a list of file paths (including associated extension), in which case they can either be absolute, or relative to the current file; |
| 193 | 3) Pass a `path = <path to folder>` parameter and a `scripts(<filename_1>, <filename_2>, ...)` parameter that are relative to the provided path (resolved as `{path}/{filename_x}.sql`, `.sql` added only if extension is missing). |
| 194 | |
| 195 | In any case they will be applied in the given order<sup>3</sup>: |
| 196 | |
| 197 | ```rust,no_run |
| 198 | # #[cfg(all(feature = "migrate", feature = "postgres"))] |
| 199 | # mod example { |
| 200 | # struct App {} |
| 201 | # fn create_app(pool: PgPool) -> App { App {} } |
| 202 | use sqlx::PgPool; |
| 203 | use serde_json::json; |
| 204 | |
| 205 | // Alternatives: |
| 206 | // #[sqlx::test(fixtures("./fixtures/users.sql", "./fixtures/posts.sql"))] |
| 207 | // or |
| 208 | // #[sqlx::test(fixtures(path = "./fixtures", scripts("users", "posts")))] |
| 209 | #[sqlx::test(fixtures("users", "posts"))] |
| 210 | async fn test_create_comment(pool: PgPool) -> sqlx::Result<()> { |
| 211 | // See examples/postgres/social-axum-with-tests for a more in-depth example. |
| 212 | let mut app = create_app(pool); |
| 213 | |
| 214 | let comment = test_request( |
| 215 | &mut app, "POST", "/v1/comment", json! { "postId": "1234" } |
| 216 | ).await?; |
| 217 | |
| 218 | assert_eq!(comment["postId"], "1234"); |
| 219 | |
| 220 | Ok(()) |
| 221 | } |
| 222 | # } |
| 223 | ``` |
| 224 | |
| 225 | Multiple `fixtures` attributes can be used to combine different operating modes. |
| 226 | |
| 227 | <sup>3</sup>Ordering for test fixtures is entirely up to the application, and each test may choose which fixtures to |
| 228 | apply and which to omit. However, since each fixture is applied separately (sent as a single command string, so wrapped |
| 229 | in an implicit `BEGIN` and `COMMIT`), you will want to make sure to order the fixtures such that foreign key |
| 230 | requirements are always satisfied, or else you might get errors. |