alef-e2e 0.13.0

Fixture-driven e2e test generator for alef
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Dart e2e test generator using package:test and package:http.
//!
//! Generates `e2e/dart/test/<category>_test.dart` files from JSON fixtures.
//! HTTP fixtures hit the mock server at `MOCK_SERVER_URL/fixtures/<id>`.
//! Non-HTTP fixtures without a dart-specific call override emit a skip stub.

use crate::config::E2eConfig;
use crate::escape::sanitize_filename;
use crate::fixture::{Fixture, FixtureGroup, HttpFixture};
use alef_core::backend::GeneratedFile;
use alef_core::config::AlefConfig;
use alef_core::hash::{self, CommentStyle};
use alef_core::template_versions::pub_dev;
use anyhow::Result;
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;

/// Dart e2e code generator.
pub struct DartE2eCodegen;

impl E2eCodegen for DartE2eCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        alef_config: &AlefConfig,
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        let mut files = Vec::new();

        // Resolve package config.
        let dart_pkg = e2e_config.resolve_package("dart");
        let pkg_name = dart_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| alef_config.dart_pubspec_name());
        let pkg_path = dart_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| "../../packages/dart".to_string());
        let pkg_version = dart_pkg
            .as_ref()
            .and_then(|p| p.version.as_ref())
            .cloned()
            .unwrap_or_else(|| "0.1.0".to_string());

        // Generate pubspec.yaml with http dependency for HTTP client tests.
        files.push(GeneratedFile {
            path: output_base.join("pubspec.yaml"),
            content: render_pubspec(&pkg_name, &pkg_path, &pkg_version, e2e_config.dep_mode),
            generated_header: false,
        });

        // Generate dart_test.yaml to limit parallelism — the mock server uses keep-alive
        // connections and gets overwhelmed when test files run in parallel.
        files.push(GeneratedFile {
            path: output_base.join("dart_test.yaml"),
            content: concat!(
                "# Generated by alef — DO NOT EDIT.\n",
                "# Run test files sequentially to avoid overwhelming the mock server with\n",
                "# concurrent keep-alive connections.\n",
                "concurrency: 1\n",
            )
            .to_string(),
            generated_header: false,
        });

        let test_base = output_base.join("test");

        // One test file per fixture group.
        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
                .collect();

            if active.is_empty() {
                continue;
            }

            let filename = format!("{}_test.dart", sanitize_filename(&group.category));
            let content = render_test_file(&group.category, &active, e2e_config, lang);
            files.push(GeneratedFile {
                path: test_base.join(filename),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn language_name(&self) -> &'static str {
        "dart"
    }
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

fn render_pubspec(
    pkg_name: &str,
    pkg_path: &str,
    pkg_version: &str,
    dep_mode: crate::config::DependencyMode,
) -> String {
    let test_ver = pub_dev::TEST_PACKAGE;
    let http_ver = pub_dev::HTTP_PACKAGE;

    let dep_block = match dep_mode {
        crate::config::DependencyMode::Registry => {
            format!("  {pkg_name}: ^{pkg_version}")
        }
        crate::config::DependencyMode::Local => {
            format!("  {pkg_name}:\n    path: {pkg_path}")
        }
    };

    format!(
        r#"name: e2e_dart
version: 0.1.0
publish_to: none

environment:
  sdk: ">=3.0.0 <4.0.0"

dependencies:
{dep_block}

dev_dependencies:
  test: {test_ver}
  http: {http_ver}
"#
    )
}

fn render_test_file(category: &str, fixtures: &[&Fixture], e2e_config: &E2eConfig, lang: &str) -> String {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::DoubleSlash));

    // Check if any fixture needs the http package (HTTP server tests).
    let has_http_fixtures = fixtures.iter().any(|f| f.is_http_test());

    let _ = writeln!(out, "import 'package:test/test.dart';");
    let _ = writeln!(out, "import 'dart:io';");
    if has_http_fixtures {
        let _ = writeln!(out, "import 'dart:async';");
        let _ = writeln!(out, "import 'dart:convert';");
    }
    let _ = writeln!(out);

    // Emit file-level HTTP client and serialization mutex.
    //
    // The shared HttpClient reuses keep-alive connections to minimize TCP overhead.
    // The mutex (_lock) ensures requests are serialized within the file so the
    // connection pool is not exercised concurrently by dart:test's async runner.
    //
    // _withRetry wraps the entire request closure with one automatic retry on
    // transient connection errors (keep-alive connections can be silently closed
    // by the server just as the client tries to reuse them).
    if has_http_fixtures {
        let _ = writeln!(out, "HttpClient _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out);
        let _ = writeln!(out, "var _lock = Future<void>.value();");
        let _ = writeln!(out);
        let _ = writeln!(out, "Future<T> _serialized<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  final current = _lock;");
        let _ = writeln!(out, "  final next = Completer<void>();");
        let _ = writeln!(out, "  _lock = next.future;");
        let _ = writeln!(out, "  try {{");
        let _ = writeln!(out, "    await current;");
        let _ = writeln!(out, "    return await fn();");
        let _ = writeln!(out, "  }} finally {{");
        let _ = writeln!(out, "    next.complete();");
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
        // The `fn` here should be the full request closure — on socket failure we
        // recreate the HttpClient (drops old pooled connections) and retry once.
        let _ = writeln!(out, "Future<T> _withRetry<T>(Future<T> Function() fn) async {{");
        let _ = writeln!(out, "  try {{");
        let _ = writeln!(out, "    return await fn();");
        let _ = writeln!(out, "  }} on SocketException {{");
        let _ = writeln!(out, "    _httpClient.close(force: true);");
        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    return fn();");
        let _ = writeln!(out, "  }} on HttpException {{");
        let _ = writeln!(out, "    _httpClient.close(force: true);");
        let _ = writeln!(out, "    _httpClient = HttpClient()..maxConnectionsPerHost = 1;");
        let _ = writeln!(out, "    return fn();");
        let _ = writeln!(out, "  }}");
        let _ = writeln!(out, "}}");
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "// E2e tests for category: {category}");
    let _ = writeln!(out, "void main() {{");

    // Close the shared client after all tests in this file complete.
    if has_http_fixtures {
        let _ = writeln!(out, "  tearDownAll(() => _httpClient.close());");
        let _ = writeln!(out);
    }

    for fixture in fixtures {
        render_test_case(&mut out, fixture, e2e_config, lang);
    }

    let _ = writeln!(out, "}}");
    out
}

