@@ -12,28 +12,22 @@ use anyhow::{Context as _, anyhow};
1212use axum:: body:: Bytes ;
1313use axum:: { Router , body:: Body , http:: Request , response:: Response as AxumResponse } ;
1414use axum_extra:: headers:: { ETag , HeaderMapExt as _} ;
15- use docs_rs_database:: { AsyncPoolClient , Pool } ;
15+ use docs_rs_database:: testing :: TestDatabase ;
1616use docs_rs_fastly:: Cdn ;
1717use docs_rs_headers:: { IfNoneMatch , SURROGATE_CONTROL , SurrogateKeys } ;
18- use docs_rs_opentelemetry:: {
19- AnyMeterProvider ,
20- testing:: { CollectedMetrics , TestMetrics } ,
21- } ;
18+ use docs_rs_opentelemetry:: testing:: { CollectedMetrics , TestMetrics } ;
2219use docs_rs_storage:: { AsyncStorage , Storage , StorageKind , testing:: TestStorage } ;
2320use docs_rs_types:: Version ;
2421use fn_error_context:: context;
25- use futures_util:: stream:: TryStreamExt ;
2622use http:: {
2723 HeaderMap , HeaderName , HeaderValue , StatusCode ,
2824 header:: { CACHE_CONTROL , CONTENT_TYPE } ,
2925} ;
3026use http_body_util:: BodyExt ;
3127use serde:: de:: DeserializeOwned ;
32- use sqlx:: Connection as _;
3328use std:: { collections:: HashMap , fs, future:: Future , panic, rc:: Rc , sync:: Arc } ;
34- use tokio:: { runtime, task :: block_in_place } ;
29+ use tokio:: runtime;
3530use tower:: ServiceExt ;
36- use tracing:: error;
3731
3832// testing krate name constants
3933pub ( crate ) const KRATE : & str = "krate" ;
@@ -452,8 +446,7 @@ impl TestEnvironment {
452446 fs:: create_dir_all ( config. registry_index_path . clone ( ) ) ?;
453447
454448 let test_metrics = TestMetrics :: new ( ) ;
455-
456- let test_db = TestDatabase :: new ( & config, test_metrics. provider ( ) )
449+ let test_db = TestDatabase :: new ( & config. database , test_metrics. provider ( ) )
457450 . await
458451 . context ( "can't initialize test database" ) ?;
459452
@@ -542,108 +535,3 @@ impl TestEnvironment {
542535 fakes:: FakeRelease :: new ( self . async_db ( ) , self . context . async_storage . clone ( ) )
543536 }
544537}
545-
546- #[ derive( Debug ) ]
547- pub ( crate ) struct TestDatabase {
548- pool : Pool ,
549- schema : String ,
550- runtime : runtime:: Handle ,
551- }
552-
553- impl TestDatabase {
554- async fn new ( config : & Config , otel_meter_provider : & AnyMeterProvider ) -> Result < Self > {
555- // A random schema name is generated and used for the current connection. This allows each
556- // test to create a fresh instance of the database to run within.
557- let schema = format ! ( "docs_rs_test_schema_{}" , rand:: random:: <u64 >( ) ) ;
558-
559- let config = & config. database ;
560-
561- let pool = Pool :: new_with_schema ( config, & schema, otel_meter_provider) . await ?;
562-
563- let mut conn = sqlx:: PgConnection :: connect ( & config. database_url ) . await ?;
564- sqlx:: query ( & format ! ( "CREATE SCHEMA {schema}" ) )
565- . execute ( & mut conn)
566- . await
567- . context ( "error creating schema" ) ?;
568- sqlx:: query ( & format ! ( "SET search_path TO {schema}, public" ) )
569- . execute ( & mut conn)
570- . await
571- . context ( "error setting search path" ) ?;
572- docs_rs_database:: migrate ( & mut conn, None )
573- . await
574- . context ( "error running migrations" ) ?;
575-
576- // Move all sequence start positions 10000 apart to avoid overlapping primary keys
577- let sequence_names: Vec < _ > = sqlx:: query!(
578- "SELECT relname
579- FROM pg_class
580- INNER JOIN pg_namespace ON
581- pg_class.relnamespace = pg_namespace.oid
582- WHERE pg_class.relkind = 'S'
583- AND pg_namespace.nspname = $1
584- " ,
585- schema,
586- )
587- . fetch ( & mut conn)
588- . map_ok ( |row| row. relname )
589- . try_collect ( )
590- . await ?;
591-
592- for ( i, sequence) in sequence_names. into_iter ( ) . enumerate ( ) {
593- let offset = ( i + 1 ) * 10000 ;
594- sqlx:: query ( & format ! (
595- r#"ALTER SEQUENCE "{sequence}" RESTART WITH {offset};"#
596- ) )
597- . execute ( & mut conn)
598- . await ?;
599- }
600-
601- Ok ( TestDatabase {
602- pool,
603- schema,
604- runtime : runtime:: Handle :: current ( ) ,
605- } )
606- }
607-
608- pub ( crate ) fn pool ( & self ) -> & Pool {
609- & self . pool
610- }
611-
612- pub ( crate ) async fn async_conn ( & self ) -> AsyncPoolClient {
613- self . pool
614- . get_async ( )
615- . await
616- . expect ( "failed to get a connection out of the pool" )
617- }
618- }
619-
620- impl Drop for TestDatabase {
621- fn drop ( & mut self ) {
622- let pool = self . pool . clone ( ) ;
623- let schema = self . schema . clone ( ) ;
624- let runtime = self . runtime . clone ( ) ;
625-
626- block_in_place ( move || {
627- runtime. block_on ( async move {
628- let Ok ( mut conn) = pool. get_async ( ) . await else {
629- error ! ( "error in drop impl" ) ;
630- return ;
631- } ;
632-
633- let migration_result = docs_rs_database:: migrate ( & mut conn, Some ( 0 ) ) . await ;
634-
635- if let Err ( e) = sqlx:: query ( format ! ( "DROP SCHEMA {} CASCADE;" , schema) . as_str ( ) )
636- . execute ( & mut * conn)
637- . await
638- {
639- error ! ( "failed to drop test schema {}: {}" , schema, e) ;
640- return ;
641- }
642-
643- if let Err ( err) = migration_result {
644- error ! ( ?err, "error reverting migrations" ) ;
645- }
646- } )
647- } ) ;
648- }
649- }
0 commit comments