Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix issues-592 and Uniform type conversion method #593

Merged
merged 1 commit into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@ public class DefaultTypeConvertProvider : ITypeConvertProvider
typeof(DateTime?)
};

private readonly List<Type> _notNeedSerializeTypes = new()
private readonly List<Type> _simpleTypes = new()
{
typeof(String),
typeof(Guid),
typeof(DateTime),
typeof(Decimal),
typeof(Guid?),
typeof(DateTime?),
typeof(Decimal?)
typeof(string),
typeof(short?),
typeof(short),
typeof(int),
typeof(int?),
typeof(long),
typeof(long?),
typeof(float),
typeof(float?),
typeof(decimal),
typeof(decimal?),
typeof(double),
typeof(double?),
typeof(bool),
typeof(bool?)
};

private readonly IDeserializer? _deserializer;
Expand All @@ -38,15 +46,20 @@ public class DefaultTypeConvertProvider : ITypeConvertProvider

public object? ConvertTo(string value, Type type, IDeserializer? deserializer = null)
{
if (_types.Contains(type))
return TypeDescriptor.GetConverter(type).ConvertFromInvariantString(value)!;
if (value.IsNullOrWhiteSpace())
return default;

if (_simpleTypes.Contains(type))
{
if (type.IsNullableType())
return Convert.ChangeType(value, Nullable.GetUnderlyingType(type)!);

if (!IsSupportDeserialize(type))
return Convert.ChangeType(value, type);
}

if (_types.Contains(type))
return TypeDescriptor.GetConverter(type).ConvertFromInvariantString(value)!;

return (deserializer ?? _deserializer)!.Deserialize(value, type);
}

private bool IsSupportDeserialize(Type type)
=> !type.IsPrimitive && !_notNeedSerializeTypes.Contains(type);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.BuildingBlocks.Data.Tests;

[TestClass]
public class DefaultTypeConvertProviderTest
{
[TestMethod]
public void ConvertToByBaseType()
{
var defaultTypeConvertProvider = new DefaultTypeConvertProvider();
Assert.AreEqual((short)0, defaultTypeConvertProvider.ConvertTo<short>("0"));
Assert.AreEqual((short)0, defaultTypeConvertProvider.ConvertTo<short?>("0"));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<short?>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<short>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<int>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<int?>("0"));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<int?>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<int>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<long>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<long?>("0"));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<long?>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<long>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<float>("0"));
Assert.AreEqual((float)0, defaultTypeConvertProvider.ConvertTo<float?>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<float>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<float?>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<decimal>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<decimal?>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<decimal>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<decimal?>(""));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<double>("0"));
Assert.AreEqual((double)0, defaultTypeConvertProvider.ConvertTo<double?>("0"));
Assert.AreEqual(0, defaultTypeConvertProvider.ConvertTo<double>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<double?>(""));
Assert.AreEqual(default,
defaultTypeConvertProvider.ConvertTo<DateTime>(default(DateTime).ToString(CultureInfo.InvariantCulture)));
Assert.AreEqual(default(DateTime),
defaultTypeConvertProvider.ConvertTo<DateTime?>(default(DateTime).ToString(CultureInfo.InvariantCulture)));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<DateTime?>(""));
Assert.AreEqual(default, defaultTypeConvertProvider.ConvertTo<DateTime>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<string?>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<string>(""));
Assert.AreEqual(bool.Parse("False"), defaultTypeConvertProvider.ConvertTo<bool>("False"));
Assert.AreEqual(bool.Parse("False"), defaultTypeConvertProvider.ConvertTo<bool?>("False"));
Assert.AreEqual(false, defaultTypeConvertProvider.ConvertTo<bool>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<bool?>(""));

var guid = Guid.NewGuid();

Assert.AreEqual(guid, defaultTypeConvertProvider.ConvertTo<Guid>(guid.ToString()));
Assert.AreEqual(guid, defaultTypeConvertProvider.ConvertTo<Guid?>(guid.ToString()));
Assert.AreEqual(Guid.Empty, defaultTypeConvertProvider.ConvertTo<Guid>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<Guid?>(""));

var date = DateTime.UtcNow;

Assert.AreEqual(date.ToString(CultureInfo.InvariantCulture),
defaultTypeConvertProvider.ConvertTo<DateTime>(date.ToString(CultureInfo.InvariantCulture))
.ToString(CultureInfo.InvariantCulture));

var convertToValue = defaultTypeConvertProvider.ConvertTo<DateTime?>(date.ToString(CultureInfo.InvariantCulture));
Assert.IsNotNull(convertToValue);
Assert.AreEqual(date.ToString(CultureInfo.InvariantCulture), ((DateTime)convertToValue).ToString(CultureInfo.InvariantCulture));
Assert.AreEqual(default(DateTime), defaultTypeConvertProvider.ConvertTo<DateTime>(""));
Assert.AreEqual(null, defaultTypeConvertProvider.ConvertTo<DateTime?>(""));
}

