Skip to content

Commit

Permalink
Review ad fix EF SqlServer example
Browse files Browse the repository at this point in the history
  • Loading branch information
javiertuya committed Jan 5, 2024
1 parent 05c28bf commit 4682520
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 70 deletions.
7 changes: 3 additions & 4 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -255,14 +255,13 @@ jobs:
# run: dotnet nuget add source https://apiint.nugettest.org/v3/index.json -n int.nugettest.org
- name: Run test - ADO.NET
run: dotnet test --logger "trx;LogFileName=../../reports/qacover-report.trx" QACoverTest/QACoverTest.csproj
#- name: Run test - Entity Framework
# run: dotnet test --logger "trx;LogFileName=../../reports/qacover-report-ef.trx" QACoverTestEf/QACoverTestEf.csproj
- name: Run test - Entity Framework
run: dotnet test --logger "trx;LogFileName=../../reports/qacover-report-ef.trx" QACoverTestEf/QACoverTestEf.csproj
- name: Junit html report
if: always()
uses: javiertuya/[email protected]
with:
#net-trx-report: "net/reports/qacover-report.trx,net/reports/qacover-report-ef.trx"
net-trx-report: "net/reports/qacover-report.trx"
net-trx-report: "net/reports/qacover-report.trx,net/reports/qacover-report-ef.trx"
net-surefire-folder: "net/target/surefire-reports"
surefire-files: "net/target/surefire-reports/TEST-*.xml"
report-dir: net/target/site
Expand Down
2 changes: 1 addition & 1 deletion net/QACover/Giis.Qacover.Driver/StatementAdapter.N.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public override bool HasRows(string sql)
// que tienen como tipo interno un string). Esto causa que otros metodos que
// utilicen GetSqlWithValues para hacer logs puedan no mostrar correctamente la sql.
cmd.CommandText = sql;
if (this.nativeParams != null)
if (cmd is SqlCommand && this.nativeParams != null)
AddParameters(cmd, this.nativeParams);
else if (this.parameters != null && this.parameters.Size() > 0)
cmd.CommandText = GetSqlWithValues(sql);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,8 @@
using System.Data.Common;

//Prueba de concepto de un interceptor EF Core
//(sutituye al anterior que usaba un componente no nativo Z.EntityFramework...)
//Este interceptor se anyade en OnConfiguring del contexto y se puede deshabilitar
//para no capturar determinadas queries, p.e. cuando se crean datos de prueba

