db_tests.rs

  1mod buffer_tests;
  2mod channel_tests;
  3mod db_tests;
  4mod extension_tests;
  5mod migrations;
  6
  7use std::sync::Arc;
  8use std::sync::atomic::{AtomicI32, Ordering::SeqCst};
  9use std::time::Duration;
 10
 11use collections::HashSet;
 12use gpui::BackgroundExecutor;
 13use parking_lot::Mutex;
 14use rand::prelude::*;
 15use sea_orm::ConnectionTrait;
 16use sqlx::migrate::MigrateDatabase;
 17
 18use self::migrations::run_database_migrations;
 19
 20use collab::db::*;
 21
 22pub struct TestDb {
 23    pub db: Option<Arc<Database>>,
 24    pub connection: Option<sqlx::AnyConnection>,
 25}
 26
 27impl TestDb {
 28    pub fn sqlite(executor: BackgroundExecutor) -> Self {
 29        let url = "sqlite::memory:";
 30        let runtime = tokio::runtime::Builder::new_current_thread()
 31            .enable_io()
 32            .enable_time()
 33            .build()
 34            .unwrap();
 35
 36        let mut db = runtime.block_on(async {
 37            let mut options = ConnectOptions::new(url);
 38            options.max_connections(5);
 39            let mut db = Database::new(options).await.unwrap();
 40            let sql = include_str!(concat!(
 41                env!("CARGO_MANIFEST_DIR"),
 42                "/migrations.sqlite/20221109000000_test_schema.sql"
 43            ));
 44            db.pool
 45                .execute(sea_orm::Statement::from_string(
 46                    db.pool.get_database_backend(),
 47                    sql,
 48                ))
 49                .await
 50                .unwrap();
 51            db.initialize_notification_kinds().await.unwrap();
 52            db
 53        });
 54
 55        db.test_options = Some(DatabaseTestOptions {
 56            executor,
 57            runtime,
 58            query_failure_probability: parking_lot::Mutex::new(0.0),
 59        });
 60
 61        Self {
 62            db: Some(Arc::new(db)),
 63            connection: None,
 64        }
 65    }
 66
 67    pub fn postgres(executor: BackgroundExecutor) -> Self {
 68        static LOCK: Mutex<()> = Mutex::new(());
 69
 70        let _guard = LOCK.lock();
 71        let mut rng = StdRng::from_os_rng();
 72        let url = format!(
 73            "postgres://postgres@localhost/zed-test-{}",
 74            rng.random::<u128>()
 75        );
 76        let runtime = tokio::runtime::Builder::new_current_thread()
 77            .enable_io()
 78            .enable_time()
 79            .build()
 80            .unwrap();
 81
 82        let mut db = runtime.block_on(async {
 83            sqlx::Postgres::create_database(&url)
 84                .await
 85                .expect("failed to create test db");
 86            let mut options = ConnectOptions::new(url);
 87            options
 88                .max_connections(5)
 89                .idle_timeout(Duration::from_secs(0));
 90            let mut db = Database::new(options).await.unwrap();
 91            let migrations_path = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
 92            run_database_migrations(db.options(), migrations_path)
 93                .await
 94                .unwrap();
 95            db.initialize_notification_kinds().await.unwrap();
 96            db
 97        });
 98
 99        db.test_options = Some(DatabaseTestOptions {
100            executor,
101            runtime,
102            query_failure_probability: parking_lot::Mutex::new(0.0),
103        });
104
105        Self {
106            db: Some(Arc::new(db)),
107            connection: None,
108        }
109    }
110
111    pub fn db(&self) -> &Arc<Database> {
112        self.db.as_ref().unwrap()
113    }
114
115    pub fn set_query_failure_probability(&self, probability: f64) {
116        let database = self.db.as_ref().unwrap();
117        let test_options = database.test_options.as_ref().unwrap();
118        *test_options.query_failure_probability.lock() = probability;
119    }
120}
121
122#[macro_export]
123macro_rules! test_both_dbs {
124    ($test_name:ident, $postgres_test_name:ident, $sqlite_test_name:ident) => {
125        #[gpui::test]
126        async fn $postgres_test_name(cx: &mut gpui::TestAppContext) {
127            // In CI, only run postgres tests on Linux (where we have the postgres service).
128            // Locally, always run them (assuming postgres is available).
129            if std::env::var("CI").is_ok() && !cfg!(target_os = "linux") {
130                return;
131            }
132            let test_db = $crate::db_tests::TestDb::postgres(cx.executor().clone());
133            $test_name(test_db.db()).await;
134        }
135
136        #[gpui::test]
137        async fn $sqlite_test_name(cx: &mut gpui::TestAppContext) {
138            let test_db = $crate::db_tests::TestDb::sqlite(cx.executor().clone());
139            $test_name(test_db.db()).await;
140        }
141    };
142}
143
144impl Drop for TestDb {
145    fn drop(&mut self) {
146        let db = self.db.take().unwrap();
147        if let sea_orm::DatabaseBackend::Postgres = db.pool.get_database_backend() {
148            db.test_options.as_ref().unwrap().runtime.block_on(async {
149                use util::ResultExt;
150                let query = "
151                        SELECT pg_terminate_backend(pg_stat_activity.pid)
152                        FROM pg_stat_activity
153                        WHERE
154                            pg_stat_activity.datname = current_database() AND
155                            pid <> pg_backend_pid();
156                    ";
157                db.pool
158                    .execute(sea_orm::Statement::from_string(
159                        db.pool.get_database_backend(),
160                        query,
161                    ))
162                    .await
163                    .log_err();
164                sqlx::Postgres::drop_database(db.options.get_url())
165                    .await
166                    .log_err();
167            })
168        }
169    }
170}
171
172#[track_caller]
173fn assert_channel_tree_matches(actual: Vec<Channel>, expected: Vec<Channel>) {
174    let expected_channels = expected.into_iter().collect::<HashSet<_>>();
175    let actual_channels = actual.into_iter().collect::<HashSet<_>>();
176    pretty_assertions::assert_eq!(expected_channels, actual_channels);
177}
178
179fn channel_tree(channels: &[(ChannelId, &[ChannelId], &'static str)]) -> Vec<Channel> {
180    use std::collections::HashMap;
181
182    let mut result = Vec::new();
183    let mut order_by_parent: HashMap<Vec<ChannelId>, i32> = HashMap::new();
184
185    for (id, parent_path, name) in channels {
186        let parent_key = parent_path.to_vec();
187        let order = if parent_key.is_empty() {
188            1
189        } else {
190            *order_by_parent
191                .entry(parent_key.clone())
192                .and_modify(|e| *e += 1)
193                .or_insert(1)
194        };
195
196        result.push(Channel {
197            id: *id,
198            name: (*name).to_owned(),
199            visibility: ChannelVisibility::Members,
200            parent_path: parent_key,
201            channel_order: order,
202        });
203    }
204
205    result
206}
207
208static GITHUB_USER_ID: AtomicI32 = AtomicI32::new(5);
209
210async fn new_test_user(db: &Arc<Database>, email: &str) -> UserId {
211    db.create_user(
212        email,
213        None,
214        false,
215        NewUserParams {
216            github_login: email[0..email.find('@').unwrap()].to_string(),
217            github_user_id: GITHUB_USER_ID.fetch_add(1, SeqCst),
218        },
219    )
220    .await
221    .unwrap()
222    .user_id
223}