tests.rs

  1mod buffer_tests;
  2mod channel_tests;
  3mod contributor_tests;
  4mod db_tests;
  5mod extension_tests;
  6mod feature_flag_tests;
  7mod message_tests;
  8
  9use super::*;
 10use gpui::BackgroundExecutor;
 11use parking_lot::Mutex;
 12use sea_orm::ConnectionTrait;
 13use sqlx::migrate::MigrateDatabase;
 14use std::sync::{
 15    atomic::{AtomicI32, AtomicU32, Ordering::SeqCst},
 16    Arc,
 17};
 18
 19pub struct TestDb {
 20    pub db: Option<Arc<Database>>,
 21    pub connection: Option<sqlx::AnyConnection>,
 22}
 23
 24impl TestDb {
 25    pub fn sqlite(background: BackgroundExecutor) -> Self {
 26        let url = "sqlite::memory:";
 27        let runtime = tokio::runtime::Builder::new_current_thread()
 28            .enable_io()
 29            .enable_time()
 30            .build()
 31            .unwrap();
 32
 33        let mut db = runtime.block_on(async {
 34            let mut options = ConnectOptions::new(url);
 35            options.max_connections(5);
 36            let mut db = Database::new(options, Executor::Deterministic(background))
 37                .await
 38                .unwrap();
 39            let sql = include_str!(concat!(
 40                env!("CARGO_MANIFEST_DIR"),
 41                "/migrations.sqlite/20221109000000_test_schema.sql"
 42            ));
 43            db.pool
 44                .execute(sea_orm::Statement::from_string(
 45                    db.pool.get_database_backend(),
 46                    sql,
 47                ))
 48                .await
 49                .unwrap();
 50            db.initialize_notification_kinds().await.unwrap();
 51            db
 52        });
 53
 54        db.runtime = Some(runtime);
 55
 56        Self {
 57            db: Some(Arc::new(db)),
 58            connection: None,
 59        }
 60    }
 61
 62    pub fn postgres(background: BackgroundExecutor) -> Self {
 63        static LOCK: Mutex<()> = Mutex::new(());
 64
 65        let _guard = LOCK.lock();
 66        let mut rng = StdRng::from_entropy();
 67        let url = format!(
 68            "postgres://postgres@localhost/zed-test-{}",
 69            rng.gen::<u128>()
 70        );
 71        let runtime = tokio::runtime::Builder::new_current_thread()
 72            .enable_io()
 73            .enable_time()
 74            .build()
 75            .unwrap();
 76
 77        let mut db = runtime.block_on(async {
 78            sqlx::Postgres::create_database(&url)
 79                .await
 80                .expect("failed to create test db");
 81            let mut options = ConnectOptions::new(url);
 82            options
 83                .max_connections(5)
 84                .idle_timeout(Duration::from_secs(0));
 85            let mut db = Database::new(options, Executor::Deterministic(background))
 86                .await
 87                .unwrap();
 88            let migrations_path = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
 89            db.migrate(Path::new(migrations_path), false).await.unwrap();
 90            db.initialize_notification_kinds().await.unwrap();
 91            db
 92        });
 93
 94        db.runtime = Some(runtime);
 95
 96        Self {
 97            db: Some(Arc::new(db)),
 98            connection: None,
 99        }
100    }
101
102    pub fn db(&self) -> &Arc<Database> {
103        self.db.as_ref().unwrap()
104    }
105}
106
107#[macro_export]
108macro_rules! test_both_dbs {
109    ($test_name:ident, $postgres_test_name:ident, $sqlite_test_name:ident) => {
110        #[gpui::test]
111        async fn $postgres_test_name(cx: &mut gpui::TestAppContext) {
112            let test_db = $crate::db::TestDb::postgres(cx.executor().clone());
113            $test_name(test_db.db()).await;
114        }
115
116        #[gpui::test]
117        async fn $sqlite_test_name(cx: &mut gpui::TestAppContext) {
118            let test_db = $crate::db::TestDb::sqlite(cx.executor().clone());
119            $test_name(test_db.db()).await;
120        }
121    };
122}
123
124impl Drop for TestDb {
125    fn drop(&mut self) {
126        let db = self.db.take().unwrap();
127        if let sea_orm::DatabaseBackend::Postgres = db.pool.get_database_backend() {
128            db.runtime.as_ref().unwrap().block_on(async {
129                use util::ResultExt;
130                let query = "
131                        SELECT pg_terminate_backend(pg_stat_activity.pid)
132                        FROM pg_stat_activity
133                        WHERE
134                            pg_stat_activity.datname = current_database() AND
135                            pid <> pg_backend_pid();
136                    ";
137                db.pool
138                    .execute(sea_orm::Statement::from_string(
139                        db.pool.get_database_backend(),
140                        query,
141                    ))
142                    .await
143                    .log_err();
144                sqlx::Postgres::drop_database(db.options.get_url())
145                    .await
146                    .log_err();
147            })
148        }
149    }
150}
151
152fn channel_tree(channels: &[(ChannelId, &[ChannelId], &'static str)]) -> Vec<Channel> {
153    channels
154        .iter()
155        .map(|(id, parent_path, name)| Channel {
156            id: *id,
157            name: name.to_string(),
158            visibility: ChannelVisibility::Members,
159            parent_path: parent_path.to_vec(),
160        })
161        .collect()
162}
163
164static GITHUB_USER_ID: AtomicI32 = AtomicI32::new(5);
165
166async fn new_test_user(db: &Arc<Database>, email: &str) -> UserId {
167    db.create_user(
168        email,
169        false,
170        NewUserParams {
171            github_login: email[0..email.find('@').unwrap()].to_string(),
172            github_user_id: GITHUB_USER_ID.fetch_add(1, SeqCst),
173        },
174    )
175    .await
176    .unwrap()
177    .user_id
178}
179
180static TEST_CONNECTION_ID: AtomicU32 = AtomicU32::new(1);
181fn new_test_connection(server: ServerId) -> ConnectionId {
182    ConnectionId {
183        id: TEST_CONNECTION_ID.fetch_add(1, SeqCst),
184        owner_id: server.0 as u32,
185    }
186}