braze-sync 0.9.0

GitOps CLI for managing Braze configuration as code
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
//! Integration tests for `braze-sync export` (Catalog Schema).
//!
//! Each test stands up a wiremock server, writes a temporary
//! braze-sync.config.yaml that points the api_endpoint at the mock,
//! invokes the real binary via assert_cmd, and asserts on the resulting
//! filesystem state and exit code.
//!
//! Tests use `flavor = "multi_thread"` so wiremock can serve HTTP
//! requests on a worker thread while the test thread is parked in
//! `spawn_blocking` waiting on the subprocess. Single-threaded
//! `#[tokio::test]` would deadlock because the blocking subprocess wait
//! would hold the only worker.

mod common;

use assert_cmd::Command;
use common::write_config;
use serde_json::json;
use std::fs;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_catalog_schemas_writes_files_and_exits_zero() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "catalogs": [
                {
                    "name": "cardiology",
                    "description": "Cardiology catalog",
                    "fields": [
                        {"name": "id", "type": "string"},
                        {"name": "score", "type": "number"}
                    ]
                },
                {
                    "name": "dermatology",
                    "fields": [
                        {"name": "id", "type": "string"}
                    ]
                }
            ]
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "catalog_schema"])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let cardiology = tmp_path.join("catalogs/cardiology/schema.yaml");
    let dermatology = tmp_path.join("catalogs/dermatology/schema.yaml");
    assert!(cardiology.exists(), "cardiology schema should exist");
    assert!(dermatology.exists(), "dermatology schema should exist");

    let content = fs::read_to_string(&cardiology).unwrap();
    assert!(content.contains("name: cardiology"));
    assert!(content.contains("- name: id"));
    assert!(content.contains("- name: score"));
    assert!(content.starts_with("# Generated by braze-sync."));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_with_name_filter_uses_get_endpoint() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/catalogs/cardiology"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "catalogs": [
                {"name": "cardiology", "fields": [{"name": "id", "type": "string"}]}
            ]
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args([
                "export",
                "--resource",
                "catalog_schema",
                "--name",
                "cardiology",
            ])
            .assert()
            .success();
    })
    .await
    .unwrap();

    assert!(
        tmp_path.join("catalogs/cardiology/schema.yaml").exists(),
        "cardiology schema should exist after --name export"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unauthorized_braze_response_yields_exit_code_4() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(401).set_body_string("invalid api key"))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "wrong-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "catalog_schema"])
            .assert()
            .failure()
            .code(4);
    })
    .await
    .unwrap();
}

#[test]
fn missing_config_file_yields_exit_code_3() {
    Command::cargo_bin("braze-sync")
        .unwrap()
        .env("BRAZE_API_KEY", "anything")
        .args(["--config", "/nonexistent/braze-sync.config.yaml"])
        .args(["export"])
        .assert()
        .failure()
        .code(3);
}

#[test]
fn invalid_args_name_without_resource_yields_exit_code_3() {
    // clap rejects --name without --resource at parse time. We expect
    // exit 3 (config / argument error).
    Command::cargo_bin("braze-sync")
        .unwrap()
        .args(["export", "--name", "x"])
        .assert()
        .failure()
        .code(3);
}

#[test]
fn help_flag_exits_zero() {
    Command::cargo_bin("braze-sync")
        .unwrap()
        .arg("--help")
        .assert()
        .success();
}

