Browse files

Upgraded to NHibernate 3.2 GA

  • Loading branch information...
1 parent b35c654 commit ebefa820ddc876fba24f8bf2a6ab73e0638221d9 @stuartcarnie stuartcarnie committed Sep 2, 2011
View
173 App.config
@@ -1,132 +1,131 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
- <configSections>
- <section name="hibernate-configuration"
+ <configSections>
+ <section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
- <section name="log4net"
+ <section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
- </configSections>
+ </configSections>
- <connectionStrings>
- <add name="TestConnectionString"
+ <connectionStrings>
+ <add name="TestConnectionString"
connectionString="TestConnectionString-TestConnectionString" />
- </connectionStrings>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"
+ </connectionStrings>
+ <runtime>
+ <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"
applies-to="v1.1.4322">
- <qualifyAssembly partialName="System.Web"
+ <qualifyAssembly partialName="System.Web"
fullName="System.Web, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
- </assemblyBinding>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"
+ </assemblyBinding>
+ <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"
applies-to="v2.0.50727">
- <qualifyAssembly partialName="System.Web"
+ <qualifyAssembly partialName="System.Web"
fullName="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
- </assemblyBinding>
+ </assemblyBinding>
- <!-- The assembly binding for FirebirdClient ADO.NET 2.0 DataProvider -->
- <!-- -->
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <qualifyAssembly partialName="FirebirdSql.Data.FirebirdClient" fullName="FirebirdSql.Data.FirebirdClient, Version=2.1.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c" />
- </assemblyBinding>
- <!-- -->
+ </runtime>
- </runtime>
-
- <!--
+ <!--
hibernate-configuration section
You don't need to change this section for your own use.
You can write your own hibernate.cfg.xml to override all session-factory configuration.
Templates are available in NHibernate.Config.Templates folder.
-->
- <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
- <bytecode-provider type="lcg"/>
- <reflection-optimizer use="true"/>
- <session-factory name="NHibernate.Test">
- <property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider, NHibernate</property>
- <property name="cache.use_query_cache">true</property>
- <property name="prepare_sql">false</property>
- <property name="query.startup_check">false</property>
- <!--
+ <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
+ <bytecode-provider type="lcg"/>
+ <reflection-optimizer use="true"/>
+ <session-factory name="NHibernate.Test">
+ <!--<property name="query.factory_class">NHibernate.Hql.Classic.ClassicQueryTranslatorFactory, NHibernate</property>
+-->
+ <property name="connection.provider">NHibernate.Test.DebugConnectionProvider, NHibernate.Test</property>
+ <property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider, NHibernate</property>
+ <property name="cache.use_query_cache">true</property>
+ <property name="query.startup_check">false</property>
+ <!--
The valid strings for Isolation can be found in the documentation for the System.Data.IsolationLevel
Enumeration documentation.
Use the member names - not the values.
-->
- <property name="connection.isolation">ReadCommitted</property>
-
- <!-- This is the System.Data.dll provider for MSSQL Server -->
- <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
- <property name="connection.connection_string">
- Server=(local)\sqlexpress;initial catalog=nhibernate;Integrated Security=SSPI
- </property>
- <property name="show_sql">true</property>
- <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
- <property name="use_outer_join">true</property>
- <property name="command_timeout">444</property>
- <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
- <property name="adonet.wrap_result_sets">false</property>
- </session-factory>
- </hibernate-configuration>
-
- <!-- This section contains the log4net configuration settings -->
- <log4net debug="false">
-
- <!-- Define some output appenders -->
- <appender name="trace"
+ <property name="adonet.batch_size">10</property>
+ <property name="connection.isolation">ReadCommitted</property>
+ <property name="hbm2ddl.keywords">none</property>
+ <property name="format_sql">true</property>
+
+ <!-- This is the System.Data.dll provider for MSSQL Server -->
+ <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
+ <property name="connection.connection_string">Server=localhost\sqlexpress;initial catalog=nhibernate;Integrated Security=SSPI</property>
+
+ <property name="show_sql">false</property>
+ <property name="command_timeout">444</property>
+ <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
+ <property name="adonet.wrap_result_sets">false</property>
+ </session-factory>
+ </hibernate-configuration>
+
+ <!-- This section contains the log4net configuration settings -->
+ <log4net debug="false">
+
+ <!-- Define some output appenders -->
+ <appender name="trace"
type="log4net.Appender.TraceAppender, log4net">
- <layout type="log4net.Layout.PatternLayout,log4net">
- <param name="ConversionPattern"
+ <layout type="log4net.Layout.PatternLayout,log4net">
+ <param name="ConversionPattern"
value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
- </layout>
- </appender>
+ </layout>
+ </appender>
- <appender name="console"
+ <appender name="console"
type="log4net.Appender.ConsoleAppender, log4net">
- <layout type="log4net.Layout.PatternLayout,log4net">
- <param name="ConversionPattern"
+ <layout type="log4net.Layout.PatternLayout,log4net">
+ <param name="ConversionPattern"
value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
- </layout>
- </appender>
+ </layout>
+ </appender>
- <appender name="rollingFile"
+ <appender name="rollingFile"
type="log4net.Appender.RollingFileAppender,log4net" >
- <param name="File"
+ <param name="File"
value="log.txt" />
- <param name="AppendToFile"
+ <param name="AppendToFile"
value="false" />
- <param name="RollingStyle"
+ <param name="RollingStyle"
value="Date" />
- <param name="DatePattern"
+ <param name="DatePattern"
value="yyyy.MM.dd" />
- <param name="StaticLogFileName"
+ <param name="StaticLogFileName"
value="true" />
- <layout type="log4net.Layout.PatternLayout,log4net">
- <param name="ConversionPattern"
+ <layout type="log4net.Layout.PatternLayout,log4net">
+ <param name="ConversionPattern"
value="%d [%t] %-5p %c - %m%n" />
- </layout>
- </appender>
+ </layout>
+ </appender>
+
+ <!-- Setup the root category, add the appenders and set the default priority -->
- <!-- Setup the root category, add the appenders and set the default priority -->
+ <root>
+ <priority value="WARN" />
+ <appender-ref ref="console" />
+ </root>
- <root>
- <priority value="WARN" />
- <appender-ref ref="console" />
- </root>
+ <logger name="NHibernate.Hql.Ast.ANTLR">
+ <priority value="OFF" />
+ </logger>
- <logger name="NHibernate.Bytecode.CodeDom">
- <priority value="OFF" />
- </logger>
+ <logger name="NHibernate.SQL">
+ <level value="OFF" />
+ </logger>
- <logger name="NHibernate.SQL">
- <level value="OFF" />
- </logger>
+ <logger name="NHibernate.AdoNet.AbstractBatcher">
+ <level value="OFF" />
+ </logger>
- <logger name="NHibernate.Tool.hbm2ddl.SchemaExport">
- <level value="ERROR" />
- </logger>
- </log4net>
+ <logger name="NHibernate.Tool.hbm2ddl.SchemaExport">
+ <level value="ERROR" />
+ </logger>
+ </log4net>
</configuration>
View
81 DebugConnectionProvider.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections;
+using System.Data;
+using Iesi.Collections;
+using NHibernate.Connection;
+
+namespace NHibernate.Test
+{
+ /// <summary>
+ /// This connection provider keeps a list of all open connections,
+ /// it is used when testing to check that tests clean up after themselves.
+ /// </summary>
+ public class DebugConnectionProvider : DriverConnectionProvider
+ {
+ private ISet connections = new ListSet();
+
+ public override IDbConnection GetConnection()
+ {
+ try
+ {
+ IDbConnection connection = base.GetConnection();
+ connections.Add(connection);
+ return connection;
+ }
+ catch (Exception e)
+ {
+ throw new HibernateException("Could not open connection to: " + ConnectionString, e);
+ }
+
+ }
+
+ public override void CloseConnection(IDbConnection conn)
+ {
+ base.CloseConnection(conn);
+ connections.Remove(conn);
+ }
+
+ public bool HasOpenConnections
+ {
+ get
+ {
+ // check to see if all connections that were at one point opened
+ // have been closed through the CloseConnection
+ // method
+ if (connections.IsEmpty)
+ {
+ // there are no connections, either none were opened or
+ // all of the closings went through CloseConnection.
+ return false;
+ }
+ else
+ {
+ // Disposing of an ISession does not call CloseConnection (should it???)
+ // so a Diposed of ISession will leave an IDbConnection in the list but
+ // the IDbConnection will be closed (atleast with MsSql it works this way).
+ foreach (IDbConnection conn in connections)
+ {
+ if (conn.State != ConnectionState.Closed)
+ {
+ return true;
+ }
+ }
+
+ // all of the connections have been Disposed and were closed that way
+ // or they were Closed through the CloseConnection method.
+ return false;
+ }
+ }
+ }
+
+ public void CloseAllConnections()
+ {
+ while (!connections.IsEmpty)
+ {
+ IEnumerator en = connections.GetEnumerator();
+ en.MoveNext();
+ CloseConnection(en.Current as IDbConnection);
+ }
+ }
+ }
+}
View
55 NHibernate.Test-Lite.csproj
@@ -15,7 +15,23 @@
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
- <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <TargetFrameworkProfile />
+ <PublishUrl>publish\</PublishUrl>
+ <Install>true</Install>
+ <InstallFrom>Disk</InstallFrom>
+ <UpdateEnabled>false</UpdateEnabled>
+ <UpdateMode>Foreground</UpdateMode>
+ <UpdateInterval>7</UpdateInterval>
+ <UpdateIntervalUnits>Days</UpdateIntervalUnits>
+ <UpdatePeriodically>false</UpdatePeriodically>
+ <UpdateRequired>false</UpdateRequired>
+ <MapFileExtensions>true</MapFileExtensions>
+ <ApplicationRevision>0</ApplicationRevision>
+ <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
+ <IsWebBootstrapper>false</IsWebBootstrapper>
+ <UseApplicationTrust>false</UseApplicationTrust>
+ <BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -45,14 +61,6 @@
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
- <Reference Include="Castle.Core, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>lib\Castle.Core.dll</HintPath>
- </Reference>
- <Reference Include="Castle.DynamicProxy2, Version=2.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>lib\Castle.DynamicProxy2.dll</HintPath>
- </Reference>
<Reference Include="Iesi.Collections, Version=1.0.0.3, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\Iesi.Collections.dll</HintPath>
@@ -65,10 +73,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\NHibernate.dll</HintPath>
</Reference>
- <Reference Include="nunit.core, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>lib\nunit.core.dll</HintPath>
- </Reference>
<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>lib\nunit.framework.dll</HintPath>
@@ -80,11 +84,14 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
+ <Compile Include="DebugConnectionProvider.cs" />
<Compile Include="NHSpecificTest\BugTestCase.cs" />
<Compile Include="NHSpecificTest\NH1234\DomainClass.cs" />
<Compile Include="NHSpecificTest\NH1234\SampleTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestCase.cs" />
+ <Compile Include="TestConfigurationHelper.cs" />
+ <Compile Include="TestDialect.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
@@ -95,6 +102,28 @@
<ItemGroup>
<EmbeddedResource Include="NHSpecificTest\NH1234\Mappings.hbm.xml" />
</ItemGroup>
+ <ItemGroup>
+ <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
+ <Visible>False</Visible>
+ <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
+ <Install>false</Install>
+ </BootstrapperPackage>
+ <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
+ <Visible>False</Visible>
+ <ProductName>.NET Framework 3.5 SP1</ProductName>
+ <Install>true</Install>
+ </BootstrapperPackage>
+ <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
+ <Visible>False</Visible>
+ <ProductName>Windows Installer 3.1</ProductName>
+ <Install>true</Install>
+ </BootstrapperPackage>
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="hibernate.cfg.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
View
664 TestCase.cs
@@ -11,295 +11,383 @@
using NHibernate.Tool.hbm2ddl;
using NHibernate.Type;
using NUnit.Framework;
+using NHibernate.Hql.Classic;
+using NHibernate.Hql.Ast.ANTLR;
namespace NHibernate.Test
{
- public abstract class TestCase
- {
- private const bool OutputDdl = false;
- protected Configuration cfg;
- protected ISessionFactoryImplementor sessions;
-
- private static readonly ILog log = LogManager.GetLogger(typeof(TestCase));
-
- protected Dialect.Dialect Dialect
- {
- get { return NHibernate.Dialect.Dialect.GetDialect(cfg.Properties); }
- }
-
- protected ISession lastOpenedSession;
-
- /// <summary>
- /// Mapping files used in the TestCase
- /// </summary>
- protected abstract IList Mappings { get; }
-
- /// <summary>
- /// Assembly to load mapping files from (default is NHibernate.DomainModel).
- /// </summary>
- protected virtual string MappingsAssembly
- {
- get { return "NHibernate.DomainModel"; }
- }
-
- static TestCase()
- {
- // Configure log4net here since configuration through an attribute doesn't always work.
- XmlConfigurator.Configure();
- }
-
- /// <summary>
- /// Creates the tables used in this TestCase
- /// </summary>
- [TestFixtureSetUp]
- public void TestFixtureSetUp()
- {
- try
- {
- Configure();
- if (!AppliesTo(Dialect))
- {
- Assert.Ignore(GetType() + " does not apply to " + Dialect);
- }
-
- CreateSchema();
- BuildSessionFactory();
- }
- catch (Exception e)
- {
- log.Error("Error while setting up the test fixture", e);
- throw;
- }
- }
-
- /// <summary>
- /// Removes the tables used in this TestCase.
- /// </summary>
- /// <remarks>
- /// If the tables are not cleaned up sometimes SchemaExport runs into
- /// Sql errors because it can't drop tables because of the FKs. This
- /// will occur if the TestCase does not have the same hbm.xml files
- /// included as a previous one.
- /// </remarks>
- [TestFixtureTearDown]
- public void TestFixtureTearDown()
- {
- DropSchema();
- Cleanup();
- }
-
- protected virtual void OnSetUp()
- {
- }
-
- /// <summary>
- /// Set up the test. This method is not overridable, but it calls
- /// <see cref="OnSetUp" /> which is.
- /// </summary>
- [SetUp]
- public void SetUp()
- {
- OnSetUp();
- }
-
- protected virtual void OnTearDown()
- {
- }
-
- /// <summary>
- /// Checks that the test case cleans up after itself. This method
- /// is not overridable, but it calls <see cref="OnTearDown" /> which is.
- /// </summary>
- [TearDown]
- public void TearDown()
- {
- OnTearDown();
-
- bool wasClosed = CheckSessionWasClosed();
- bool wasCleaned = CheckDatabaseWasCleaned();
- bool fail = !wasClosed || !wasCleaned;
-
- if (fail)
- {
- Assert.Fail("Test didn't clean up after itself");
- }
- }
-
- private bool CheckSessionWasClosed()
- {
- if (lastOpenedSession != null && lastOpenedSession.IsOpen)
- {
- log.Error("Test case didn't close a session, closing");
- lastOpenedSession.Close();
- return false;
- }
-
- return true;
- }
-
- private bool CheckDatabaseWasCleaned()
- {
- if (sessions.GetAllClassMetadata().Count == 0)
- {
- // Return early in the case of no mappings, also avoiding
- // a warning when executing the HQL below.
- return true;
- }
-
- bool empty;
- using (ISession s = sessions.OpenSession())
- {
- IList objects = s.CreateQuery("from System.Object o").List();
- empty = objects.Count == 0;
- }
-
- if (!empty)
- {
- log.Error("Test case didn't clean up the database after itself, re-creating the schema");
- DropSchema();
- CreateSchema();
- }
-
- return empty;
- }
-
- private void Configure()
- {
- cfg = new Configuration();
-
- Assembly assembly = Assembly.Load(MappingsAssembly);
-
- foreach (string file in Mappings)
- {
- cfg.AddResource(MappingsAssembly + "." + file, assembly);
- }
-
- Configure(cfg);
-
- ApplyCacheSettings(cfg);
- }
-
- private void CreateSchema()
- {
- new SchemaExport(cfg).Create(OutputDdl, true);
- }
-
- private void DropSchema()
- {
- new SchemaExport(cfg).Drop(OutputDdl, true);
- }
-
- protected virtual void BuildSessionFactory()
- {
- sessions = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
- }
-
- private void Cleanup()
- {
- sessions.Close();
- sessions = null;
- lastOpenedSession = null;
- cfg = null;
- }
-
- public int ExecuteStatement(string sql)
- {
- if (cfg == null)
- {
- cfg = new Configuration();
- }
-
- using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
- {
- IDbConnection conn = prov.GetConnection();
-
- try
- {
- using (IDbTransaction tran = conn.BeginTransaction())
- using (IDbCommand comm = conn.CreateCommand())
- {
- comm.CommandText = sql;
- comm.Transaction = tran;
- comm.CommandType = CommandType.Text;
- int result = comm.ExecuteNonQuery();
- tran.Commit();
- return result;
- }
- }
- finally
- {
- prov.CloseConnection(conn);
- }
- }
- }
-
- protected ISessionFactoryImplementor Sfi
- {
- get { return sessions; }
- }
-
- protected virtual ISession OpenSession()
- {
- lastOpenedSession = sessions.OpenSession();
- return lastOpenedSession;
- }
-
- protected virtual ISession OpenSession(IInterceptor sessionLocalInterceptor)
- {
- lastOpenedSession = sessions.OpenSession(sessionLocalInterceptor);
- return lastOpenedSession;
- }
-
- protected void ApplyCacheSettings(Configuration configuration)
- {
- if (CacheConcurrencyStrategy == null)
- {
- return;
- }
-
- foreach (PersistentClass clazz in configuration.ClassMappings)
- {
- bool hasLob = false;
- foreach (Property prop in clazz.PropertyClosureIterator)
- {
- if (prop.Value.IsSimpleValue)
- {
- IType type = ((SimpleValue)prop.Value).Type;
- if (type == NHibernateUtil.BinaryBlob)
- {
- hasLob = true;
- }
- }
- }
- if (!hasLob && !clazz.IsInherited)
- {
- configuration.SetCacheConcurrencyStrategy(clazz.EntityName, CacheConcurrencyStrategy);
- }
- }
-
- foreach (Mapping.Collection coll in configuration.CollectionMappings)
- {
- configuration.SetCollectionCacheConcurrencyStrategy(coll.Role, CacheConcurrencyStrategy);
- }
- }
-
- #region Properties overridable by subclasses
-
- protected virtual bool AppliesTo(Dialect.Dialect dialect)
- {
- return true;
- }
-
- protected virtual void Configure(Configuration configuration)
- {
- }
-
- protected virtual string CacheConcurrencyStrategy
- {
- get { return "nonstrict-read-write"; }
- //get { return null; }
- }
-
- #endregion
- }
+ public abstract class TestCase
+ {
+ private const bool OutputDdl = false;
+ protected Configuration cfg;
+ protected ISessionFactoryImplementor sessions;
+
+ private static readonly ILog log = LogManager.GetLogger(typeof(TestCase));
+
+ protected Dialect.Dialect Dialect
+ {
+ get { return NHibernate.Dialect.Dialect.GetDialect(cfg.Properties); }
+ }
+
+ protected TestDialect TestDialect
+ {
+ get { return TestDialect.GetTestDialect(Dialect); }
+ }
+
+ /// <summary>
+ /// To use in in-line test
+ /// </summary>
+ protected bool IsClassicParser
+ {
+ get
+ {
+ return sessions.Settings.QueryTranslatorFactory is ClassicQueryTranslatorFactory;
+ }
+ }
+
+ /// <summary>
+ /// To use in in-line test
+ /// </summary>
+ protected bool IsAntlrParser
+ {
+ get
+ {
+ return sessions.Settings.QueryTranslatorFactory is ASTQueryTranslatorFactory;
+ }
+ }
+
+ protected ISession lastOpenedSession;
+ private DebugConnectionProvider connectionProvider;
+
+ /// <summary>
+ /// Mapping files used in the TestCase
+ /// </summary>
+ protected abstract IList Mappings { get; }
+
+ /// <summary>
+ /// Assembly to load mapping files from (default is NHibernate.DomainModel).
+ /// </summary>
+ protected virtual string MappingsAssembly
+ {
+ get { return "NHibernate.DomainModel"; }
+ }
+
+ static TestCase()
+ {
+ // Configure log4net here since configuration through an attribute doesn't always work.
+ XmlConfigurator.Configure();
+ }
+
+ /// <summary>
+ /// Creates the tables used in this TestCase
+ /// </summary>
+ [TestFixtureSetUp]
+ public void TestFixtureSetUp()
+ {
+ try
+ {
+ Configure();
+ if (!AppliesTo(Dialect))
+ {
+ Assert.Ignore(GetType() + " does not apply to " + Dialect);
+ }
+
+ CreateSchema();
+ try
+ {
+ BuildSessionFactory();
+ if (!AppliesTo(sessions))
+ {
+ Assert.Ignore(GetType() + " does not apply with the current session-factory configuration");
+ }
+ }
+ catch
+ {
+ DropSchema();
+ throw;
+ }
+ }
+ catch (Exception e)
+ {
+ Cleanup();
+ log.Error("Error while setting up the test fixture", e);
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Removes the tables used in this TestCase.
+ /// </summary>
+ /// <remarks>
+ /// If the tables are not cleaned up sometimes SchemaExport runs into
+ /// Sql errors because it can't drop tables because of the FKs. This
+ /// will occur if the TestCase does not have the same hbm.xml files
+ /// included as a previous one.
+ /// </remarks>
+ [TestFixtureTearDown]
+ public void TestFixtureTearDown()
+ {
+ if (!AppliesTo(Dialect))
+ return;
+
+ DropSchema();
+ Cleanup();
+ }
+
+ protected virtual void OnSetUp()
+ {
+ }
+
+ /// <summary>
+ /// Set up the test. This method is not overridable, but it calls
+ /// <see cref="OnSetUp" /> which is.
+ /// </summary>
+ [SetUp]
+ public void SetUp()
+ {
+ OnSetUp();
+ }
+
+ protected virtual void OnTearDown()
+ {
+ }
+
+ /// <summary>
+ /// Checks that the test case cleans up after itself. This method
+ /// is not overridable, but it calls <see cref="OnTearDown" /> which is.
+ /// </summary>
+ [TearDown]
+ public void TearDown()
+ {
+ OnTearDown();
+
+ bool wasClosed = CheckSessionWasClosed();
+ bool wasCleaned = CheckDatabaseWasCleaned();
+ bool wereConnectionsClosed = CheckConnectionsWereClosed();
+ bool fail = !wasClosed || !wasCleaned || !wereConnectionsClosed;
+
+ if (fail)
+ {
+ Assert.Fail("Test didn't clean up after itself. session closed: " + wasClosed + " database cleaned: " + wasCleaned
+ + " connection closed: " + wereConnectionsClosed);
+ }
+ }
+
+ private bool CheckSessionWasClosed()
+ {
+ if (lastOpenedSession != null && lastOpenedSession.IsOpen)
+ {
+ log.Error("Test case didn't close a session, closing");
+ lastOpenedSession.Close();
+ return false;
+ }
+
+ return true;
+ }
+
+ private bool CheckDatabaseWasCleaned()
+ {
+ if (sessions.GetAllClassMetadata().Count == 0)
+ {
+ // Return early in the case of no mappings, also avoiding
+ // a warning when executing the HQL below.
+ return true;
+ }
+
+ bool empty;
+ using (ISession s = sessions.OpenSession())
+ {
+ IList objects = s.CreateQuery("from System.Object o").List();
+ empty = objects.Count == 0;
+ }
+
+ if (!empty)
+ {
+ log.Error("Test case didn't clean up the database after itself, re-creating the schema");
+ DropSchema();
+ CreateSchema();
+ }
+
+ return empty;
+ }
+
+ private bool CheckConnectionsWereClosed()
+ {
+ if (connectionProvider == null || !connectionProvider.HasOpenConnections)
+ {
+ return true;
+ }
+
+ log.Error("Test case didn't close all open connections, closing");
+ connectionProvider.CloseAllConnections();
+ return false;
+ }
+
+ private void Configure()
+ {
+ cfg = new Configuration();
+ if (TestConfigurationHelper.hibernateConfigFile != null)
+ cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
+
+ AddMappings(cfg);
+
+ Configure(cfg);
+
+ ApplyCacheSettings(cfg);
+ }
+
+ protected virtual void AddMappings(Configuration configuration)
+ {
+ Assembly assembly = Assembly.Load(MappingsAssembly);
+
+ foreach (string file in Mappings)
+ {
+ configuration.AddResource(MappingsAssembly + "." + file, assembly);
+ }
+ }
+
+ protected virtual void CreateSchema()
+ {
+ new SchemaExport(cfg).Create(OutputDdl, true);
+ }
+
+ private void DropSchema()
+ {
+ new SchemaExport(cfg).Drop(OutputDdl, true);
+ }
+
+ protected virtual void BuildSessionFactory()
+ {
+ sessions = (ISessionFactoryImplementor)cfg.BuildSessionFactory();
+ connectionProvider = sessions.ConnectionProvider as DebugConnectionProvider;
+ }
+
+ private void Cleanup()
+ {
+ if (sessions != null)
+ {
+ sessions.Close();
+ }
+ sessions = null;
+ connectionProvider = null;
+ lastOpenedSession = null;
+ cfg = null;
+ }
+
+ public int ExecuteStatement(string sql)
+ {
+ if (cfg == null)
+ {
+ cfg = new Configuration();
+ }
+
+ using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
+ {
+ IDbConnection conn = prov.GetConnection();
+
+ try
+ {
+ using (IDbTransaction tran = conn.BeginTransaction())
+ using (IDbCommand comm = conn.CreateCommand())
+ {
+ comm.CommandText = sql;
+ comm.Transaction = tran;
+ comm.CommandType = CommandType.Text;
+ int result = comm.ExecuteNonQuery();
+ tran.Commit();
+ return result;
+ }
+ }
+ finally
+ {
+ prov.CloseConnection(conn);
+ }
+ }
+ }
+
+ public int ExecuteStatement(ISession session, ITransaction transaction, string sql)
+ {
+ using (IDbCommand cmd = session.Connection.CreateCommand())
+ {
+ cmd.CommandText = sql;
+ if (transaction != null)
+ transaction.Enlist(cmd);
+ return cmd.ExecuteNonQuery();
+ }
+ }
+
+ protected ISessionFactoryImplementor Sfi
+ {
+ get { return sessions; }
+ }
+
+ protected virtual ISession OpenSession()
+ {
+ lastOpenedSession = sessions.OpenSession();
+ return lastOpenedSession;
+ }
+
+ protected virtual ISession OpenSession(IInterceptor sessionLocalInterceptor)
+ {
+ lastOpenedSession = sessions.OpenSession(sessionLocalInterceptor);
+ return lastOpenedSession;
+ }
+
+ protected void ApplyCacheSettings(Configuration configuration)
+ {
+ if (CacheConcurrencyStrategy == null)
+ {
+ return;
+ }
+
+ foreach (PersistentClass clazz in configuration.ClassMappings)
+ {
+ bool hasLob = false;
+ foreach (Property prop in clazz.PropertyClosureIterator)
+ {
+ if (prop.Value.IsSimpleValue)
+ {
+ IType type = ((SimpleValue)prop.Value).Type;
+ if (type == NHibernateUtil.BinaryBlob)
+ {
+ hasLob = true;
+ }
+ }
+ }
+ if (!hasLob && !clazz.IsInherited)
+ {
+ configuration.SetCacheConcurrencyStrategy(clazz.EntityName, CacheConcurrencyStrategy);
+ }
+ }
+
+ foreach (Mapping.Collection coll in configuration.CollectionMappings)
+ {
+ configuration.SetCollectionCacheConcurrencyStrategy(coll.Role, CacheConcurrencyStrategy);
+ }
+ }
+
+ #region Properties overridable by subclasses
+
+ protected virtual bool AppliesTo(Dialect.Dialect dialect)
+ {
+ return true;
+ }
+
+ protected virtual bool AppliesTo(ISessionFactoryImplementor factory)
+ {
+ return true;
+ }
+
+ protected virtual void Configure(Configuration configuration)
+ {
+ }
+
+ protected virtual string CacheConcurrencyStrategy
+ {
+ get { return "nonstrict-read-write"; }
+ //get { return null; }
+ }
+
+ #endregion
+ }
}
View
38 TestConfigurationHelper.cs
@@ -0,0 +1,38 @@
+namespace NHibernate.Test
+{
+ using System;
+ using System.IO;
+ using Cfg;
+
+ public static class TestConfigurationHelper
+ {
+ public static readonly string hibernateConfigFile;
+
+ static TestConfigurationHelper()
+ {
+ // Verify if hibernate.cfg.xml exists
+ hibernateConfigFile = TestConfigurationHelper.GetDefaultConfigurationFilePath();
+ }
+
+ public static string GetDefaultConfigurationFilePath()
+ {
+ string baseDir = AppDomain.CurrentDomain.BaseDirectory;
+ string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath;
+ string binPath = relativeSearchPath == null ? baseDir : Path.Combine(baseDir, relativeSearchPath);
+ string fullPath = Path.Combine(binPath, Cfg.Configuration.DefaultHibernateCfgFileName);
+ return File.Exists(fullPath) ? fullPath : null;
+ }
+
+ /// <summary>
+ /// Standar Configuration for tests.
+ /// </summary>
+ /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
+ public static Configuration GetDefaultConfiguration()
+ {
+ Configuration result = new Configuration();
+ if (hibernateConfigFile != null)
+ result.Configure(hibernateConfigFile);
+ return result;
+ }
+ }
+}
View
71 TestDialect.cs
@@ -0,0 +1,71 @@
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using NHibernate.SqlTypes;
+
+namespace NHibernate.Test
+{
+ /// <summary>
+ /// Like NHibernate's Dialect class, but for differences only important during testing.
+ /// Defaults to true for all support. Users of different dialects can turn support
+ /// off if the unit tests fail.
+ /// </summary>
+ public class TestDialect
+ {
+ public static TestDialect GetTestDialect(Dialect.Dialect dialect)
+ {
+ string testDialectTypeName = "NHibernate.Test.TestDialects." + dialect.GetType().Name.Replace("Dialect", "TestDialect");
+ System.Type testDialectType = System.Type.GetType(testDialectTypeName);
+ if (testDialectType != null)
+ return (TestDialect)Activator.CreateInstance(testDialectType, dialect);
+ return new TestDialect(dialect);
+ }
+
+ private Dialect.Dialect dialect;
+
+ public TestDialect(Dialect.Dialect dialect)
+ {
+ this.dialect = dialect;
+ }
+
+ public virtual bool SupportsOperatorAll { get { return true; } }
+ public virtual bool SupportsOperatorSome { get { return true; } }
+ public virtual bool SupportsLocate { get { return true; } }
+
+ public virtual bool SupportsDistributedTransactions { get { return true; } }
+
+ /// <summary>
+ /// Whether two transactions can be run at the same time. For example, with SQLite
+ /// the database is locked when one transaction is run, so running a second transaction
+ /// will cause a "database is locked" error message.
+ /// </summary>
+ public virtual bool SupportsConcurrentTransactions { get { return true; } }
+
+ public virtual bool SupportsFullJoin { get { return true; } }
+
+ public virtual bool HasBrokenDecimalType { get { return false; } }
+
+ public virtual bool SupportsNullCharactersInUtfStrings { get { return true; } }
+
+ public virtual bool SupportsSelectForUpdateOnOuterJoin { get { return true; } }
+
+ public virtual bool SupportsHavingWithoutGroupBy { get { return true; } }
+
+ public virtual bool IgnoresTrailingWhitespace { get { return false; } }
+
+ public bool SupportsSqlType(SqlType sqlType)
+ {
+ try
+ {
+ dialect.GetTypeName(sqlType);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ }
+}
View
23 hibernate.cfg.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+This template was written to work with NHibernate.Test.
+Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
+for your own use before compile tests in VisualStudio.
+-->
+<!-- This is the System.Data.OracleClient.dll provider for Oracle from MS -->
+<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
+ <session-factory name="NHibernate.Test">
+ <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
+ <property name="connection.connection_string">
+ Data Source=localhost\SQLEXPRESS;Initial Catalog=NHTEST;Integrated Security=True;Pooling=False
+ </property>
+ <property name="adonet.batch_size">10</property>
+ <property name="show_sql">false</property>
+ <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
+ <property name="command_timeout">10</property>
+ <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
+ <!--<property name="query.factory_class">
+ NHibernate.Hql.Classic.ClassicQueryTranslatorFactory, NHibernate
+ </property>-->
+ </session-factory>
+</hibernate-configuration>
View
BIN lib/Castle.Core.dll
Binary file not shown.
View
BIN lib/Castle.DynamicProxy2.dll
Binary file not shown.
View
BIN lib/Iesi.Collections.dll
Binary file not shown.
View
BIN lib/Iesi.Collections.pdb
Binary file not shown.
View
BIN lib/NHibernate.dll
Binary file not shown.
View
BIN lib/NHibernate.pdb
Binary file not shown.
View
BIN lib/nunit.core.dll
Binary file not shown.
View
BIN lib/nunit.framework.dll
Binary file not shown.

0 comments on commit ebefa82

Please sign in to comment.