caesar_cipher_enc_dec 1.0.10

can easily use caesar cipher
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! # CLI Output and Input Tests
//!
//! Tests for CLI helper functions including file I/O with improved error messages.
//!
//! ## テスト観点表(等価分割・境界値)
//!
//! | テスト観点                       | 分類     | 期待値                                |
//! |----------------------------------|----------|---------------------------------------|
//! | 存在しないファイル読込           | 異常系   | エラーメッセージにファイルパス含む    |
//! | text+file同時指定                | 異常系   | clap が即エラーを返す                 |
//! | テキスト引数のみ指定             | 正常系   | テキストがそのまま返る                |
//! | ファイルから正常読込             | 正常系   | ファイル内容が返る                    |
//! | 空ファイル読込                   | 境界値   | 空文字列返却                          |
//! | ファイルへの正常出力             | 正常系   | ファイルに正しく書き込まれる          |
//! | 大きなテキストの出力             | 境界値   | 正常に書き込まれる                    |
//! | 特殊文字を含むテキストの出力     | 正常系   | そのまま書き込まれる                  |
//! | 存在しないディレクトリへの出力   | 異常系   | エラー返却                            |
//! | 存在しないファイルのエラーメッセージ検証 | 異常系 | パスが含まれること              |
//! | Unicode テキストのファイル読み書き | 正常系 | UTF-8が保持される                    |
//! | 空テキスト引数                   | 境界値   | 空文字列がそのまま返る                |

use std::fs;
use std::io::Write;
use tempfile::{NamedTempFile, TempDir};

// Note: get_input_text and output_result are private functions in cli module.
// We test them indirectly through the CLI binary or test the public interface.
// For direct testing, we use the test module within cli.rs.
// Here we test the CLI binary behavior via process execution.

// =============================================================================
// CLI binary integration tests
// =============================================================================

#[test]
fn test_cli_encrypt_with_text_arg() {
    // Given: CLI with encrypt command and text argument
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "encrypt", "--text", "Hello", "--shift", "3"])
        .output()
        .expect("Failed to execute CLI");

    // When: Command executes
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output contains encrypted text
    assert!(
        stdout.contains("Khoor"),
        "Expected 'Khoor' in output, got: {}",
        stdout
    );
}

#[test]
fn test_cli_encrypt_stdin_matches_text_arg_for_surrounding_spaces() {
    use std::io::Write;
    use std::process::{Command, Stdio};

    // Given: --text with surrounding spaces
    let text_arg_output = Command::new("cargo")
        .args([
            "run",
            "--",
            "encrypt",
            "--text",
            "  Hello  ",
            "--shift",
            "3",
        ])
        .output()
        .expect("Failed to execute CLI with --text");
    assert!(text_arg_output.status.success());
    let text_arg_line = String::from_utf8_lossy(&text_arg_output.stdout)
        .lines()
        .last()
        .unwrap_or("")
        .to_string();

    // When: the same text is provided via stdin
    let mut stdin_child = Command::new("cargo")
        .args(["run", "--", "encrypt", "--shift", "3"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn CLI for stdin");
    stdin_child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(b"  Hello  \n")
        .unwrap();
    let stdin_output = stdin_child.wait_with_output().unwrap();
    assert!(stdin_output.status.success());
    let stdin_stdout = String::from_utf8_lossy(&stdin_output.stdout);
    let stdin_line = stdin_stdout
        .strip_prefix("Enter text: ")
        .unwrap_or(&stdin_stdout)
        .trim_end_matches(['\n', '\r'])
        .to_string();

    // Then: ciphertext matches and surrounding spaces are preserved
    assert_eq!(
        text_arg_line, stdin_line,
        "--text line: {:?}, stdin ciphertext: {:?}, full stdin stdout: {:?}",
        text_arg_line, stdin_line, stdin_stdout
    );
    assert_eq!(stdin_line, "  Khoor  ");
}

#[test]
fn test_cli_decrypt_with_text_arg() {
    // Given: CLI with decrypt command and text argument
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "decrypt", "--text", "Khoor", "--shift", "3"])
        .output()
        .expect("Failed to execute CLI");

    // When: Command executes
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output contains decrypted text
    assert!(
        stdout.contains("Hello"),
        "Expected 'Hello' in output, got: {}",
        stdout
    );
}

