When you work with ORM like nhibernate, having a tool like nhprof is the key of success. But even with NHProfiler you could not prevent people of doing wrong stuff because they do not use it :) . I have a simple scenario, a developer changed a method on the server lazily fetching a property of a large resultset. The effect is that the service call, that usually responded in milliseconds starts to respond in 10 seconds.

The reason is really simple, the function loaded about 200 entities from the database and if you are sure you want to access for all 200 entities a property, you should do eager fetching because issuing ~200 queries to the database is not usually a good idea. Then after some time the function started to do timeout, so I inspected again the code and did not find anything strange, but NHprof reveals me that the query was actually fetching another related entity, from a table with millions of row causing timeout. This is due to a modification to a mapping, someone disabled proxy for that class, so NH decided to do a join with the table with millions of row, slowing the method again .

After the problem was fixed, I created some helpers that permits me to write a test that will alert me immediately in the future if such a problem is comeback again.

   1: [Test]

   2: public void verify_xxxx()

   3: {

   4:     var sut = new cccccService();

   5:     sut.DoSomething(1);

   6:     this.NhibernateQueryCount().Should().Be.EqualTo(1);

   7:     String query = this.NhibernateGetQueries().First();

   8:     query.Should().Not.Contain("relatedlin1_.Id");

   9: }

This test is not really a UnitTest, it is more an integration one, but it is able to verify that calling a function on a service class only one query is issued to the database and the query should not eager fetch data from the other table (relatedlin…). This is much more an integration test than a unit test, but it is quite interesting because it permits me to write assertion on number and text of SQL generated by NHibernate, a feature that is really interesting especially if you know that production database is quite big. To achieve this is really simple.

I wrote this simple test helper based on my infrastructure.

   1: public class InterceptNhQueriesHelper : ITestHelper

   2:  {

   3:      public const string nhQueries = "DFCDE96A-ADF7-4C46-A55B-219381364B7F";

   4:      private Dictionary<String, Level> _oldLevel = new Dictionary<string, Level>();

   5:  

   6:      #region ITestHelper Members

   7:  

   8:      public void FixtureSetUp(BaseTestFixture fixture)

   9:      {

  10:          ILogger loggerToForceInitializationOfLoggingSystem = IoC.Resolve<ILogger>();

  11:          var repository = LogManager.GetAllRepositories();

  12:          Log4NetLogEventSourceAppender interceptorAppender = new Log4NetLogEventSourceAppender();

  13:          foreach (var loggerRepository in repository)

  14:          {

  15:              Hierarchy hierarchy = (Hierarchy)loggerRepository;

  16:              if (hierarchy.GetAppenders()

  17:                      .Count(appender => appender.GetType() == typeof(Log4NetLogEventSourceAppender)) == 0)

  18:              {

  19:                  hierarchy.Root.AddAppender(interceptorAppender);

  20:                  hierarchy.RaiseConfigurationChanged(EventArgs.Empty);

  21:              }

  22:              _oldLevel[hierarchy.Name] = hierarchy.Root.Level;

  23:              hierarchy.Root.Level = Level.Debug;

  24:  

  25:              var loggers = loggerRepository.GetCurrentLoggers();

  26:              foreach (var logger in loggers)

  27:              {

  28:                  Logger realLogger = logger as Logger;

  29:                  if (realLogger.Name.IndexOf("NHIBERNATE", StringComparison.InvariantCultureIgnoreCase) >= 0)

  30:                  {

  31:                      _oldLevel[realLogger.Name] = realLogger.Level;

  32:                      realLogger.Level = Level.Debug;

  33:                      if (!realLogger.Appenders.OfType<IAppender>().Any(appender => appender.GetType() == typeof(Log4NetLogEventSourceAppender)))

  34:                      {

  35:                          //non ho appender intercettori

  36:                          realLogger.AddAppender(interceptorAppender);

  37:                      }

  38:                  }

  39:              }

  40:  

  41:              hierarchy.RaiseConfigurationChanged(EventArgs.Empty);

  42:          }

  43:  

  44:          Log4NetLogEventSourceAppender.OnLog += Log4NetLogEventSourceAppender_OnLog;

  45:          loggerToForceInitializationOfLoggingSystem.Debug("TESTLOG DEBUG");

  46:          loggerToForceInitializationOfLoggingSystem.Info("TESTLOG Info");

  47:          loggerToForceInitializationOfLoggingSystem.Error("TESTLOG Error");

  48:      }

  49:  

  50:      private BaseTestFixture currentFixture;

  51:      private List<String> SqlInstructions = new List<string>();

  52:  

  53:      void Log4NetLogEventSourceAppender_OnLog(object sender, OnLog4NetLogEventArgs e)

  54:      {

  55:          if (e.LoggingEvent.LoggerName.Equals("nhibernate.sql", StringComparison.OrdinalIgnoreCase))

  56:          {

  57:              SqlInstructions.Add(e.LoggingEvent.MessageObject as string);

  58:          }

  59:      }

  60:  

  61:      public void SetUp(BaseTestFixture fixture)

  62:      {

  63:          currentFixture = fixture;

  64:          fixture.SetIntoTestContext(nhQueries, SqlInstructions);

  65:          SqlInstructions.Clear();

  66:      }

  67:  

  68:      public void TearDown(BaseTestFixture fixture)

  69:      {

  70:          currentFixture = null;

  71:      }

  72:  

  73:      public void FixtureTearDown(BaseTestFixture fixture)

  74:      {

  75:          var repository = LogManager.GetAllRepositories();

  76:          foreach (var loggerRepository in repository)

  77:          {

  78:              Hierarchy hierarchy = (Hierarchy)loggerRepository;

  79:              hierarchy.Root.Level = _oldLevel[hierarchy.Name];

  80:  

  81:              var loggers = loggerRepository.GetCurrentLoggers();

  82:              foreach (var logger in loggers)

  83:              {

  84:                  Logger realLogger = logger as Logger;

  85:                  if (realLogger.Name.IndexOf("NHIBERNATE", StringComparison.InvariantCultureIgnoreCase) >= 0 &&

  86:                      _oldLevel.ContainsKey(realLogger.Name))

  87:                  {

  88:  

  89:                      realLogger.Level = _oldLevel[realLogger.Name];

  90:                  }

  91:              }

  92:              hierarchy.RaiseConfigurationChanged(EventArgs.Empty);

  93:          }

  94:      }

  95:  

  96:      public int Priority

  97:      {

  98:          get { return 1; }

  99:      }

 100:  

 101:      #endregion

 102:  }

