BasicDataServiceTest.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 OpenSim.Tests.Common;
  36. using log4net;
  37. using System.Data;
  38. using System.Data.Common;
  39. using System.Reflection;
  40. namespace OpenSim.Data.Tests
  41. {
  42. /// <summary>This is a base class for testing any Data service for any DBMS.
  43. /// Requires NUnit 2.5 or better (to support the generics).
  44. /// </summary>
  45. /// <remarks>
  46. /// FIXME: Should extend OpenSimTestCase but compile on mono 2.4.3 currently fails with
  47. /// AssetTests`2 : System.MemberAccessException : Cannot create an instance of OpenSim.Data.Tests.AssetTests`2[TConn,TAssetData] because Type.ContainsGenericParameters is true.
  48. /// and similar on EstateTests, InventoryTests and RegionTests.
  49. /// Runs fine with mono 2.10.8.1, so easiest thing is to wait until min Mono version uplifts.
  50. /// </remarks>
  51. /// <typeparam name="TConn"></typeparam>
  52. /// <typeparam name="TService"></typeparam>
  53. public class BasicDataServiceTest<TConn, TService>
  54. where TConn : DbConnection, new()
  55. where TService : class, new()
  56. {
  57. protected string m_connStr;
  58. private TService m_service;
  59. private string m_file;
  60. // TODO: Is this in the right place here?
  61. // Later: apparently it's not, but does it matter here?
  62. // protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  63. protected ILog m_log; // doesn't matter here that it's not static, init to correct type in instance .ctor
  64. public BasicDataServiceTest()
  65. : this("")
  66. {
  67. }
  68. public BasicDataServiceTest(string conn)
  69. {
  70. m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn));
  71. m_log = LogManager.GetLogger(this.GetType());
  72. OpenSim.Tests.Common.TestLogging.LogToConsole(); // TODO: Is that right?
  73. }
  74. /// <summary>
  75. /// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it.
  76. /// You'd probably want to to cast the 'service' to a more specific type and store it in a member var.
  77. /// This framework takes care of disposing it, if it's disposable.
  78. /// </summary>
  79. /// <param name="service">The service being tested</param>
  80. protected virtual void InitService(object service)
  81. {
  82. }
  83. [TestFixtureSetUp]
  84. public void Init()
  85. {
  86. // Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops)
  87. if (typeof(TConn).Name.StartsWith("Sqlite"))
  88. {
  89. // SQLite doesn't work on power or z linux
  90. if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd"))
  91. Assert.Ignore();
  92. // for SQLite, if no explicit conn string is specified, use a temp file
  93. if (String.IsNullOrEmpty(m_connStr))
  94. {
  95. m_file = Path.GetTempFileName() + ".db";
  96. m_connStr = "URI=file:" + m_file + ",version=3";
  97. }
  98. }
  99. if (String.IsNullOrEmpty(m_connStr))
  100. {
  101. string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name);
  102. m_log.Warn(msg);
  103. Assert.Ignore(msg);
  104. }
  105. // Try the connection, ignore tests if Open() fails
  106. using (TConn conn = new TConn())
  107. {
  108. conn.ConnectionString = m_connStr;
  109. try
  110. {
  111. conn.Open();
  112. conn.Close();
  113. }
  114. catch
  115. {
  116. string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name);
  117. m_log.Warn(msg);
  118. Assert.Ignore(msg);
  119. }
  120. }
  121. // If we manage to connect to the database with the user
  122. // and password above it is our test database, and run
  123. // these tests. If anything goes wrong, ignore these
  124. // tests.
  125. try
  126. {
  127. m_service = new TService();
  128. InitService(m_service);
  129. }
  130. catch (Exception e)
  131. {
  132. m_log.Error(e.ToString());
  133. Assert.Ignore();
  134. }
  135. }
  136. [TestFixtureTearDown]
  137. public void Cleanup()
  138. {
  139. if (m_service != null)
  140. {
  141. if (m_service is IDisposable)
  142. ((IDisposable)m_service).Dispose();
  143. m_service = null;
  144. }
  145. if (!String.IsNullOrEmpty(m_file) && File.Exists(m_file))
  146. File.Delete(m_file);
  147. }
  148. protected virtual DbConnection Connect()
  149. {
  150. DbConnection cnn = new TConn();
  151. cnn.ConnectionString = m_connStr;
  152. cnn.Open();
  153. return cnn;
  154. }
  155. protected virtual void ExecuteSql(string sql)
  156. {
  157. using (DbConnection dbcon = Connect())
  158. {
  159. using (DbCommand cmd = dbcon.CreateCommand())
  160. {
  161. cmd.CommandText = sql;
  162. cmd.ExecuteNonQuery();
  163. }
  164. }
  165. }
  166. protected delegate bool ProcessRow(IDataReader reader);
  167. protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action)
  168. {
  169. int nRecs = 0;
  170. using (DbConnection dbcon = Connect())
  171. {
  172. using (DbCommand cmd = dbcon.CreateCommand())
  173. {
  174. cmd.CommandText = sql;
  175. CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default;
  176. using (DbDataReader rdr = cmd.ExecuteReader(cb))
  177. {
  178. while (rdr.Read())
  179. {
  180. nRecs++;
  181. if (!action(rdr))
  182. break;
  183. }
  184. }
  185. }
  186. }
  187. return nRecs;
  188. }
  189. /// <summary>Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all
  190. /// databases, so we just DROP and ignore an exception.
  191. /// </summary>
  192. /// <param name="tables"></param>
  193. protected virtual void DropTables(params string[] tables)
  194. {
  195. foreach (string tbl in tables)
  196. {
  197. try
  198. {
  199. ExecuteSql("DROP TABLE " + tbl + ";");
  200. }catch
  201. {
  202. }
  203. }
  204. }
  205. /// <summary>Clear tables listed as parameters (without dropping them).
  206. /// </summary>
  207. /// <param name="tables"></param>
  208. protected virtual void ResetMigrations(params string[] stores)
  209. {
  210. string lst = "";
  211. foreach (string store in stores)
  212. {
  213. string s = "'" + store + "'";
  214. if (lst == "")
  215. lst = s;
  216. else
  217. lst += ", " + s;
  218. }
  219. string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst);
  220. try
  221. {
  222. ExecuteSql("DELETE FROM migrations where name " + sCond);
  223. }
  224. catch
  225. {
  226. }
  227. }
  228. /// <summary>Clear tables listed as parameters (without dropping them).
  229. /// </summary>
  230. /// <param name="tables"></param>
  231. protected virtual void ClearTables(params string[] tables)
  232. {
  233. foreach (string tbl in tables)
  234. {
  235. try
  236. {
  237. ExecuteSql("DELETE FROM " + tbl + ";");
  238. }
  239. catch
  240. {
  241. }
  242. }
  243. }
  244. }
  245. }