[TestMethod]
public void ConvertToByComplexType()
{
var list = new List<int>()
{
1,
3,
5
};
var value = list.ToJson();
var defaultTypeConvertProvider = new DefaultTypeConvertProvider();
var actualValue = defaultTypeConvertProvider.ConvertTo<List<int>>(value, new DefaultJsonDeserializer());
Assert.IsNotNull(actualValue);
Assert.AreEqual(3, actualValue.Count);
Assert.AreEqual(1, actualValue[0]);
Assert.AreEqual(3, actualValue[1]);
Assert.AreEqual(5, actualValue[2]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\Contrib\Extensions\Masa.Contrib.Extensions.BackgroundJobs.Memory\Masa.Contrib.Extensions.BackgroundJobs.Memory.csproj" />
<ProjectReference Include="..\..\Masa.BuildingBlocks.Data\Masa.BuildingBlocks.Data.csproj" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

global using Masa.BuildingBlocks.Data.Tests.Infrastructure;
global using Masa.Contrib.Data.Serialization.Json;
global using Microsoft.VisualStudio.TestTools.UnitTesting;
global using System.Globalization;
global using DateTime = System.DateTime;

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Data\Masa.BuildingBlocks.Data.Contracts\Masa.BuildingBlocks.Data.Contracts.csproj" />
<ProjectReference Include="..\..\Data\Masa.BuildingBlocks.Data.Contracts\Masa.BuildingBlocks.Data.Contracts.csproj" />
<ProjectReference Include="..\..\Data\Masa.BuildingBlocks.Data\Masa.BuildingBlocks.Data.csproj" />
<ProjectReference Include="..\..\Exception\Masa.BuildingBlocks.Exceptions\Masa.BuildingBlocks.Exceptions.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ public void TestDbContext4()
[TestMethod]
public void TestDbContext5()
{
Services.Configure<AppConfigOptions>(options => { options.DbConnectionString = MemoryConnectionString; });
Services.Configure<AppConfigOptions>(options =>
{
options.DbConnectionString = MemoryConnectionString;
});
var dbContext = CreateDbContext<CustomDbContext5>(null);
var student = GenerateStudent();
dbContext.Set<Student>().Add(student);
Expand All @@ -76,7 +79,10 @@ public void TestDbContext6()
[TestMethod]
public void TestDbContext7()
{
Services.Configure<AppConfigOptions>(options => { options.DbConnectionString = MemoryConnectionString; });
Services.Configure<AppConfigOptions>(options =>
{
options.DbConnectionString = MemoryConnectionString;
});
var dbContext = CreateDbContext<CustomDbContext7>(null);
var student = GenerateStudent();
dbContext.Set<Student>().Add(student);
Expand Down Expand Up @@ -287,7 +293,10 @@ public async Task TestModifyConnectionString()

IServiceProvider serviceProvider = default!;
var dbContext =
await CreateDbContextAsync<CustomDbContext>(optionsBuilder => { optionsBuilder.UseSqlite(); }, sp => serviceProvider = sp);
await CreateDbContextAsync<CustomDbContext>(optionsBuilder =>
{
optionsBuilder.UseSqlite();
}, sp => serviceProvider = sp);

var connectionStringProvider = serviceProvider.GetService<IConnectionStringProvider>();
Assert.IsNotNull(connectionStringProvider);
Expand Down Expand Up @@ -338,20 +347,32 @@ public async Task TestUseConfigurationAndSpecify()
.Build();
Services.AddSingleton<IConfiguration>(configuration);

await CreateDbContextAsync<CustomDbContext>(optionsBuilder => { optionsBuilder.UseSqlite(); });
await CreateDbContextAsync<CustomDbContext>(optionsBuilder =>
{
optionsBuilder.UseSqlite();
});
await Assert.ThrowsExceptionAsync<ArgumentException>(async () =>
{
await CreateDbContextAsync<CustomDbContext2>(optionsBuilder => { optionsBuilder.UseSqlite(SqliteConnectionString); });
await CreateDbContextAsync<CustomDbContext2>(optionsBuilder =>
{
optionsBuilder.UseSqlite(SqliteConnectionString);
});
});
}

[TestMethod]
public async Task TestAddMultiDbContextAsync()
{
Services.AddMasaDbContext<CustomDbContext>(dbContextBuilder => { dbContextBuilder.UseInMemoryDatabase(MemoryConnectionString); });
Services.AddMasaDbContext<CustomDbContext>(dbContextBuilder =>
{
dbContextBuilder.UseInMemoryDatabase(MemoryConnectionString);
});
IServiceProvider serviceProvider = default!;
var customDbContext2 = await CreateDbContextAsync<CustomDbContext2>(
dbContextBuilder => { dbContextBuilder.UseInMemoryDatabase(MemoryConnectionString); }, sp => serviceProvider = sp);
dbContextBuilder =>
{
dbContextBuilder.UseInMemoryDatabase(MemoryConnectionString);
}, sp => serviceProvider = sp);

var customDbContext = serviceProvider.GetService<CustomDbContext>();
Assert.IsNotNull(customDbContext);
Expand Down Expand Up @@ -572,14 +593,87 @@ public async Task TestAddOrUpdateOrDeleteWhenUserIdIsIntAsyncBySpecifyUserIdAndT
Assert.AreNotEqual(inputModificationTime.AddDays(2), modificationTimeByUpdate);
}

[TestMethod]
public async Task TestAddOrUpdateOrDeleteWhenUserIdIsStringAsync()
{
Services.Configure<AuditEntityOptions>(options => options.UserIdType = typeof(string));

var creator = "admin";
var customUserContext = new CustomUserContext(creator);
Services.AddSingleton<IUserContext>(customUserContext);

var connectionString = MemoryConnectionString;
var dbContext = await CreateDbContextAsync<CustomDbContext>(dbContextBuilder =>
{
dbContextBuilder
.UseInMemoryDatabase(connectionString)
.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll)
.UseFilter();
});
Assert.IsNotNull(dbContext);
await dbContext.Set<People2>().AddAsync(new People2()
{
Name = "masa"
});
await dbContext.SaveChangesAsync();

var people = await dbContext.Set<People2>().FirstOrDefaultAsync();
Assert.IsNotNull(people);
Assert.AreEqual(creator, people.Creator);
Assert.AreEqual(creator, people.Modifier);
}

[TestMethod]
public async Task TestAddOrUpdateOrDeleteWhenUserIdIsGuidAsync()
{
Services.Configure<AuditEntityOptions>(options => options.UserIdType = typeof(Guid));

var customUserContext = new CustomUserContext("");
Services.AddSingleton<IUserContext>(customUserContext);

var connectionString = MemoryConnectionString;
var dbContext = await CreateDbContextAsync<CustomDbContext>(dbContextBuilder =>
{
dbContextBuilder
.UseInMemoryDatabase(connectionString)
.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll)
.UseFilter();
});
Assert.IsNotNull(dbContext);
await dbContext.Set<People>().AddAsync(new People()
{
Name = "masa"
});
await dbContext.SaveChangesAsync();

var people = await dbContext.Set<People>().AsTracking().FirstOrDefaultAsync();
Assert.IsNotNull(people);
Assert.AreEqual(null, people.Creator);
Assert.AreEqual(null, people.Modifier);

var creator = Guid.NewGuid();
customUserContext.SetUserId(creator.ToString());

dbContext.Set<People>().Update(people);
await dbContext.SaveChangesAsync();

var peopleByUpdate = await dbContext.Set<People>().AsTracking().FirstOrDefaultAsync();
Assert.IsNotNull(peopleByUpdate);
Assert.AreEqual(null, peopleByUpdate.Creator);
Assert.AreEqual(creator, peopleByUpdate.Modifier);
}

