200 lines
9 KiB
C#
200 lines
9 KiB
C#
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using VideoDownloader.Server;
|
|
|
|
namespace VideoDownloader.Tests.Server;
|
|
|
|
/// <summary>
|
|
/// E2E (M0): 실제 Kestrel 서버 기동 → 인증/페어링/큐 제어/라이브러리/스트리밍/웹 컴패니언 검증.
|
|
/// </summary>
|
|
public class RemoteServerE2ETests : IDisposable
|
|
{
|
|
private readonly string _libDir = Path.Combine(Path.GetTempPath(), $"vd_srv_{Guid.NewGuid():N}");
|
|
|
|
private sealed class FakeQueue : IQueueAdapter
|
|
{
|
|
public List<QueueItemDto> Items { get; } = new();
|
|
public List<string> Actions { get; } = new();
|
|
|
|
public Task<IReadOnlyList<QueueItemDto>> GetItemsAsync() => Task.FromResult<IReadOnlyList<QueueItemDto>>(Items);
|
|
public Task<string> AddAsync(string url, string? title)
|
|
{
|
|
var item = new QueueItemDto(Guid.NewGuid().ToString("N"), title ?? url, url, "대기", 0);
|
|
Items.Add(item);
|
|
Changed?.Invoke();
|
|
return Task.FromResult(item.Id);
|
|
}
|
|
public Task PauseAsync(string id) { Actions.Add($"pause:{id}"); return Task.CompletedTask; }
|
|
public Task ResumeAsync(string id) { Actions.Add($"resume:{id}"); return Task.CompletedTask; }
|
|
public Task CancelAsync(string id) { Actions.Add($"cancel:{id}"); return Task.CompletedTask; }
|
|
|
|
public event Action? Changed;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task 서버_전_API_E2E_인증_큐_라이브러리_스트리밍_웹컴패니언()
|
|
{
|
|
Directory.CreateDirectory(_libDir);
|
|
var mediaPath = Path.Combine(_libDir, "sample.mp4");
|
|
File.WriteAllBytes(mediaPath, new byte[256 * 1024]); // 256KB 가짜 미디어
|
|
|
|
var queue = new FakeQueue();
|
|
await using var server = await ServerHost.StartAsync(new ServerOptions
|
|
{
|
|
Port = 0, // 사용 가능한 포트 자동 할당
|
|
Token = "test-token-123",
|
|
LibraryFolder = _libDir,
|
|
Queue = queue,
|
|
});
|
|
|
|
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
|
|
|
// 1) 인증 없으면 401
|
|
var anon = await http.GetAsync("/api/queue");
|
|
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, anon.StatusCode);
|
|
|
|
// 2) 틀린 토큰도 401
|
|
using var bad = new HttpRequestMessage(HttpMethod.Get, "/api/queue");
|
|
bad.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "wrong");
|
|
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.SendAsync(bad)).StatusCode);
|
|
|
|
// 3) 페어링(올바른 토큰)
|
|
var pair = await http.PostAsJsonAsync("/api/pair", new { token = "test-token-123", device = "E2E-Phone" });
|
|
Assert.True(pair.IsSuccessStatusCode);
|
|
|
|
// 4) 큐: URL 추가 → 목록 조회
|
|
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "test-token-123");
|
|
var add = await http.PostAsJsonAsync("/api/queue", new { url = "https://x.test/v.mp4", title = "E2E 영상" });
|
|
Assert.True(add.IsSuccessStatusCode);
|
|
var items = await http.GetFromJsonAsync<List<QueueItemDto>>("/api/queue");
|
|
Assert.NotNull(items);
|
|
Assert.Single(items!);
|
|
Assert.Equal("E2E 영상", items![0].Title);
|
|
var id = items[0].Id;
|
|
|
|
// 5) 큐 제어 위임
|
|
Assert.True((await http.PostAsync($"/api/queue/{id}/pause", null)).IsSuccessStatusCode);
|
|
Assert.True((await http.PostAsync($"/api/queue/{id}/resume", null)).IsSuccessStatusCode);
|
|
Assert.True((await http.PostAsync($"/api/queue/{id}/cancel", null)).IsSuccessStatusCode);
|
|
Assert.Equal(new[] { $"pause:{id}", $"resume:{id}", $"cancel:{id}" }, queue.Actions);
|
|
|
|
// 6) 라이브러리
|
|
var lib = await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library");
|
|
Assert.NotNull(lib);
|
|
Assert.Single(lib!);
|
|
Assert.Equal("sample.mp4", lib![0].FileName);
|
|
|
|
// 7) 스트리밍: Range 요청 → 206 부분 응답
|
|
using var range = new HttpRequestMessage(HttpMethod.Get, $"/stream/{lib[0].Id}");
|
|
range.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(0, 1023);
|
|
range.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "test-token-123");
|
|
var partial = await http.SendAsync(range);
|
|
Assert.Equal(System.Net.HttpStatusCode.PartialContent, partial.StatusCode);
|
|
var bytes = await partial.Content.ReadAsByteArrayAsync();
|
|
Assert.Equal(1024, bytes.Length);
|
|
|
|
// 8) 파일 다운로드: 전체 길이
|
|
var file = await http.GetByteArrayAsync($"/file/{lib[0].Id}");
|
|
Assert.Equal(256 * 1024, file.Length);
|
|
|
|
// 9) 웹 컴패니언 페이지 제공
|
|
var page = await http.GetStringAsync("/");
|
|
Assert.Contains("VideoDownloader", page);
|
|
Assert.Contains("api/queue", page); // 페이지가 API 를 호출하는 스크립트 포함
|
|
}
|
|
|
|
[Fact]
|
|
public async Task 이어보기_위치_동기화_E2E_저장_조회_재시작_유지()
|
|
{
|
|
Directory.CreateDirectory(_libDir);
|
|
File.WriteAllBytes(Path.Combine(_libDir, "sample.mp4"), new byte[1024]);
|
|
|
|
var queue = new FakeQueue();
|
|
var opts = new ServerOptions
|
|
{
|
|
Port = 0,
|
|
Token = "pos-token",
|
|
LibraryFolder = _libDir,
|
|
Queue = queue,
|
|
};
|
|
await using var server = await ServerHost.StartAsync(opts);
|
|
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
|
|
|
// 1) 익명 401
|
|
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.GetAsync("/api/position/abc")).StatusCode);
|
|
|
|
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "pos-token");
|
|
var lib = (await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library"))!;
|
|
var id = lib[0].Id;
|
|
|
|
// 2) 미저장 기본값 0
|
|
var before = await http.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
|
Assert.NotNull(before);
|
|
Assert.Equal(0, before!.PositionSec);
|
|
|
|
// 3) 저장 → 조회 라운드트립
|
|
var save = await http.PostAsJsonAsync($"/api/position/{id}", new PositionDto(93.5));
|
|
Assert.True(save.IsSuccessStatusCode);
|
|
var after = await http.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
|
Assert.Equal(93.5, after!.PositionSec);
|
|
|
|
// 4) 존재하지 않는 항목도 기본값 0 (섹션 파일 무손상)
|
|
var unknown = await http.GetFromJsonAsync<PositionDto>("/api/position/no-such-id");
|
|
Assert.Equal(0, unknown!.PositionSec);
|
|
|
|
// 5) 서버 재시작 후에도 유지(파일 영속)
|
|
await server.DisposeAsync();
|
|
await using var server2 = await ServerHost.StartAsync(new ServerOptions
|
|
{
|
|
Port = 0, Token = "pos-token", LibraryFolder = _libDir, Queue = queue,
|
|
});
|
|
using var http2 = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server2.Port}") };
|
|
http2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "pos-token");
|
|
var persisted = await http2.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
|
Assert.Equal(93.5, persisted!.PositionSec);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task 썸네일_API_E2E_생성_캐시_404()
|
|
{
|
|
Directory.CreateDirectory(_libDir);
|
|
var mediaPath = Path.Combine(_libDir, "clip.mp4");
|
|
File.WriteAllBytes(mediaPath, new byte[2048]);
|
|
|
|
// 가짜 ffmpeg: 출력 경로에 JPEG 생성
|
|
var fake = new Tests.Platform.FakeProcessRunner
|
|
{
|
|
Behavior = (spec, _, _) =>
|
|
{
|
|
File.WriteAllBytes(spec.Args[^1], new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x01 });
|
|
return Task.FromResult(new VideoDownloader.Core.Platform.ProcessResult(0, "", ""));
|
|
},
|
|
};
|
|
|
|
await using var server = await ServerHost.StartAsync(new ServerOptions
|
|
{
|
|
Port = 0, Token = "thumb-token", LibraryFolder = _libDir,
|
|
Queue = new FakeQueue(),
|
|
Thumbnailer = new Thumbnailer(fake),
|
|
});
|
|
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
|
|
|
// 1) 익명 401
|
|
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.GetAsync("/api/library/xyz/thumb")).StatusCode);
|
|
|
|
// 2) 없는 항목 404
|
|
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "thumb-token");
|
|
Assert.Equal(System.Net.HttpStatusCode.NotFound, (await http.GetAsync("/api/library/xyz/thumb")).StatusCode);
|
|
|
|
// 3) 실제 항목 → 200 + JPEG 매직
|
|
var lib = (await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library"))!;
|
|
var thumb = await http.GetByteArrayAsync($"/api/library/{lib[0].Id}/thumb");
|
|
Assert.True(thumb.Length >= 2 && thumb[0] == 0xFF && thumb[1] == 0xD8, "JPEG 매직 바이트");
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
try { Directory.Delete(_libDir, true); } catch { }
|
|
}
|
|
}
|