// =====================================================================
// Content Block (v0.2.0)
// =====================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_content_blocks_writes_liquid_files() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_blocks": [
                {"content_block_id": "id-promo", "name": "promo"},
                {"content_block_id": "id-header", "name": "shared_header"}
            ],
            "message": "success"
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/info"))
        .and(wiremock::matchers::query_param(
            "content_block_id",
            "id-promo",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_block_id": "id-promo",
            "name": "promo",
            "description": "Promo banner",
            "content": "Hello {{ user.${first_name} }}",
            "tags": ["pr"],
            "message": "success"
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/info"))
        .and(wiremock::matchers::query_param(
            "content_block_id",
            "id-header",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_block_id": "id-header",
            "name": "shared_header",
            "content": "<header>shared</header>",
            "tags": [],
            "message": "success"
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "content_block"])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let promo = tmp_path.join("content_blocks/promo.liquid");
    let header = tmp_path.join("content_blocks/shared_header.liquid");
    assert!(promo.exists(), "promo.liquid should exist");
    assert!(header.exists(), "shared_header.liquid should exist");

    let promo_text = fs::read_to_string(&promo).unwrap();
    assert!(promo_text.starts_with("---\n"));
    assert!(promo_text.contains("name: promo"));
    assert!(promo_text.contains("description: Promo banner"));
    assert!(promo_text.contains("Hello {{ user.${first_name} }}"));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_content_block_with_name_filter_only_fetches_matching_info() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_blocks": [
                {"content_block_id": "id-promo", "name": "promo"},
                {"content_block_id": "id-header", "name": "shared_header"}
            ]
        })))
        .mount(&server)
        .await;
    // Only the matching info call should fire; the non-matching one
    // would hit this 500 mock and fail the test.
    Mock::given(method("GET"))
        .and(path("/content_blocks/info"))
        .and(wiremock::matchers::query_param(
            "content_block_id",
            "id-header",
        ))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/info"))
        .and(wiremock::matchers::query_param(
            "content_block_id",
            "id-promo",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "name": "promo",
            "content": "x",
            "tags": []
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "content_block", "--name", "promo"])
            .assert()
            .success();
    })
    .await
    .unwrap();

    assert!(tmp_path.join("content_blocks/promo.liquid").exists());
    assert!(!tmp_path
        .join("content_blocks/shared_header.liquid")
        .exists());
}

// =====================================================================
// Email Template (v0.3.0)
// =====================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_email_templates_writes_directory_layout() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/templates/email/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "templates": [
                {"email_template_id": "id-welcome", "template_name": "welcome"}
            ]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/templates/email/info"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "template_name": "welcome",
            "subject": "Welcome to our service",
            "body": "<p>Hello</p>",
            "plaintext_body": "Hello",
            "description": "Welcome email",
            "preheader": "Get started",
            "tags": ["onboarding"],
            "message": "success"
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "email_template"])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let et_dir = tmp_path.join("email_templates/welcome");
    assert!(et_dir.join("template.yaml").exists());
    assert!(et_dir.join("body.html").exists());
    assert!(et_dir.join("body.txt").exists());

    let yaml = fs::read_to_string(et_dir.join("template.yaml")).unwrap();
    assert!(yaml.contains("name: welcome"));
    assert!(yaml.contains("subject: Welcome to our service"));
    let html = fs::read_to_string(et_dir.join("body.html")).unwrap();
    assert_eq!(html, "<p>Hello</p>");
    let txt = fs::read_to_string(et_dir.join("body.txt")).unwrap();
    assert_eq!(txt, "Hello");
}

// =====================================================================
// Custom Attribute
// =====================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn export_custom_attributes_writes_registry_yaml() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/custom_attributes"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "attributes": [
                {
                    "name": "last_visit_date",
                    "data_type": "date",
                    "description": "Most recent visit",
                    "status": "Active"
                },
                {
                    "name": "preferred_clinic_id",
                    "data_type": "string",
                    "description": "User's preferred clinic",
                    "status": "Active"
                },
                {
                    "name": "legacy_segment",
                    "data_type": "string",
                    "status": "Blocklisted"
                }
            ],
            "message": "success"
        })))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let tmp_path = tmp.path().to_path_buf();

    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["export", "--resource", "custom_attribute"])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let registry_path = tmp_path.join("custom_attributes/registry.yaml");
    assert!(registry_path.exists(), "registry.yaml should exist");
    let content = fs::read_to_string(&registry_path).unwrap();
    assert!(content.contains("last_visit_date"));
    assert!(content.contains("preferred_clinic_id"));
    assert!(content.contains("legacy_segment"));
    assert!(content.contains("deprecated: true"));
    // Verify sorted order (last_visit_date < legacy_segment < preferred_clinic_id)
    let pos_last = content.find("last_visit_date").unwrap();
    let pos_legacy = content.find("legacy_segment").unwrap();
    let pos_pref = content.find("preferred_clinic_id").unwrap();
    assert!(pos_last < pos_legacy);
    assert!(pos_legacy < pos_pref);
}