fn render_test_case(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig, lang: &str) {
    // HTTP fixtures: hit the mock server.
    if let Some(http) = &fixture.http {
        render_http_test_case(out, fixture, http);
        return;
    }

    // Non-HTTP fixtures: check if there is a dart-specific call override.
    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
    let call_overrides = call_config.overrides.get(lang);

    if call_overrides.is_none() {
        // No dart-specific call override — emit a skip stub.
        render_skip_stub(out, fixture);
        return;
    }

    // Has a dart call override — render a call-based test.
    let function_name = call_overrides
        .and_then(|o| o.function.as_ref())
        .cloned()
        .unwrap_or_else(|| call_config.function.clone());
    let result_var = &call_config.result_var;
    let description = escape_dart(&fixture.description);
    let is_async = call_config.r#async;

    if is_async {
        let _ = writeln!(out, "  test('{description}', () async {{");
    } else {
        let _ = writeln!(out, "  test('{description}', () {{");
    }

    if is_async {
        let _ = writeln!(out, "    final {result_var} = await {function_name}();");
    } else {
        let _ = writeln!(out, "    final {result_var} = {function_name}();");
    }

    let _ = writeln!(out, "  }});");
    let _ = writeln!(out);
}

/// Render an HTTP server test using `dart:io` `HttpClient` against MOCK_SERVER_URL.
///
/// The mock server registers each fixture at `/fixtures/<fixture_id>` and returns
/// the pre-canned response. Tests send the correct HTTP method and headers to that
/// endpoint.
///
/// Uses `dart:io` `HttpClient` directly (not `package:http`) with
/// `persistentConnection = false` on every request to avoid keep-alive connection
/// reuse issues: when tests run concurrently, stale pooled connections from previous
/// tests get reset by the mock server.
fn render_http_test_case(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
    let description = escape_dart(&fixture.description);
    let request = &http.request;
    let expected = &http.expected_response;
    let method = request.method.to_uppercase();
    let fixture_id = &fixture.id;
    let expected_status = expected.status_code;

    // Skip 101 Switching Protocols — dart:io HttpClient cannot handle protocol-switch responses.
    if expected_status == 101 {
        let _ = writeln!(out, "  test('{description}', () {{");
        let _ = writeln!(
            out,
            "    markTestSkipped('Skipped: Dart HttpClient cannot handle 101 Switching Protocols responses');"
        );
        let _ = writeln!(out, "  }});");
        let _ = writeln!(out);
        return;
    }

    // dart:io restricted headers (handled automatically by the HTTP stack).
    const DART_RESTRICTED_HEADERS: &[&str] = &["content-length", "host", "transfer-encoding"];

    // Determine effective content-type:
    // - If the fixture has an explicit Content-Type header, use that.
    // - Otherwise, if there's a body, default to application/json.
    let has_explicit_content_type = request.headers.keys().any(|k| k.to_lowercase() == "content-type");
    let effective_content_type = if has_explicit_content_type {
        request
            .headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == "content-type")
            .map(|(_, v)| v.as_str())
            .unwrap_or("application/json")
    } else if request.body.is_some() {
        request.content_type.as_deref().unwrap_or("application/json")
    } else {
        ""
    };

    let has_body = request.body.is_some();
    let escaped_method = escape_dart(&method);
    let is_redirect = expected_status / 100 == 3;

    let _ = writeln!(
        out,
        "  test('{description}', () => _serialized(() => _withRetry(() async {{"
    );
    let _ = writeln!(
        out,
        "    final baseUrl = Platform.environment['MOCK_SERVER_URL'] ?? 'http://localhost:8080';"
    );
    let _ = writeln!(out, "    final uri = Uri.parse('$baseUrl/fixtures/{fixture_id}');");

    // Use the shared client (keep-alive connection reuse with retry on failure).
    let _ = writeln!(
        out,
        "    final ioReq = await _httpClient.openUrl('{escaped_method}', uri);"
    );
    // Disable automatic redirect following for redirect tests.
    if is_redirect {
        let _ = writeln!(out, "    ioReq.followRedirects = false;");
    }

    // Set headers.
    if !effective_content_type.is_empty() {
        let escaped_ct = escape_dart(effective_content_type);
        let _ = writeln!(out, "    ioReq.headers.set('content-type', '{escaped_ct}');");
    }
    for (name, value) in &request.headers {
        if DART_RESTRICTED_HEADERS.contains(&name.to_lowercase().as_str()) {
            continue;
        }
        if name.to_lowercase() == "content-type" {
            continue; // Already handled above.
        }
        let escaped_name = escape_dart(&name.to_lowercase());
        let escaped_value = escape_dart(value);
        let _ = writeln!(out, "    ioReq.headers.set('{escaped_name}', '{escaped_value}');");
    }
    // Add cookies.
    if !request.cookies.is_empty() {
        let cookie_str: Vec<String> = request.cookies.iter().map(|(k, v)| format!("{k}={v}")).collect();
        let cookie_header = escape_dart(&cookie_str.join("; "));
        let _ = writeln!(out, "    ioReq.headers.set('cookie', '{cookie_header}');");
    }

    // Write body bytes if present (bypass charset-based encoding issues).
    if has_body {
        let json_str = serde_json::to_string(&request.body).unwrap_or_default();
        let escaped = escape_dart(&json_str);
        let _ = writeln!(out, "    final bodyBytes = utf8.encode('{escaped}');");
        let _ = writeln!(out, "    ioReq.add(bodyBytes);");
    }

    let _ = writeln!(out, "    final ioResp = await ioReq.close();");
    let _ = writeln!(
        out,
        "    expect(ioResp.statusCode, equals({expected_status}), reason: 'status code mismatch');"
    );

    // Always drain the response body to allow the server to cleanly close the connection.
    // This prevents RST packets that corrupt subsequent requests.
    let needs_body_read = !is_redirect && expected.body.is_some();
    let _ = writeln!(out, "    final bodyStr = await ioResp.transform(utf8.decoder).join();");

    // Assert body if expected (not for redirects — body is empty).
    if needs_body_read {
        if let Some(expected_body) = &expected.body {
            match expected_body {
                serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
                    let json_str = serde_json::to_string(expected_body).unwrap_or_default();
                    let escaped = escape_dart(&json_str);
                    let _ = writeln!(out, "    final bodyJson = jsonDecode(bodyStr);");
                    let _ = writeln!(out, "    final expectedJson = jsonDecode('{escaped}');");
                    let _ = writeln!(
                        out,
                        "    expect(bodyJson, equals(expectedJson), reason: 'body mismatch');"
                    );
                }
                serde_json::Value::String(s) => {
                    let escaped = escape_dart(s);
                    let _ = writeln!(
                        out,
                        "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                    );
                }
                other => {
                    let escaped = escape_dart(&other.to_string());
                    let _ = writeln!(
                        out,
                        "    expect(bodyStr.trim(), equals('{escaped}'), reason: 'body mismatch');"
                    );
                }
            }
        }
    }

    // Assert response headers if specified.
    for (name, value) in &expected.headers {
        if value == "<<absent>>" || value == "<<present>>" || value == "<<uuid>>" {
            continue;
        }
        // content-encoding is set by the real server's compression middleware
        // but the mock server doesn't compress bodies, so skip this assertion.
        if name.to_lowercase() == "content-encoding" {
            continue;
        }
        let escaped_name = escape_dart(&name.to_lowercase());
        let escaped_value = escape_dart(value);
        let _ = writeln!(
            out,
            "    expect(ioResp.headers.value('{escaped_name}'), contains('{escaped_value}'), reason: 'header {escaped_name} mismatch');"
        );
    }

    let _ = writeln!(out, "  }})));");
    let _ = writeln!(out);
}

/// Emit a compilable skip stub for non-HTTP fixtures without a dart call override.
fn render_skip_stub(out: &mut String, fixture: &Fixture) {
    let description = escape_dart(&fixture.description);
    let fixture_id = &fixture.id;
    let _ = writeln!(out, "  test('{description}', () {{");
    let _ = writeln!(
        out,
        "    markTestSkipped('TODO: implement Dart e2e test for fixture \\'{fixture_id}\\'');"
    );
    let _ = writeln!(out, "  }});");
    let _ = writeln!(out);
}

/// Escape a string for embedding in a Dart single-quoted string literal.
fn escape_dart(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('\'', "\\'")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
        .replace('$', "\\$")
}