Skip to content

Commit 1ce77a5

Browse files
refactor(testkit): use the new sandbox helpers with the credential gating changes
Add SandboxBuilder::image and CliSandboxBuilder::create_ready, so both builders set an image and wait for Ready the same way. Convert tonic::Status into testkit::Error, keeping its code, so gRPC results take .context() directly, and drop Error::from_status. Create the host-gateway sandbox with cx.sandbox(..).image(..).policy(..) instead of a hand-written CLI create. In credential gating, use create_ready and poll_exec. Drop the remaining map_err calls on I/O results in host-server-support. Signed-off-by: Matthew Grossman <[email protected]>
1 parent de47b66 commit 1ce77a5

11 files changed

Lines changed: 63 additions & 84 deletions

File tree

‎tests/suites/conformance/src/cli.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,9 @@ async fn cli_stop_start_delete(cx: &mut Context) -> testkit::Result {
5959
let sandbox = cx
6060
.cli_sandbox("cl")
6161
.command(["sh", "-c", "exec sleep infinity"])
62-
.create()
62+
.create_ready()
6363
.await?;
6464
let name = sandbox.name().to_string();
65-
sandbox.wait_ready().await?;
6665

6766
cx.cli(["sandbox", "stop", &name]).await?.success()?;
6867
sandbox

‎tests/suites/conformance/src/credential_gating.rs‎

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use host_server_support::{HttpRecorder, Request, WebSocketRecorder};
1414
use testkit::policy::{self, Access, Endpoint as _};
1515
use testkit::sdk::raw::proto;
1616
use testkit::{
17-
Context, Error, GrpcCode, PYTHON_BINARIES, Poll, Result, ResultExt as _, Sandbox, YamlFile,
17+
Context, Error, GrpcCode, PYTHON_BINARIES, Result, ResultExt as _, Sandbox, YamlFile,
1818
};
1919

2020
const TEST_HOST: &str = "host.openshell.internal";
@@ -298,10 +298,8 @@ fn sandbox_with(
298298
) -> testkit::SandboxBuilder {
299299
cx.sandbox(suffix)
300300
.policy(policy)
301-
.spec(|spec| {
302-
spec.image = Some(testkit::python_image());
303-
spec.providers = providers.iter().map(ToString::to_string).collect();
304-
})
301+
.image(testkit::python_image())
302+
.spec(|spec| spec.providers = providers.iter().map(ToString::to_string).collect())
305303
.command(["sleep", "infinity"])
306304
}
307305

@@ -313,9 +311,9 @@ async fn create_sandbox(
313311
policy: proto::SandboxPolicy,
314312
providers: &[&str],
315313
) -> Result<Sandbox> {
316-
let sandbox = sandbox_with(cx, suffix, policy, providers).create().await?;
317-
sandbox.wait_ready().await?;
318-
Ok(sandbox)
314+
sandbox_with(cx, suffix, policy, providers)
315+
.create_ready()
316+
.await
319317
}
320318

321319
/// Fail unless the gateway rejects the sandbox as a failed precondition, and
@@ -384,25 +382,15 @@ fn redact(request: &Request) -> String {
384382

385383
/// Wait until new exec sessions report `expected` from [`TOKEN_PRESENCE`].
386384
async fn wait_for_token(sandbox: &Sandbox, expected: &str) -> Result {
387-
testkit::poll_until(
388-
&format!("the provider environment to report {expected}"),
389-
Duration::from_secs(30),
390-
Duration::from_millis(500),
391-
async || {
392-
let output = sandbox.exec(["sh", "-lc", TOKEN_PRESENCE]).await?;
393-
Ok(if output.stdout.contains(expected) {
394-
Poll::Ready(())
395-
} else {
396-
Poll::Pending(format!(
397-
"exit {}; stdout: {}; stderr: {}",
398-
output.exit_code,
399-
output.stdout.trim(),
400-
output.stderr.trim()
401-
))
402-
})
403-
},
404-
)
405-
.await
385+
sandbox
386+
.poll_exec(
387+
&format!("the provider environment to report {expected}"),
388+
Duration::from_secs(30),
389+
["sh", "-lc", TOKEN_PRESENCE],
390+
|output| output.stdout.contains(expected),
391+
)
392+
.await?;
393+
Ok(())
406394
}
407395

408396
/// Replace `sandbox`'s policy with `policy` and wait until it is applied.

‎tests/suites/conformance/src/image.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ async fn explicit_image_is_used(cx: &mut Context) -> testkit::Result {
1212
let sandbox = cx
1313
.sandbox("ei")
1414
.command(["sleep", "infinity"])
15-
.spec(|spec| spec.image = Some(image.clone()))
15+
.image(image.clone())
1616
.create_ready()
1717
.await?;
1818
expect_ubuntu(&sandbox)

‎tests/suites/drivers/podman/tests/oci_identity.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,9 @@ USER {OCI_IDENTITY}
6969
.image(&image.tag)
7070
.policy_yaml(IMAGE_IDENTITY_POLICY)
7171
.command(["sleep", "infinity"])
72-
.create()
72+
.create_ready()
7373
.await
7474
.context("sandbox starts from the OCI identity image")?;
75-
sandbox.wait_ready().await?;
7675

7776
let supervisor = engine
7877
.container_for_role(sandbox.name(), "supervisor")

‎tests/suites/features/host-gateway/tests/host_gateway.rs‎

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
1212
use host_server_support::HttpRecorder;
1313
use testkit::policy;
14-
use testkit::{Context, PYTHON_BINARIES, Result, ResultExt as _, YamlFile};
14+
use testkit::sdk::raw::proto;
15+
use testkit::{Context, PYTHON_BINARIES, ResultExt as _};
1516

1617
/// The image's Python, which needs nothing beyond its standard library. The
1718
/// policy allows [`PYTHON_BINARIES`], the real paths behind `python3` in
@@ -42,42 +43,24 @@ print(response.decode(errors="replace"))
4243
async fn python_sandbox_reaches_host_server(cx: &mut Context) -> testkit::Result {
4344
let marker = format!("host-gateway-{}", cx.run_id());
4445
let server = HttpRecorder::start(marker.clone()).await?;
45-
let policy = YamlFile::new(&policy(server.port)?)?;
46-
let port = server.port.to_string();
4746
let image = testkit::python_image();
4847

4948
// The client runs through `sandbox exec` in a Ready sandbox, not as the
5049
// main process. A gateway with several replicas (k3s-ha) can refuse to
5150
// attach to a main process that already finished with "sandbox is not
5251
// ready" when the request reaches a replica that doesn't hold the
5352
// sandbox's session.
54-
let name = cx.name("hg");
55-
cx.track(&name);
56-
cx.cli([
57-
"sandbox",
58-
"create",
59-
"--name",
60-
&name,
61-
"--from",
62-
&image,
63-
"--policy",
64-
policy.path()?,
65-
"--detach",
66-
"--no-tty",
67-
"--",
68-
"sh",
69-
"-c",
70-
"exec sleep infinity",
71-
])
72-
.await?
73-
.success()
74-
.context(format!("create a sandbox from {image}"))?;
75-
cx.adopt(&name).await?.wait_ready().await?;
53+
let sandbox = cx
54+
.sandbox("hg")
55+
.image(image.clone())
56+
.policy(policy(server.port))
57+
.command(["sh", "-c", "exec sleep infinity"])
58+
.create_ready()
59+
.await
60+
.context(format!("create a sandbox from {image}"))?;
7661

77-
let client = cx
78-
.cli([
79-
"sandbox", "exec", "--name", &name, "--no-tty", "--", PYTHON, "-c", CLIENT, &port,
80-
])
62+
let client = sandbox
63+
.exec([PYTHON, "-c", CLIENT, &server.port.to_string()])
8164
.await?
8265
.success()
8366
.context("run the client in the sandbox")?;
@@ -94,7 +77,7 @@ async fn python_sandbox_reaches_host_server(cx: &mut Context) -> testkit::Result
9477
/// connect to `host.openshell.internal` on `port`. The endpoint names only the
9578
/// host and port, as the policy docs describe, so the driver's address for the
9679
/// name is what makes it reachable, not an `allowed_ips` range.
97-
fn policy(port: u16) -> Result<String> {
80+
fn policy(port: u16) -> proto::SandboxPolicy {
9881
let mut policy = policy::base();
9982
policy::allow(
10083
&mut policy,
@@ -103,5 +86,5 @@ fn policy(port: u16) -> Result<String> {
10386
port,
10487
PYTHON_BINARIES,
10588
);
106-
policy::to_yaml(&policy)
89+
policy
10790
}

‎tests/suites/features/kubernetes-updates/tests/update.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ async fn image_update_retains_workspace_and_identity(cx: &mut Context) -> testki
458458
let sandbox = cx
459459
// The testkit's unique prefix leaves five characters of the name limit.
460460
.sandbox("image")
461-
.spec(|spec| spec.image = Some(ORIGINAL_IMAGE.to_string()))
461+
.image(ORIGINAL_IMAGE.as_str())
462462
.create()
463463
.await?;
464464
sandbox.wait_ready().await?;
@@ -597,7 +597,7 @@ async fn terminal_workload_can_stop_update_and_restart(cx: &mut Context) -> test
597597
let sandbox = cx
598598
.sandbox("term")
599599
.restart_policy(testkit::sdk::SandboxRestartPolicy::Never)
600-
.spec(|spec| spec.image = Some(ORIGINAL_IMAGE.to_string()))
600+
.image(ORIGINAL_IMAGE.as_str())
601601
.create()
602602
.await?;
603603
sandbox.wait_ready().await?;

‎tests/support/host-server/src/lib.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ mod websocket;
1515

1616
use std::time::Duration;
1717

18-
use testkit::{Error, Result, ResultExt as _};
18+
use testkit::{Result, ResultExt as _};
1919
use tokio::net::TcpListener;
2020

2121
pub use http::{HttpRecorder, Request};
@@ -29,11 +29,9 @@ const MAX_REQUEST: usize = 1024 * 1024;
2929
async fn bind() -> Result<(TcpListener, u16)> {
3030
let listener = TcpListener::bind(("0.0.0.0", 0))
3131
.await
32-
.map_err(|error| Error::from_error(&error))
3332
.context("bind a host server")?;
3433
let port = listener
3534
.local_addr()
36-
.map_err(|error| Error::from_error(&error))
3735
.context("read the host server's address")?
3836
.port();
3937
Ok((listener, port))

‎tests/testkit/README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,17 @@ fails. A killed test process skips cleanup, so names are unique to the run.
6464
`Context` currently provides:
6565

6666
- `cx.sandbox(suffix)` to build a sandbox with a run-unique name, then
67-
`create()` it or `create_ready()` to also wait for Ready. The returned
67+
`create()` it or `create_ready()` to also wait for Ready. Set its image
68+
with `image(..)` and its policy with `policy(..)`. The returned
6869
`Sandbox` can wait for ready or finished, stop, start, exec or
6970
`poll_exec` until the output matches, read its config and draft policy, set
7071
a setting, read `sandbox get` JSON with `get_json()`, and delete. Its
7172
`expect_listed`, `expect_absent` and `wait_absent` check list and get.
7273
Exec output has `success()`, `failure()` and `expect_stdout()`.
7374
- `cx.cli_sandbox(suffix)` for a sandbox only `openshell sandbox create`
7475
can make, such as one with `policy_yaml(...)` or `--no-keep`. `create()`
75-
detaches and returns the `Sandbox`; `run()` returns the attached CLI
76-
output.
76+
detaches and returns the `Sandbox`, `create_ready()` also waits for Ready,
77+
and `run()` returns the attached CLI output.
7778
- `cx.track(name)` to register a sandbox created some other way, such as
7879
through the CLI, for cleanup. Call it before the
7980
create, so a create that fails after the gateway accepted it is still cleaned

‎tests/testkit/testkit/src/cli_sandbox.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,13 @@ impl<'a> CliSandboxBuilder<'a> {
8787
self.cx.adopt(&self.name).await
8888
}
8989

90+
/// Create the sandbox and wait until it is Ready.
91+
pub async fn create_ready(self) -> Result<Sandbox> {
92+
let sandbox = self.create().await?;
93+
sandbox.wait_ready().await?;
94+
Ok(sandbox)
95+
}
96+
9097
/// Create the sandbox attached to its main command and return the CLI's
9198
/// output, whatever its exit code. For a test of the main command's
9299
/// result, or of a create that must fail.

‎tests/testkit/testkit/src/context.rs‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,6 @@ impl Context {
200200
.await?
201201
.get_gateway_info(proto::GetGatewayInfoRequest {})
202202
.await
203-
.map_err(|status| Error::from_error(&status))
204203
.context("get gateway info")?
205204
.into_inner();
206205
let drivers: Vec<(&str, &str)> = info
@@ -289,6 +288,13 @@ impl SandboxBuilder {
289288
self
290289
}
291290

291+
/// Create the sandbox from `image` instead of the gateway's default.
292+
#[must_use]
293+
pub fn image(mut self, image: impl Into<String>) -> Self {
294+
self.spec.image = Some(image.into());
295+
self
296+
}
297+
292298
#[must_use]
293299
pub fn restart_policy(mut self, policy: SandboxRestartPolicy) -> Self {
294300
self.spec.restart_policy = policy;
@@ -342,7 +348,6 @@ impl SandboxBuilder {
342348
.await?
343349
.create_sandbox(request)
344350
.await
345-
.map_err(|status| Error::from_status(&status))
346351
.context(format!("create sandbox {name}"))?;
347352
self.client
348353
.get_sandbox(&name)
@@ -560,7 +565,6 @@ impl Sandbox {
560565
.await?
561566
.update_config(request)
562567
.await
563-
.map_err(|status| Error::from_error(&status))
564568
.context(format!("set {key} on sandbox {}", self.name))?;
565569
Ok(())
566570
}
@@ -577,7 +581,6 @@ impl Sandbox {
577581
.await?
578582
.get_sandbox_config(request)
579583
.await
580-
.map_err(|status| Error::from_error(&status))
581584
.context(format!("get config of sandbox {}", self.name))?
582585
.into_inner())
583586
}
@@ -595,7 +598,6 @@ impl Sandbox {
595598
.await?
596599
.get_draft_policy(request)
597600
.await
598-
.map_err(|status| Error::from_error(&status))
599601
.context(format!("get draft policy of sandbox {}", self.name))?
600602
.into_inner())
601603
}

0 commit comments

Comments
 (0)