DocSpace-buildtools/products/ASC.Files/Tests/BaseFilesTests.cs

290 lines
10 KiB
C#
Raw Normal View History

2022-04-22 13:24:54 +00:00
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
namespace ASC.Files.Tests;
class FilesApplication : WebApplicationFactory<Program>
2020-12-29 16:45:18 +00:00
{
2022-04-22 13:24:54 +00:00
private readonly Dictionary<string, string> _args;
public FilesApplication(Dictionary<string, string> args)
2022-03-18 15:44:00 +00:00
{
2022-04-22 13:24:54 +00:00
_args = args;
}
2022-03-18 15:44:00 +00:00
2022-04-22 13:24:54 +00:00
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
foreach (var s in _args)
2022-03-18 15:44:00 +00:00
{
2022-04-22 13:24:54 +00:00
builder.UseSetting(s.Key, s.Value);
2022-03-18 15:44:00 +00:00
}
2022-04-22 13:24:54 +00:00
builder.ConfigureAppConfiguration((context, a) =>
2022-03-18 15:44:00 +00:00
{
2022-04-22 13:24:54 +00:00
(a.Sources[0] as ChainedConfigurationSource).Configuration["pathToConf"] = a.Build()["pathToConf"];
});
builder.ConfigureServices(services =>
{
var DIHelper = new ASC.Common.DIHelper();
DIHelper.Configure(services);
2022-04-25 08:09:51 +00:00
foreach (var a in Assembly.Load("ASC.Files").GetTypes().Where(r => r.IsAssignableTo<ControllerBase>() && !r.IsAbstract))
2022-03-18 15:44:00 +00:00
{
2022-04-22 13:24:54 +00:00
DIHelper.TryAdd(a);
2022-03-18 15:44:00 +00:00
}
2022-04-22 13:24:54 +00:00
});
2022-03-18 15:44:00 +00:00
2022-04-22 13:24:54 +00:00
base.ConfigureWebHost(builder);
}
}
2022-03-18 15:44:00 +00:00
2022-04-22 13:24:54 +00:00
[SetUpFixture]
public class MySetUpClass
{
protected IServiceScope Scope { get; set; }
[OneTimeSetUp]
public void CreateDb()
{
2022-05-13 15:08:30 +00:00
var host = new FilesApplication(new Dictionary<string, string>
2022-03-18 15:44:00 +00:00
{
2022-04-22 13:24:54 +00:00
{ "pathToConf", Path.Combine("..","..", "..", "config") },
{ "ConnectionStrings:default:connectionString", BaseFilesTests.TestConnection },
{ "migration:enabled", "true" },
{ "core:products:folder", Path.Combine("..", "..", "..", "products") },
2022-05-13 15:08:30 +00:00
{ "web:hub:internal", "" }
2022-04-22 13:24:54 +00:00
})
2022-05-13 15:08:30 +00:00
.WithWebHostBuilder(builder =>
{
});
2022-03-18 15:44:00 +00:00
2022-04-22 13:24:54 +00:00
Migrate(host.Services);
Migrate(host.Services, Assembly.GetExecutingAssembly().GetName().Name);
Scope = host.Services.CreateScope();
2022-05-13 15:08:30 +00:00
//var tenantManager = Scope.ServiceProvider.GetService<TenantManager>();
//var tenant = tenantManager.GetTenant(1);
//tenantManager.SetCurrentTenant(tenant);
2022-03-18 15:44:00 +00:00
}
2022-04-22 13:24:54 +00:00
[OneTimeTearDown]
public void DropDb()
2020-12-29 16:45:18 +00:00
{
2022-04-25 08:09:51 +00:00
var context = Scope.ServiceProvider.GetService<DbContextManager<UserDbContext>>();
2022-04-22 13:24:54 +00:00
context.Value.Database.EnsureDeleted();
2022-05-13 15:08:30 +00:00
try
{
2022-07-08 08:46:34 +00:00
Directory.Delete(Path.Combine(Path.Combine("..", "..", "..", "..", "..", "..", "Data.Test")), true);
2022-05-13 15:08:30 +00:00
}
catch { }
2022-04-22 13:24:54 +00:00
}
2020-12-21 23:27:10 +00:00
2022-04-22 13:24:54 +00:00
private void Migrate(IServiceProvider serviceProvider, string testAssembly = null)
{
using var scope = serviceProvider.CreateScope();
2020-12-21 23:27:10 +00:00
2022-04-22 13:24:54 +00:00
if (!string.IsNullOrEmpty(testAssembly))
2020-12-29 16:45:18 +00:00
{
2022-04-22 13:24:54 +00:00
var configuration = scope.ServiceProvider.GetService<IConfiguration>();
configuration["testAssembly"] = testAssembly;
2020-12-29 16:45:18 +00:00
}
2022-04-22 13:24:54 +00:00
using var db = scope.ServiceProvider.GetService<DbContextManager<UserDbContext>>();
db.Value.Migrate();
2022-04-25 08:09:51 +00:00
using var filesDb = scope.ServiceProvider.GetService<DbContextManager<Core.EF.FilesDbContext>>();
filesDb.Value.Migrate();
2020-12-29 16:45:18 +00:00
}
2022-04-22 13:24:54 +00:00
}
2020-12-29 16:45:18 +00:00
2022-06-17 07:17:17 +00:00
public partial class BaseFilesTests
{
2022-07-13 10:00:08 +00:00
private readonly JsonSerializerOptions _options;
protected UserManager _userManager;
2022-07-13 10:00:08 +00:00
private HttpClient _client;
2022-05-13 15:08:30 +00:00
private readonly string _baseAddress;
2022-06-17 07:17:17 +00:00
private string _cookie;
public static readonly string TestConnection = string.Format("Server=localhost;Database=onlyoffice_test.{0};User ID=root;Password=root;Pooling=true;Character Set=utf8;AutoEnlist=false;SSL Mode=none;AllowPublicKeyRetrieval=True", DateTime.Now.Ticks);
2022-05-13 15:08:30 +00:00
public BaseFilesTests()
{
_options = new JsonSerializerOptions()
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true
};
_options.Converters.Add(new ApiDateTimeConverter());
_options.Converters.Add(new FileEntryWrapperConverter());
_options.Converters.Add(new FileShareConverter());
_baseAddress = @$"http://localhost:{new Random().Next(5000, 6000)}/api/2.0/files/";
}
[OneTimeSetUp]
2022-06-17 07:17:17 +00:00
public async Task OneTimeSetup()
2022-04-22 13:24:54 +00:00
{
var host = new FilesApplication(new Dictionary<string, string>
{
{ "pathToConf", Path.Combine("..","..", "..", "config") },
{ "ConnectionStrings:default:connectionString", TestConnection },
{ "migration:enabled", "true" },
{ "web:hub:internal", "" },
{ "$STORAGE_ROOT", Path.Combine("..", "..", "..", "Data.Test") },
{ "log:dir", Path.Combine("..", "..", "..", "Logs", "Test") },
2022-04-22 13:24:54 +00:00
})
.WithWebHostBuilder(a => { });
2022-04-25 08:09:51 +00:00
_client = host.CreateClient(new WebApplicationFactoryClientOptions()
{
2022-05-13 15:08:30 +00:00
BaseAddress = new Uri(_baseAddress)
2022-04-25 08:09:51 +00:00
});
var scope = host.Services.CreateScope();
_userManager = scope.ServiceProvider.GetService<UserManager>();
2022-05-13 15:08:30 +00:00
var tenantManager = scope.ServiceProvider.GetService<TenantManager>();
var tenant = tenantManager.GetTenant(1);
tenantManager.SetCurrentTenant(tenant);
var securityContext = scope.ServiceProvider.GetService<SecurityContext>();
2022-06-17 07:17:17 +00:00
_cookie = securityContext.AuthenticateMe(tenant.OwnerId);
2022-06-17 07:17:17 +00:00
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _cookie);
2022-04-25 08:09:51 +00:00
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;");
2022-06-17 07:17:17 +00:00
await _client.GetAsync("/");
2022-04-22 13:24:54 +00:00
}
2022-04-22 13:24:54 +00:00
public BatchRequestDto GetBatchModel(string text)
{
var json = text;
2022-04-22 13:24:54 +00:00
var jsonDocument = JsonDocument.Parse(json);
var root = jsonDocument.RootElement;
var folderIds = root[0].GetProperty("folderIds").EnumerateArray().ToList();
var fileIds = root[1].GetProperty("fileIds").EnumerateArray().ToList();
var destFolderdId = root[2];
2022-04-22 13:24:54 +00:00
var batchModel = new BatchRequestDto
{
FolderIds = folderIds,
FileIds = fileIds,
DestFolderId = destFolderdId,
DeleteAfter = false,
ConflictResolveType = FileConflictResolveType.Overwrite
};
2022-04-22 13:24:54 +00:00
return batchModel;
}
2022-07-13 10:00:08 +00:00
protected Task<T> GetAsync<T>(string url)
{
2022-07-13 10:00:08 +00:00
return SendAsync<T>(HttpMethod.Get, url);
}
2022-07-13 10:00:08 +00:00
protected Task<T> PostAsync<T>(string url, object data = null)
{
2022-07-13 10:00:08 +00:00
return SendAsync<T>(HttpMethod.Post, url, data);
}
2022-07-13 10:00:08 +00:00
protected Task<T> PutAsync<T>(string url, object data = null)
{
2022-07-13 10:00:08 +00:00
return SendAsync<T>(HttpMethod.Put, url, data);
}
2022-07-13 10:00:08 +00:00
protected Task<T> DeleteAsync<T>(string url, object data = null)
{
2022-07-13 10:00:08 +00:00
return SendAsync<T>(HttpMethod.Delete, url, data);
}
2022-07-13 10:00:08 +00:00
private protected Task<SuccessApiResponse> DeleteAsync(string url, object data = null)
{
2022-07-13 10:00:08 +00:00
return SendAsync(HttpMethod.Delete, url, data);
2022-05-13 15:08:30 +00:00
}
protected async Task<List<FileOperationResult>> WaitLongOperation()
{
List<FileOperationResult> statuses = null;
while (true)
{
2022-07-08 12:31:07 +00:00
statuses = await GetAsync<List<FileOperationResult>>("fileops");
2022-05-13 15:08:30 +00:00
if (statuses.TrueForAll(r => r.Finished))
{
break;
}
await Task.Delay(100);
}
return statuses;
2022-07-07 14:45:23 +00:00
}
protected void CheckStatuses(List<FileOperationResult> statuses)
{
2022-07-13 10:00:08 +00:00
Assert.IsTrue(statuses.Count > 0);
2022-07-07 14:45:23 +00:00
Assert.IsTrue(statuses.TrueForAll(r => string.IsNullOrEmpty(r.Error)));
2022-07-13 10:00:08 +00:00
}
protected async Task<T> SendAsync<T>(HttpMethod method, string url, object data = null)
{
var result = await SendAsync(method, url, data);
if (result.Response is JsonElement jsonElement)
{
return jsonElement.Deserialize<T>(_options);
}
throw new Exception("can't parsing result");
}
protected async Task<SuccessApiResponse> SendAsync(HttpMethod method, string url, object data = null)
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _cookie);
var request = new HttpRequestMessage
{
RequestUri = new Uri(_baseAddress + url),
Method = method,
};
if (data != null)
{
request.Content = JsonContent.Create(data);
}
var response = await _client.SendAsync(request);
return await response.Content.ReadFromJsonAsync<SuccessApiResponse>();
}
}