team-ljyzipelo

공개
179줄5.2 KB
1using System.Security;
2using Zipelo.Core;
3
4namespace Zipelo.SecurityTests;
5
6internal static class Check
7{
8 public static void That(bool condition, string message)
9 {
10 if (!condition)
11 {
12 throw new InvalidOperationException(message);
13 }
14 }
15
16 public static void Equal<T>(T expected, T actual)
17 {
18 That(EqualityComparer<T>.Default.Equals(expected, actual), "기대 결과와 실제 결과가 다름");
19 }
20
21 public static T Throws<T>(Action action) where T : Exception
22 {
23 try
24 {
25 action();
26 }
27 catch (T exception)
28 {
29 return exception;
30 }
31
32 throw new InvalidOperationException("예상한 예외가 발생하지 않음");
33 }
34
35 public static async Task<T> ThrowsAsync<T>(Func<Task> action) where T : Exception
36 {
37 try
38 {
39 await action();
40 }
41 catch (T exception)
42 {
43 return exception;
44 }
45
46 throw new InvalidOperationException("예상한 비동기 예외가 발생하지 않음");
47 }
48}
49
50// 실제 압축 엔진을 대체하는 제품 코드가 아닌 코어 호출용 테스트 대역임.
51internal sealed class EngineStub(
52 Func<IReadOnlyList<Stream>, EngineContext, CancellationToken, Task> execute) : IArchiveEngine
53{
54 public int Calls { get; private set; }
55
56 public IReadOnlyCollection<EngineCapability> Capabilities { get; } = Enum
57 .GetValues<ArchiveAction>()
58 .Select(action => new EngineCapability("zip", action))
59 .ToArray();
60
61 public Task ExecuteAsync(
62 ArchiveAction action,
63 IReadOnlyList<Stream> inputs,
64 EngineContext context,
65 CancellationToken cancellationToken)
66 {
67 Calls++;
68 return execute(inputs, context, cancellationToken);
69 }
70}
71
72// 메모리에서 게시 여부만 관찰함. 파일시스템의 링크 방어를 구현하거나 입증하지 않음.
73internal sealed class RecordingOutput : IOutputTransaction
74{
75 public Dictionary<string, MemoryStream> Staged { get; } = new(StringComparer.Ordinal);
76 public Dictionary<string, byte[]> Published { get; } = new(StringComparer.Ordinal);
77 public ArchiveError? CreateError { get; init; }
78 public bool FailDispose { get; init; }
79 public bool Disposed { get; private set; }
80 public int CreateCalls { get; private set; }
81 public int CommitCalls { get; private set; }
82 public int DisposeCalls { get; private set; }
83 public Action? BeforeCommit { get; init; }
84 public Action? AfterCommit { get; init; }
85 public Func<ValueTask>? BeforeDispose { get; init; }
86
87 public ValueTask<Stream> CreateFileAsync(
88 IReadOnlyList<string> relativeSegments,
89 CancellationToken cancellationToken)
90 {
91 cancellationToken.ThrowIfCancellationRequested();
92 CreateCalls++;
93 if (CreateError is { } error)
94 {
95 throw new ArchiveException(error);
96 }
97
98 var stream = new MemoryStream();
99 Staged.Add(string.Join('/', relativeSegments), stream);
100 return ValueTask.FromResult<Stream>(stream);
101 }
102
103 public ValueTask CommitAsync(CancellationToken cancellationToken)
104 {
105 BeforeCommit?.Invoke();
106 cancellationToken.ThrowIfCancellationRequested();
107 CommitCalls++;
108 foreach (var (name, stream) in Staged)
109 {
110 Published.Add(name, stream.ToArray());
111 }
112
113 AfterCommit?.Invoke();
114 return ValueTask.CompletedTask;
115 }
116
117 public async ValueTask DisposeAsync()
118 {
119 DisposeCalls++;
120 if (BeforeDispose is not null) { await BeforeDispose(); }
121 Disposed = true;
122 foreach (var stream in Staged.Values)
123 {
124 stream.Dispose();
125 }
126
127 if (FailDispose) { throw new IOException("테스트 정리 실패"); }
128 }
129}
130
131internal sealed class InlineProgress(Action<JobEvent> report) : IProgress<JobEvent>
132{
133 public void Report(JobEvent value) => report(value);
134}
135
136internal sealed class ManualTimeProvider : TimeProvider
137{
138 private long timestamp;
139
140 public override long TimestampFrequency => TimeSpan.TicksPerSecond;
141 public override long GetTimestamp() => timestamp;
142 public void Advance(TimeSpan duration) => timestamp += duration.Ticks;
143}
144
145internal sealed class ChunkedStream(byte[] bytes, Action? afterRead = null) : MemoryStream(bytes, false)
146{
147 public override ValueTask<int> ReadAsync(
148 Memory<byte> buffer,
149 CancellationToken cancellationToken = default)
150 {
151 cancellationToken.ThrowIfCancellationRequested();
152 var count = Read(buffer.Span[..Math.Min(buffer.Length, 1)]);
153 if (count != 0)
154 {
155 afterRead?.Invoke();
156 }
157
158 return ValueTask.FromResult(count);
159 }
160}
161
162internal static class TestSecrets
163{
164 public static SecureString Create()
165 {
166 var value = new SecureString();
167 foreach (var character in "테스트 암호! 123")
168 {
169 value.AppendChar(character);
170 }
171
172 value.MakeReadOnly();
173 return value;
174 }
175
176 public static ValueTask<SecureString?> None(
177 PasswordChallenge challenge,
178 CancellationToken cancellationToken) => ValueTask.FromResult<SecureString?>(null);
179}