#[test]
fn test_cli_encrypt_from_file() {
    // Given: A temporary file with text content
    let mut temp_file = NamedTempFile::new().unwrap();
    write!(temp_file, "Hello World").unwrap();
    let file_path = temp_file.path().to_string_lossy().to_string();

    // When: CLI reads from file
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "encrypt", "--file", &file_path, "--shift", "3"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output contains encrypted text
    assert!(
        stdout.contains("Khoor Zruog"),
        "Expected 'Khoor Zruog' in output, got: {}",
        stdout
    );
}

#[test]
fn test_cli_encrypt_output_to_file() {
    // Given: A temporary output file path
    let temp_dir = TempDir::new().unwrap();
    let output_path = temp_dir.path().join("output.txt");
    let output_path_str = output_path.to_string_lossy().to_string();

    // When: CLI writes to file
    let result = std::process::Command::new("cargo")
        .args([
            "run",
            "--",
            "encrypt",
            "--text",
            "Hello",
            "--shift",
            "3",
            "--output",
            &output_path_str,
        ])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&result.stdout);

    // Then: File contains encrypted text and message includes path
    let content = fs::read_to_string(&output_path).unwrap();
    assert_eq!(content, "Khoor");
    assert!(
        stdout.contains(&output_path_str),
        "Output message should contain file path '{}', got: {}",
        output_path_str,
        stdout
    );
}

// =============================================================================
// Error handling tests (異常系)
// =============================================================================

#[test]
fn test_cli_nonexistent_file_error_contains_path() {
    // Given: A path to a nonexistent file
    let nonexistent_path = "/tmp/nonexistent_caesar_test_file_12345.txt";

    // When: CLI tries to read from nonexistent file
    let output = std::process::Command::new("cargo")
        .args([
            "run",
            "--",
            "encrypt",
            "--file",
            nonexistent_path,
            "--shift",
            "3",
        ])
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Then: Error message contains the file path
    assert!(
        stderr.contains(nonexistent_path),
        "Error message should contain file path '{}', got: {}",
        nonexistent_path,
        stderr
    );
}

#[test]
fn test_cli_both_text_and_file_error() {
    // Given: Both text and file arguments provided
    let mut temp_file = NamedTempFile::new().unwrap();
    write!(temp_file, "content").unwrap();
    let file_path = temp_file.path().to_string_lossy().to_string();

    // When: CLI receives both arguments
    let output = std::process::Command::new("cargo")
        .args([
            "run", "--", "encrypt", "--text", "Hello", "--file", &file_path, "--shift", "3",
        ])
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Then: clap validates conflict before application logic
    assert!(
        !output.status.success(),
        "Command should fail on clap validation"
    );
    assert!(
        stderr.contains("cannot be used with") || stderr.contains("conflicts with"),
        "Error should mention clap conflict, got: {}",
        stderr
    );
}

#[test]
fn test_cli_brute_force_both_text_and_file_error() {
    // Given: Both text and file arguments provided for brute-force
    let mut temp_file = NamedTempFile::new().unwrap();
    write!(temp_file, "content").unwrap();
    let file_path = temp_file.path().to_string_lossy().to_string();

    // When: CLI receives both arguments
    let output = std::process::Command::new("cargo")
        .args([
            "run",
            "--",
            "brute-force",
            "--text",
            "Khoor",
            "--file",
            &file_path,
        ])
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Then: clap validates conflict before application logic
    assert!(
        !output.status.success(),
        "Command should fail on clap validation"
    );
    assert!(
        stderr.contains("cannot be used with") || stderr.contains("conflicts with"),
        "Error should mention clap conflict, got: {}",
        stderr
    );
}

// =============================================================================
// Boundary value tests (境界値)
// =============================================================================