this helpers seems complex, but basically it simply add during FixtureSetup an appender to log4net, this appender basically raises an event whenever it receives a log.

   1: public class Log4NetLogEventSourceAppender : AppenderSkeleton

   2:    {

   3:        private Object _syncRoot;

   4:  

   5:        public Log4NetLogEventSourceAppender()

   6:        {

   7:            _syncRoot = new object();

   8:        }

   9:  

  10:        /// <summary>

  11:        /// Occurs when [on log].

  12:        /// </summary>

  13:        public static event EventHandler<OnLog4NetLogEventArgs> OnLog;

  14:  

  15:        protected override void Append(LoggingEvent loggingEvent)

  16:        {

  17:            EventHandler<OnLog4NetLogEventArgs> temp = OnLog;

  18:            if (temp != null)

  19:            {

  20:                lock (_syncRoot)

  21:                {

  22:                    temp(null, new OnLog4NetLogEventArgs(loggingEvent));

  23:                }

  24:            }

  25:        }

  26:  

  27:    }

  28:  

  29:    public class OnLog4NetLogEventArgs : EventArgs

  30:    {

  31:        public LoggingEvent LoggingEvent { get; private set; }

  32:  

  33:        public OnLog4NetLogEventArgs(LoggingEvent loggingEvent)

  34:        {

  35:            LoggingEvent = loggingEvent;

  36:        }

  37:    }

This appender permits the helper to intercept all logs and since Nhibernate raise a log with name nhibernate.sql with the SQL Code whenever it raises a query to the database, the helper can filter for those kind of messages and store each query inside a standard String collection.

   1: public static class InterceptNhQueriesHelperMethods

   2: {

   3:     public static Int32 NhibernateQueryCount(this BaseTestFixtureWithHelper fixture)

   4:     {

   5:         return fixture.GetFromTestContext<List<String>>(InterceptNhQueriesHelper.nhQueries).Count;

   6:     }

   7:  

   8:     public static List<String> NhibernateGetQueries(this BaseTestFixtureWithHelper fixture)

   9:     {

  10:         return fixture.GetFromTestContext<List<String>>(InterceptNhQueriesHelper.nhQueries);

  11:     }

  12: }

Now I can simply decorate my Test Fixture with a  specific attribute and let the magic happens.

   1: [InterceptNhQueries]

   2:    public class XxxFixture : Test.Utilities.BaseTestFixtureWithHelper

Inside a test I can use NhibernateQueryCount() to know the number of the queries issued by NH during the test and NhibernateGetQueries() to grab the whole list and assert on how NH interacted with the database during a test.

Gian Maria.

Tags: , ,