Skip to content

Commit 164043e

Browse files
authored
Merge pull request #108 from rust-lang/tests-migration
Another round of test refactoring
2 parents 81441ae + 4fcf0db commit 164043e

18 files changed

+62
-86
lines changed

src/bors/handlers/help.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@ pub(super) async fn command_help<Client: RepositoryClient>(
2525
#[cfg(test)]
2626
mod tests {
2727
use crate::bors::handlers::help::HELP_MESSAGE;
28-
use crate::tests::event::default_pr_number;
29-
use crate::tests::state::ClientBuilder;
28+
use crate::tests::mocks::run_test;
3029

3130
#[sqlx::test]
32-
async fn test_help(pool: sqlx::PgPool) {
33-
let state = ClientBuilder::default().pool(pool).create_state().await;
34-
state.comment("@bors help").await;
35-
state
36-
.client()
37-
.check_comments(default_pr_number(), &[HELP_MESSAGE]);
31+
async fn help_command(pool: sqlx::PgPool) {
32+
run_test(pool, |mut tester| async {
33+
tester.post_comment("@bors help").await;
34+
assert_eq!(tester.get_comment().await, HELP_MESSAGE);
35+
Ok(tester)
36+
})
37+
.await;
3838
}
3939
}

src/bors/handlers/mod.rs

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
use anyhow::Context;
21
use std::sync::Arc;
2+
3+
use anyhow::Context;
34
use tracing::Instrument;
45

56
use crate::bors::command::{BorsCommand, CommandParseError};
@@ -273,25 +274,17 @@ fn is_bors_observed_branch(branch: &str) -> bool {
273274

274275
#[cfg(test)]
275276
mod tests {
276-
use crate::tests::event::{comment, default_pr_number};
277-
use crate::tests::state::{test_bot_user, ClientBuilder};
277+
use crate::tests::mocks::{run_test, Comment, User};
278278

279279
#[sqlx::test]
280-
async fn test_ignore_bot_comment(pool: sqlx::PgPool) {
281-
let state = ClientBuilder::default().pool(pool).create_state().await;
282-
state
283-
.comment(comment("@bors ping").author(test_bot_user()).create())
284-
.await;
285-
state.client().check_comments(default_pr_number(), &[]);
280+
async fn ignore_bot_comment(pool: sqlx::PgPool) {
281+
run_test(pool, |mut tester| async {
282+
tester
283+
.post_comment(Comment::from("@bors ping").with_author(User::bors_bot()))
284+
.await;
285+
// Returning here will make sure that no comments were received
286+
Ok(tester)
287+
})
288+
.await;
286289
}
287-
288-
// #[sqlx::test]
289-
// async fn test_do_not_comment_when_pr_fetch_fails(pool: sqlx::PgPool) {
290-
// let state = ClientBuilder::default().pool(pool).create_state().await;
291-
// state
292-
// .client()
293-
// .set_get_pr_fn(|_| Err(anyhow::anyhow!("Foo")));
294-
// state.comment(comment("foo").create()).await;
295-
// state.client().check_comments(default_pr_number(), &[]);
296-
// }
297290
}

src/bors/handlers/ping.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ mod tests {
2020
use crate::tests::mocks::run_test;
2121

2222
#[sqlx::test]
23-
async fn test_ping(pool: sqlx::PgPool) {
23+
async fn ping_command(pool: sqlx::PgPool) {
2424
run_test(pool, |mut tester| async {
2525
tester.post_comment("@bors ping").await;
2626
assert_eq!(tester.get_comment().await, "Pong 🏓!");

src/bors/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ pub use context::BorsContext;
2121
pub use handlers::{handle_bors_global_event, handle_bors_repository_event};
2222

2323
/// Provides functionality for working with a remote repository.
24-
#[async_trait]
2524
pub trait RepositoryClient: Send + Sync {
2625
fn repository(&self) -> &GithubRepoName;
2726

src/github/api/client.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@ impl GithubRepositoryClient {
4545
}
4646
}
4747

48-
#[async_trait]
4948
impl RepositoryClient for GithubRepositoryClient {
5049
fn repository(&self) -> &GithubRepoName {
5150
self.name()

src/github/webhook.rs

Lines changed: 5 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -358,16 +358,15 @@ fn verify_gh_signature(
358358
#[cfg(test)]
359359
mod tests {
360360
use axum::extract::FromRequest;
361-
use axum::http::{HeaderValue, Method};
362-
use hmac::Mac;
363-
use hyper::{Request, StatusCode};
361+
use hyper::StatusCode;
364362
use tokio::sync::mpsc;
365363

366364
use crate::bors::event::{BorsEvent, BorsGlobalEvent};
367365
use crate::github::server::{ServerState, ServerStateRef};
366+
use crate::github::webhook::GitHubWebhook;
368367
use crate::github::webhook::WebhookSecret;
369-
use crate::github::webhook::{GitHubWebhook, HmacSha256};
370368
use crate::tests::io::load_test_file;
369+
use crate::tests::webhook::{create_webhook_request, TEST_WEBHOOK_SECRET};
371370

372371
#[tokio::test]
373372
async fn test_installation_suspend() {
@@ -650,36 +649,14 @@ mod tests {
650649

651650
async fn check_webhook(file: &str, event: &str) -> Result<GitHubWebhook, StatusCode> {
652651
let body = load_test_file(file);
653-
let body_length = body.len();
654-
655-
let secret = "ABCDEF".to_string();
656-
let mut mac =
657-
HmacSha256::new_from_slice(secret.as_bytes()).expect("Cannot create HMAC key");
658-
mac.update(body.as_bytes());
659-
let hash = mac.finalize().into_bytes();
660-
let hash = hex::encode(hash);
661-
let signature = format!("sha256={hash}");
662-
663-
let mut request = Request::new(axum::body::Body::from(body));
664-
*request.method_mut() = Method::POST;
665-
let headers = request.headers_mut();
666-
headers.insert("content-type", HeaderValue::from_static("application-json"));
667-
headers.insert(
668-
"content-length",
669-
HeaderValue::from_str(&body_length.to_string()).unwrap(),
670-
);
671-
headers.insert("x-github-event", HeaderValue::from_str(event).unwrap());
672-
headers.insert(
673-
"x-hub-signature-256",
674-
HeaderValue::from_str(&signature).unwrap(),
675-
);
652+
let request = create_webhook_request(event, &body);
676653

677654
let (repository_tx, _) = mpsc::channel(1024);
678655
let (global_tx, _) = mpsc::channel(1024);
679656
let server_ref = ServerStateRef::new(ServerState::new(
680657
repository_tx,
681658
global_tx,
682-
WebhookSecret::new(secret),
659+
WebhookSecret::new(TEST_WEBHOOK_SECRET.to_string()),
683660
));
684661
GitHubWebhook::from_request(request, &server_ref).await
685662
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#![allow(async_fn_in_trait)]
2+
13
//! This is the library of the bors bot.
24
mod bors;
35
mod config;

src/tests/event.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,6 @@ impl From<CommentBuilder> for PullRequestComment {
6565
}
6666
}
6767

68-
pub fn comment(text: &str) -> CommentBuilder {
69-
CommentBuilder::default().text(text.to_string())
70-
}
71-
7268
pub fn suite_success() -> CheckSuite {
7369
CheckSuite {
7470
status: CheckSuiteStatus::Success,

src/tests/mocks/app.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::tests::mocks::User;
12
use serde::Serialize;
23
use url::Url;
34
use wiremock::{
@@ -53,7 +54,7 @@ impl Default for App {
5354
owner: GitHubUser::default(),
5455
name: "bors".to_string(),
5556
// same as bors user html_url
56-
html_url: "https://test-bors.bot.com".parse().unwrap(),
57+
html_url: GitHubUser::from(User::bors_bot()).html_url,
5758
external_url: "https://test-bors.bot.com".parse().unwrap(),
5859
permissions: Permissions {},
5960
events: vec!["*".to_string()],

src/tests/mocks/bors.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ use crate::github::api::load_repositories;
1212
use crate::tests::database::MockedDBClient;
1313
use crate::tests::event::default_pr_number;
1414
use crate::tests::mocks::comment::{Comment, GitHubIssueCommentEventPayload};
15-
use crate::tests::mocks::webhook::{create_webhook_request, TEST_WEBHOOK_SECRET};
1615
use crate::tests::mocks::{ExternalHttpMock, Repo, World};
16+
use crate::tests::webhook::{create_webhook_request, TEST_WEBHOOK_SECRET};
1717
use crate::{
1818
create_app, create_bors_process, BorsContext, CommandParser, ServerState, WebhookSecret,
1919
};
@@ -116,13 +116,8 @@ impl BorsTester {
116116
.content
117117
}
118118

119-
pub async fn post_comment(&mut self, content: &str) {
120-
self.webhook_comment(Comment::new(
121-
Repo::default().name,
122-
default_pr_number(),
123-
content,
124-
))
125-
.await;
119+
pub async fn post_comment<C: Into<Comment>>(&mut self, comment: C) {
120+
self.webhook_comment(comment.into()).await;
126121
}
127122

128123
async fn webhook_comment(&mut self, comment: Comment) {
@@ -134,7 +129,7 @@ impl BorsTester {
134129
}
135130

136131
async fn send_webhook<S: Serialize>(&mut self, event: &str, content: S) {
137-
let webhook = create_webhook_request(event, content);
132+
let webhook = create_webhook_request(event, &serde_json::to_string(&content).unwrap());
138133
let response = self
139134
.app
140135
.call(webhook)

src/tests/mocks/comment.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ use serde::Serialize;
66
use url::Url;
77

88
use crate::github::GithubRepoName;
9+
use crate::tests::event::default_pr_number;
910
use crate::tests::mocks::repository::GitHubRepository;
1011
use crate::tests::mocks::user::{GitHubUser, User};
12+
use crate::tests::mocks::Repo;
1113

1214
#[derive(Clone, Debug)]
1315
pub struct Comment {
@@ -32,6 +34,12 @@ impl Comment {
3234
}
3335
}
3436

37+
impl<'a> From<&'a str> for Comment {
38+
fn from(value: &'a str) -> Self {
39+
Comment::new(Repo::default().name, default_pr_number(), value)
40+
}
41+
}
42+
3543
// Copied from octocrab, since its version if #[non_exhaustive]
3644
#[derive(Serialize)]
3745
pub struct GitHubIssueCommentEventPayload {

src/tests/mocks/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::tests::mocks::permissions::TeamApiMockServer;
99
use crate::TeamApiClient;
1010

1111
pub use bors::run_test;
12+
pub use comment::Comment;
1213
pub use repository::Repo;
1314
pub use user::User;
1415

@@ -20,7 +21,6 @@ mod permissions;
2021
mod pull_request;
2122
mod repository;
2223
mod user;
23-
mod webhook;
2424

2525
pub struct World {
2626
repos: HashMap<GithubRepoName, Repo>,

src/tests/mocks/pull_request.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ use super::{
1010
Repo, User,
1111
};
1212

13+
pub fn default_pr_number() -> u64 {
14+
1
15+
}
16+
1317
pub async fn mock_pull_requests(
1418
repo: &Repo,
1519
comments_tx: Sender<Comment>,
@@ -35,7 +39,7 @@ pub async fn mock_pull_requests(
3539
let comment_payload: CommentCreatePayload = req.body_json().unwrap();
3640
let comment: Comment =
3741
Comment::new(repo_name.clone(), pr_number, &comment_payload.body)
38-
.with_author(User::new(1002, "bors"));
42+
.with_author(User::bors_bot());
3943

4044
// We cannot use `tx.blocking_send()`, because this function is actually called
4145
// from within an async task, but it is not async, so we also cannot use
@@ -105,10 +109,6 @@ struct Base {
105109
sha: String,
106110
}
107111

108-
fn default_pr_number() -> u64 {
109-
1
110-
}
111-
112112
#[derive(Deserialize)]
113113
struct CommentCreatePayload {
114114
body: String,

src/tests/mocks/repository.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ timeout = 3600
6464
}
6565
}
6666

67-
fn default_repo_name() -> GithubRepoName {
67+
pub fn default_repo_name() -> GithubRepoName {
6868
GithubRepoName::new("rust-lang", "borstest")
6969
}
7070

src/tests/mocks/user.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@ pub struct User {
88
}
99

1010
impl User {
11+
pub fn default_user() -> Self {
12+
Self::new(101, "default-user")
13+
}
14+
15+
pub fn bors_bot() -> Self {
16+
Self::new(102, "bors-bot")
17+
}
18+
1119
pub fn new(id: u64, name: &str) -> Self {
1220
Self {
1321
github_id: id,
@@ -18,7 +26,7 @@ impl User {
1826

1927
impl Default for User {
2028
fn default() -> Self {
21-
Self::new(101, "default-user")
29+
Self::default_user()
2230
}
2331
}
2432

@@ -30,7 +38,7 @@ pub struct GitHubUser {
3038
avatar_url: Url,
3139
gravatar_id: String,
3240
url: Url,
33-
html_url: Url,
41+
pub html_url: Url,
3442
followers_url: Url,
3543
following_url: Url,
3644
gists_url: Url,

src/tests/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ pub(crate) mod github;
44
pub(crate) mod io;
55
pub(crate) mod mocks;
66
pub(crate) mod state;
7+
pub(crate) mod webhook;

src/tests/state.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,6 @@ impl TestRepositoryClient {
412412
}
413413
}
414414

415-
#[async_trait]
416415
impl RepositoryClient for Arc<TestRepositoryClient> {
417416
fn repository(&self) -> &GithubRepoName {
418417
&self.name
Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
use axum::body::Body;
22
use hmac::{Hmac, Mac};
33
use http::Request;
4-
use serde::Serialize;
54
use sha2::Sha256;
65

76
pub const TEST_WEBHOOK_SECRET: &str = "ABCDEF";
87

9-
pub fn create_webhook_request<S: Serialize>(event: &str, content: S) -> Request<Body> {
10-
let body = serde_json::to_string(&content).unwrap();
8+
pub fn create_webhook_request(event: &str, body: &str) -> Request<Body> {
119
let mut mac = Hmac::<Sha256>::new_from_slice(TEST_WEBHOOK_SECRET.as_bytes()).unwrap();
1210
mac.update(body.as_bytes());
1311
let signature = hex::encode(mac.finalize().into_bytes());
@@ -18,6 +16,6 @@ pub fn create_webhook_request<S: Serialize>(event: &str, content: S) -> Request<
1816
.header("x-github-event", event)
1917
.header("x-hub-signature-256", signature)
2018
.header("Content-Type", "application/json")
21-
.body(Body::from(body))
19+
.body(Body::from(body.to_string()))
2220
.unwrap()
2321
}

0 commit comments

Comments
 (0)