#[test]
fn test_cli_encrypt_empty_file() {
    // Given: An empty temporary file
    let temp_file = NamedTempFile::new().unwrap();
    let file_path = temp_file.path().to_string_lossy().to_string();

    // When: CLI reads from empty file
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "encrypt", "--file", &file_path, "--shift", "3"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output should be empty (just a newline from println)
    assert!(
        stdout.trim().is_empty(),
        "Expected empty output for empty file, got: '{}'",
        stdout.trim()
    );
}

#[test]
fn test_cli_brute_force_output() {
    // Given: An encrypted text
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "brute-force", "--text", "Khoor"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output contains brute force header and shift 3 shows "Hello"
    assert!(
        stdout.contains("Brute Force Decryption"),
        "Should contain brute force header, got: {}",
        stdout
    );
    assert!(
        stdout.contains("Shift  3: Hello"),
        "Shift 3 should decrypt to 'Hello', got: {}",
        stdout
    );
}

#[test]
fn test_cli_version_matches_cargo_toml() {
    // Given: CLI with --version flag
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "--version"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Version should match Cargo.toml (dynamically read at compile time)
    let expected_version = env!("CARGO_PKG_VERSION");
    assert!(
        stdout.contains(expected_version),
        "CLI version should be {} from Cargo.toml, got: {}",
        expected_version,
        stdout
    );
}

#[test]
fn test_cli_encrypt_unicode_text() {
    // Given: Unicode text (Japanese + English mix)
    let output = std::process::Command::new("cargo")
        .args([
            "run",
            "--",
            "encrypt",
            "--text",
            "Hello世界",
            "--shift",
            "3",
        ])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Only English letters shifted, Japanese preserved
    assert!(
        stdout.contains("Khoor世界"),
        "Expected 'Khoor世界' in output, got: {}",
        stdout
    );
}

#[test]
fn test_cli_safe_mode_invalid_shift_error() {
    // Given: CLI with safe mode and invalid shift value
    let output = std::process::Command::new("cargo")
        .args([
            "run", "--", "encrypt", "--text", "Hello", "--shift", "30", "--safe",
        ])
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Then: Error message about invalid shift
    assert!(
        stderr.contains("Invalid shift value") || stderr.contains("out of range"),
        "Should show shift validation error, got: {}",
        stderr
    );
}

#[test]
fn test_cli_safe_mode_empty_text_from_file() {
    // Given: Empty file with safe mode
    let temp_file = NamedTempFile::new().unwrap();
    let file_path = temp_file.path().to_string_lossy().to_string();

    // When: CLI reads empty file in safe mode
    let output = std::process::Command::new("cargo")
        .args([
            "run", "--", "encrypt", "--file", &file_path, "--shift", "3", "--safe",
        ])
        .output()
        .expect("Failed to execute CLI");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Then: Error about empty text
    assert!(
        stderr.contains("empty"),
        "Should show empty text error, got: {}",
        stderr
    );
}

// =============================================================================
// Brute force shift=0 tests
// =============================================================================

#[test]
fn test_cli_brute_force_includes_shift_zero() {
    // Given: An encrypted text
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "brute-force", "--text", "Khoor"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Output contains shift 0
    assert!(
        stdout.contains("Shift  0:"),
        "Brute force output should include shift 0, got: {}",
        stdout
    );
}

#[test]
fn test_cli_brute_force_shift_zero_is_original() {
    // Given: A known encrypted text "Khoor"
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "brute-force", "--text", "Khoor"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Shift 0 shows the original text unchanged
    assert!(
        stdout.contains("Shift  0: Khoor"),
        "Shift 0 should show original text 'Khoor', got: {}",
        stdout
    );
}

// =============================================================================
// Help text tests
// =============================================================================

#[test]
fn test_cli_encrypt_help_shows_correct_shift_description() {
    // Given: CLI with encrypt --help
    let output = std::process::Command::new("cargo")
        .args(["run", "--", "encrypt", "--help"])
        .output()
        .expect("Failed to execute CLI");

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Then: Help text should describe shift range accurately
    assert!(
        stdout.contains("safe mode: -25 to 25"),
        "Help text should mention safe mode range, got: {}",
        stdout
    );
    assert!(
        !stdout.contains("Shift value (1-25)"),
        "Help text should NOT contain outdated '1-25' range, got: {}",
        stdout
    );
}