//TODO revisar resto de metodos a interceptar (p.e. escalares)
//TODO Revisar que se interceptan consultas adicionales como las de obtener metadatos
//posibilidad crear configuracion adicional para omitir la evaluacion de reglas (similar a include/exclude)
namespace Giis.Qacover.Ef2driver
{
public class Ef2EventListener : DbCommandInterceptor
Expand Down
6 changes: 3 additions & 3 deletions net/QACoverTestEf/QACoverTestEf.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace />
Expand All @@ -14,8 +14,8 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.25" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.25" />

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />

<PackageReference Include="NUnit" Version="4.0.1" />
Expand Down

This file was deleted.

70 changes: 43 additions & 27 deletions net/QACoverTestEf/Test4giis.Qacover.Ef/TestEvaluationEf.N.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Generic;
using Giis.Qacover.Model;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using NUnit.Framework.Legacy;
using Test4giis.Qacoverapp.Ef;

namespace Test4giis.Qacover.Ef
{
/**
* This test requires the same SQLServer database that the one used in ADO.NET tests,
* the setup of test data and query execution are done using Entity Framework
* thorugh the mock app defined in AppSimpleEf
*/
public class TestEvaluationEf : Base
{
protected override Variability GetVariant()
{
return new Variability("sqlserver");
}

[SetUp]
public void SetUpTestData()
{
using (EfModel db = new EfModel())
{
// Deactivate the interceptor to forget the setup queries
// (although in this case queries are only updates)
db.DisableInterceptor(); //evita evaluar estas queries que no son de la aplicacion
db.Database.EnsureCreated();
//ojo, estamos usando el contexto interceptado, no pasa nada si son sentencias de actualizacion
//pero habria que permitir crear un contexto sin interceptar
//este si hace lectura
db.SimpleEntitys.RemoveRange(from c in db.SimpleEntitys select c);
// Setup a fresh table to hold the test data
try
{
db.Database.ExecuteSqlRaw("drop table TestEfTable");
}
catch (Microsoft.Data.SqlClient.SqlException) { }
db.Database.ExecuteSqlRaw("CREATE TABLE TestEfTable (Id integer NOT NULL CONSTRAINT PK_TestEfTable PRIMARY KEY , Num INTEGER NOT NULL, Txt varchar(32) NULL)");
//db.TestEfTable.RemoveRange(from c in db.TestEfTable select c);

db.Add(new SimpleEfEntity { Id = 1, Num = 0, Text = "abc" });
db.Add(new SimpleEfEntity { Id = 2, Num = 99, Text = "xyz" });
db.Add(new SimpleEfEntity { Id = 3, Num = 0, Text = null });
// Setup test data for all tests to cover some rules and do not cover oters
db.Add(new TestEfEntity { Id = 1, Num = 0, Txt = "abc" });
db.Add(new TestEfEntity { Id = 2, Num = 99, Txt = "xyz" });
db.Add(new TestEfEntity { Id = 3, Num = 0, Txt = null });
db.SaveChanges();
}
}
Expand All @@ -32,35 +48,35 @@ public void SetUpTestData()
public virtual void TestEvalEfNoParameters()
{
AppSimpleEf app = new AppSimpleEf();
List<SimpleEfEntity> pojo = app.QueryEfNoParams();
List<TestEfEntity> pojo = app.QueryEfNoParams();
ClassicAssert.AreEqual(1, pojo.Count);
ClassicAssert.AreEqual(2, pojo[0].Id);
ClassicAssert.AreEqual(99, pojo[0].Num);
ClassicAssert.AreEqual("xyz", pojo[0].Text);
ClassicAssert.AreEqual("xyz", pojo[0].Txt);
//compara eliminando las comillas dobles que inserta EntityFramework en tablas y columnas
String efSql= "SELECT s.Id, s.Num, s.Text FROM SimpleEntitys AS s WHERE (s.Text = 'xyz') AND (s.Num = 99) ORDER BY s.Id";
AssertEvalResults(efSql,
string efSql= "SELECT [t].[Id], [t].[Num], [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Txt] = 'xyz') AND ([t].[Num] = 99) ORDER BY [t].[Id]";
AssertEvalResults(efSql,
string.Empty, string.Empty,
"COVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE ((s.Text = 'xyz')) AND ((s.Num = 99))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE NOT((s.Text = 'xyz')) AND ((s.Num = 99))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE (s.Text IS NULL) AND ((s.Num = 99))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE (s.Num = 100) AND ((s.Text = 'xyz'))\n"
+ "COVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE (s.Num = 99) AND ((s.Text = 'xyz'))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE (s.Num = 98) AND ((s.Text = 'xyz'))",
"COVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE (([t].[Txt] = 'xyz')) AND (([t].[Num] = 99))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE NOT(([t].[Txt] = 'xyz')) AND (([t].[Num] = 99))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Txt] IS NULL) AND (([t].[Num] = 99))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Num] = 100) AND (([t].[Txt] = 'xyz'))\n"
+ "COVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Num] = 99) AND (([t].[Txt] = 'xyz'))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Num] = 98) AND (([t].[Txt] = 'xyz'))",
"{}", true, false);
}
[Test()]
public virtual void TestEvalEfParameters()
{
options.SetFpcServiceOptions("noboundaries");
AppSimpleEf app = new AppSimpleEf();
List<SimpleEfEntity> pojo = app.QueryEfParams(99, "xyz");
string efSql = "SELECT s.Id, s.Num, s.Text FROM SimpleEntitys AS s WHERE (s.Text = @__param1_0) AND (s.Num > @__param2_1) ORDER BY s.Id";
List<TestEfEntity> pojo = app.QueryEfParams(99, "xyz");
string efSql = "SELECT [t].[Id], [t].[Num], [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Txt] = @__param1_0) AND ([t].[Num] > @__param2_1) ORDER BY [t].[Id]";
AssertEvalResults(efSql, string.Empty, string.Empty,
"UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE ((s.Text = 'xyz')) AND ((s.Num > 99))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE NOT((s.Text = 'xyz')) AND ((s.Num > 99))\n"
+ "UNCOVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE (s.Text IS NULL) AND ((s.Num > 99))\n"
+ "COVERED SELECT s.Id , s.Num , s.Text FROM SimpleEntitys AS s WHERE NOT((s.Num > 99)) AND ((s.Text = 'xyz'))",
"UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE (([t].[Txt] = 'xyz')) AND (([t].[Num] > 99))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE NOT(([t].[Txt] = 'xyz')) AND (([t].[Num] > 99))\n"
+ "UNCOVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE ([t].[Txt] IS NULL) AND (([t].[Num] > 99))\n"
+ "COVERED SELECT [t].[Id] , [t].[Num] , [t].[Txt] FROM [TestEfTable] AS [t] WHERE NOT(([t].[Num] > 99)) AND (([t].[Txt] = 'xyz'))",
"{@__param1_0='xyz', @__param2_1=99}", true, false);
}
}
Expand Down
12 changes: 6 additions & 6 deletions net/QACoverTestEf/Test4giis.Qacoverapp.Ef/AppSimpleEf.N.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ public AppSimpleEf()
db.Database.EnsureCreated();
}
}
public List<SimpleEfEntity> QueryEfNoParams()
public List<TestEfEntity> QueryEfNoParams()
{
//String sql = "select id,num,text from test where text=? and num>?";
using (var db = new EfModel())
{
return db.SimpleEntitys.Where(b => b.Text == "xyz").Where(b => b.Num == 99)
.OrderBy(b => b.Id).ToList<SimpleEfEntity>();
return db.TestEfTable.Where(b => b.Txt == "xyz").Where(b => b.Num == 99)
.OrderBy(b => b.Id).ToList<TestEfEntity>();

}
}
public List<SimpleEfEntity> QueryEfParams(int param2, string param1)
public List<TestEfEntity> QueryEfParams(int param2, string param1)
{
//String sql = "select id,num,text from test where text=? and num>?";
using (var db = new EfModel())
{
return db.SimpleEntitys.Where(b => b.Text == param1).Where(b => b.Num > param2)
.OrderBy(b => b.Id).ToList<SimpleEfEntity>();
return db.TestEfTable.Where(b => b.Txt == param1).Where(b => b.Num > param2)
.OrderBy(b => b.Id).ToList<TestEfEntity>();
}
}

Expand Down
38 changes: 30 additions & 8 deletions net/QACoverTestEf/Test4giis.Qacoverapp.Ef/EfModel.N.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,48 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Giis.Qacover.Ef2driver;
using Giis.Portable.Util;
using Giis.Tdrules.Store.Rdb;
using System.Linq;

namespace Test4giis.Qacoverapp.Ef
{
public class EfModel : Ef2InterceptorContext
{
public DbSet<SimpleEfEntity> SimpleEntitys { get; set; }
public DbSet<TestEfEntity> TestEfTable { get; set; }

// Connection string uses the same configuration parameters that are used for ADO.NET tests
private string GetConnectionString()
{
string SetupPath = FileUtil.GetPath(Parameters.GetProjectRoot(), "..", "setup");
string DatabaseProperties = FileUtil.GetPath(SetupPath, "database.properties");
string url = new JdbcProperties().GetProp(DatabaseProperties, "qacover.netcore.qacoverdb.sqlserver.url");
string user = new JdbcProperties().GetProp(DatabaseProperties, "qacover.netcore.qacoverdb.sqlserver.user");
string EnvironmentProperties = FileUtil.GetPath(SetupPath, "environment.properties");
string password = new JdbcProperties().GetEnvVar(EnvironmentProperties, "TEST_" + "sqlserver".ToUpper() + "_PWD");
return url + ";UID=" + user + ";PWD=" + password;
}

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
base.OnConfiguring(options); //para que se instale el interceptor
options.UseSqlite("Data Source=" + FileUtil.GetPath(Parameters.GetProjectRoot(), "TestEf.db"));
base.OnConfiguring(options); // base class (Ef2InterceptorContext) will install the interceptor
options.UseSqlServer(GetConnectionString());
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Disable generated unicode literals
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(e => e.GetProperties().Where(p => p.ClrType == typeof(string))))
{
property.SetIsUnicode(false);
}
}
}

public class SimpleEfEntity
public class TestEfEntity
{
public int Id { get; set; }
public Int16 Num { get; set; }
public string Text { get; set; }
public int Num { get; set; }
public string Txt { get; set; }
}
}

0 comments on commit 4682520

Please sign in to comment.