#endregion

#region Test Model Mapping

[TestMethod]
public void TestCustomTableName()
{
var dbContext = CreateDbContext<CustomDbContext>(dbContext => { dbContext.UseInMemoryDatabase(MemoryConnectionString); });
var dbContext = CreateDbContext<CustomDbContext>(dbContext =>
{
dbContext.UseInMemoryDatabase(MemoryConnectionString);
});
var entityTableName = dbContext.Model.FindEntityType(typeof(Student))?.GetTableName();

Assert.AreEqual("masa_students", entityTableName);
Expand All @@ -592,7 +686,10 @@ public void TestCustomTableName()
[TestMethod]
public void TestQueryTrackingBehaviorByDefault()
{
var dbContext = CreateDbContext<CustomDbContext>(dbContext => { dbContext.UseInMemoryDatabase(MemoryConnectionString); });
var dbContext = CreateDbContext<CustomDbContext>(dbContext =>
{
dbContext.UseInMemoryDatabase(MemoryConnectionString);
});
Assert.AreEqual(QueryTrackingBehavior.NoTracking, dbContext.ChangeTracker.QueryTrackingBehavior);
}

Expand Down Expand Up @@ -628,4 +725,5 @@ public void TestQueryTrackingBehaviorByUseQueryTrackingBehavior()
}

#endregion

}
Loading