我尝试在Actix Web应用程序的CI工作流中运行cargo test
。每个测试都通过首先连接到默认数据库(“postgres”)然后执行SQL查询来创建自己的数据库。
这是当前使用的工作流,“测试postgres连接”成功运行,但“Cargo测试”失败:
on: [push, pull_request]
name: CI
env:
CARGO_TERM_COLOR: always
jobs:
test:
name: Test
runs-on: ubuntu-latest
container: rust:latest
services:
postgres:
image: postgres:latest
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- name: Install PSQL
run: |
apt update
apt install -y postgresql-client
- name: Test postgres connection
run: psql -h postgres -d postgres -U postgres -c 'SELECT 1;'
env:
PGPASSWORD: postgres
- name: Cargo test
uses: actions-rs/cargo@v1
with:
command: test
args: --verbose
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
下面是其中一个测试的示例:
struct Context {
pub psql_user: String,
pub psql_pw: String,
}
impl Context {
fn new() -> Self {
dotenv().ok();
let psql_user =
env::var("POSTGRES_USER").expect("POSTGRES_USER must be set for integration tests");
let psql_pw = env::var("POSTGRES_PASSWORD")
.expect("POSTGRES_PASSWORD must be set for integration tests");
let database_url = format!(
"postgres://{}:{}@localhost:5432/postgres",
psql_user, psql_pw
);
let mut conn = PgConnection::establish(&database_url)
.expect("Failed to connect to the database 'postgres'"); // This panics
// ...
}
}
# [actix_web::test]
async fn test_create_task_req() {
let ctx = Context::new("create_task_test");
// ...
}
我假设错误是在我的代码中的某个地方,因为工作流中的一切都运行良好,直到cargo test
抛出以下错误:
---- test_create_task_req stdout ----
thread 'test_create_task_req' panicked at 'Failed to connect to the database 'postgres':
BadConnection("could not connect to server: Connection refused
Is the server running on host \"localhost\" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host \"localhost\" (::1) and accepting
TCP/IP connections on port 5432?
")',
tests/tasks_crud_integration.rs:42:14
在本地运行cargo test
时,不会出现任何问题。
1条答案
按热度按时间qqrboqgw1#
通过反复试验,我最终找到了一个可行的解决方案:
正如上面所看到的,看起来最关键的改变是移除了生 rust 的容器(无论如何,这对工作流来说是不必要的)。尽管找到了解决方案,但我仍然不确切地知道Docker图像中的什么首先导致了问题。