BasicDataServiceTest.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Collections.Generic;
  30. using log4net.Config;
  31. using NUnit.Framework;
  32. using NUnit.Framework.Constraints;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using log4net;
  36. using System.Data;
  37. using System.Data.Common;
  38. using System.Reflection;
  39. namespace OpenSim.Data.Tests
  40. {
  41. /// <summary>This is a base class for testing any Data service for any DBMS.
  42. /// Requires NUnit 2.5 or better (to support the generics).
  43. /// </summary>
  44. /// <typeparam name="TConn"></typeparam>
  45. /// <typeparam name="TService"></typeparam>
  46. public class BasicDataServiceTest<TConn, TService>
  47. where TConn : DbConnection, new()
  48. where TService : class, new()
  49. {
  50. protected string m_connStr;
  51. private TService m_service;
  52. private string m_file;
  53. // TODO: Is this in the right place here?
  54. // Later: apparently it's not, but does it matter here?
  55. // protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. protected ILog m_log; // doesn't matter here that it's not static, init to correct type in instance .ctor
  57. public BasicDataServiceTest()
  58. : this("")
  59. {
  60. }
  61. public BasicDataServiceTest(string conn)
  62. {
  63. m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn));
  64. m_log = LogManager.GetLogger(this.GetType());
  65. OpenSim.Tests.Common.TestLogging.LogToConsole(); // TODO: Is that right?
  66. }
  67. /// <summary>
  68. /// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it.
  69. /// You'd probably want to to cast the 'service' to a more specific type and store it in a member var.
  70. /// This framework takes care of disposing it, if it's disposable.
  71. /// </summary>
  72. /// <param name="service">The service being tested</param>
  73. protected virtual void InitService(object service)
  74. {
  75. }
  76. [TestFixtureSetUp]
  77. public void Init()
  78. {
  79. // Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops)
  80. if (typeof(TConn).Name.StartsWith("Sqlite"))
  81. {
  82. // SQLite doesn't work on power or z linux
  83. if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd"))
  84. Assert.Ignore();
  85. // for SQLite, if no explicit conn string is specified, use a temp file
  86. if (String.IsNullOrEmpty(m_connStr))
  87. {
  88. m_file = Path.GetTempFileName() + ".db";
  89. m_connStr = "URI=file:" + m_file + ",version=3";
  90. }
  91. }
  92. if (String.IsNullOrEmpty(m_connStr))
  93. {
  94. string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name);
  95. m_log.Warn(msg);
  96. Assert.Ignore(msg);
  97. }
  98. // Try the connection, ignore tests if Open() fails
  99. using (TConn conn = new TConn())
  100. {
  101. conn.ConnectionString = m_connStr;
  102. try
  103. {
  104. conn.Open();
  105. conn.Close();
  106. }
  107. catch
  108. {
  109. string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name);
  110. m_log.Warn(msg);
  111. Assert.Ignore(msg);
  112. }
  113. }
  114. // If we manage to connect to the database with the user
  115. // and password above it is our test database, and run
  116. // these tests. If anything goes wrong, ignore these
  117. // tests.
  118. try
  119. {
  120. m_service = new TService();
  121. InitService(m_service);
  122. }
  123. catch (Exception e)
  124. {
  125. m_log.Error(e.ToString());
  126. Assert.Ignore();
  127. }
  128. }
  129. [TestFixtureTearDown]
  130. public void Cleanup()
  131. {
  132. if (m_service != null)
  133. {
  134. if (m_service is IDisposable)
  135. ((IDisposable)m_service).Dispose();
  136. m_service = null;
  137. }
  138. if (!String.IsNullOrEmpty(m_file) && File.Exists(m_file))
  139. File.Delete(m_file);
  140. }
  141. protected virtual DbConnection Connect()
  142. {
  143. DbConnection cnn = new TConn();
  144. cnn.ConnectionString = m_connStr;
  145. cnn.Open();
  146. return cnn;
  147. }
  148. protected virtual void ExecuteSql(string sql)
  149. {
  150. using (DbConnection dbcon = Connect())
  151. {
  152. using (DbCommand cmd = dbcon.CreateCommand())
  153. {
  154. cmd.CommandText = sql;
  155. cmd.ExecuteNonQuery();
  156. }
  157. }
  158. }
  159. protected delegate bool ProcessRow(IDataReader reader);
  160. protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action)
  161. {
  162. int nRecs = 0;
  163. using (DbConnection dbcon = Connect())
  164. {
  165. using (DbCommand cmd = dbcon.CreateCommand())
  166. {
  167. cmd.CommandText = sql;
  168. CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default;
  169. using (DbDataReader rdr = cmd.ExecuteReader(cb))
  170. {
  171. while (rdr.Read())
  172. {
  173. nRecs++;
  174. if (!action(rdr))
  175. break;
  176. }
  177. }
  178. }
  179. }
  180. return nRecs;
  181. }
  182. /// <summary>Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all
  183. /// databases, so we just DROP and ignore an exception.
  184. /// </summary>
  185. /// <param name="tables"></param>
  186. protected virtual void DropTables(params string[] tables)
  187. {
  188. foreach (string tbl in tables)
  189. {
  190. try
  191. {
  192. ExecuteSql("DROP TABLE " + tbl + ";");
  193. }catch
  194. {
  195. }
  196. }
  197. }
  198. /// <summary>Clear tables listed as parameters (without dropping them).
  199. /// </summary>
  200. /// <param name="tables"></param>
  201. protected virtual void ResetMigrations(params string[] stores)
  202. {
  203. string lst = "";
  204. foreach (string store in stores)
  205. {
  206. string s = "'" + store + "'";
  207. if (lst == "")
  208. lst = s;
  209. else
  210. lst += ", " + s;
  211. }
  212. string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst);
  213. try
  214. {
  215. ExecuteSql("DELETE FROM migrations where name " + sCond);
  216. }
  217. catch
  218. {
  219. }
  220. }
  221. /// <summary>Clear tables listed as parameters (without dropping them).
  222. /// </summary>
  223. /// <param name="tables"></param>
  224. protected virtual void ClearTables(params string[] tables)
  225. {
  226. foreach (string tbl in tables)
  227. {
  228. try
  229. {
  230. ExecuteSql("DELETE FROM " + tbl + ";");
  231. }
  232. catch
  233. {
  234. }
  235. }
  236. }
  237. }
  238. }