SqlConnectionTest.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. //
  2. // SqlDataAdapterTest.cs - NUnit Test Cases for testing the
  3. // SqlDataAdapter class
  4. // Author:
  5. // Senganal T ([email protected])
  6. //
  7. // Copyright (c) 2004 Novell Inc., and the individuals listed
  8. // on the ChangeLog entries.
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Data;
  31. using System.Data.SqlClient;
  32. using System.Net;
  33. using NUnit.Framework;
  34. using System.Collections;
  35. namespace MonoTests.System.Data
  36. {
  37. [TestFixture]
  38. [Category ("sqlserver")]
  39. public class SqlConnectionTest
  40. {
  41. SqlConnection conn = null ;
  42. String connectionString = ConnectionManager.Singleton.ConnectionString;
  43. ArrayList invalidConnectionStrings = null;
  44. int stateChangeEventCount = 0;
  45. int disposedEventCount = 0;
  46. int infoMessageEventCount = 0;
  47. void populateTestData ()
  48. {
  49. invalidConnectionStrings = new ArrayList ();
  50. // shud be got from a config file ..
  51. //list of invalid and valid conn strings;
  52. invalidConnectionStrings.Add ("InvalidConnectionString");
  53. invalidConnectionStrings.Add ("invalidKeyword=10");
  54. invalidConnectionStrings.Add ("Packet Size=511");
  55. invalidConnectionStrings.Add ("Packet Size=32768");
  56. invalidConnectionStrings.Add ("Connect Timeout=-1");
  57. invalidConnectionStrings.Add ("Max Pool Size=-1");
  58. invalidConnectionStrings.Add ("Min Pool Size=-1");
  59. }
  60. [SetUp]
  61. public void SetUp ()
  62. {
  63. }
  64. [TearDown]
  65. public void TearDown ()
  66. {
  67. if (conn != null)
  68. conn.Dispose ();
  69. }
  70. [Test]
  71. public void DefaultConstructorTest ()
  72. {
  73. SqlConnection conn = new SqlConnection ();
  74. Assert.AreEqual ("", conn.ConnectionString,
  75. "#1 Default Connection String should be empty");
  76. Assert.AreEqual (15, conn.ConnectionTimeout,
  77. "#2 Default ConnectionTimeout should be 15" );
  78. Assert.AreEqual ("", conn.Database,
  79. "#3 Default Database should be empty");
  80. Assert.AreEqual ("", conn.DataSource,
  81. "#4 Default DataSource should be empty");
  82. Assert.AreEqual (8192, conn.PacketSize,"#5 Default Packet Size is 8192");
  83. Assert.AreEqual (Dns.GetHostName().ToUpper (), conn.WorkstationId.ToUpper (),
  84. "#6 Default Workstationid shud be hostname");
  85. Assert.AreEqual (ConnectionState.Closed, conn.State,
  86. "#7 Connection State shud be closed by default");
  87. }
  88. [Test]
  89. public void OverloadedConstructorTest ()
  90. {
  91. // Test Exceptions are thrown for Invalid Connection Strings
  92. int count=0 ;
  93. populateTestData ();
  94. foreach (String invalidConnString in invalidConnectionStrings) {
  95. count++;
  96. try {
  97. conn = new SqlConnection ((string)invalidConnString);
  98. Assert.Fail ("#1 Exception must be thrown");
  99. }catch (AssertionException e) {
  100. throw e;
  101. }catch (Exception e) {
  102. Assert.AreEqual (typeof(ArgumentException), e.GetType(),
  103. "Incorrect Exception" + e.StackTrace);
  104. }
  105. }
  106. //check synonyms..
  107. //do i need to check for all the synonyms..
  108. conn = new SqlConnection (
  109. "Timeout=10;Connect Timeout=20;Connection Timeout=30");
  110. Assert.AreEqual (30, conn.ConnectionTimeout,
  111. "## The last set value shud be taken");
  112. conn = new SqlConnection (
  113. "Connect Timeout=100;Connection Timeout=200;Timeout=300");
  114. Assert.AreEqual (300, conn.ConnectionTimeout,
  115. "## The last set value shud be taken");
  116. conn = new SqlConnection (
  117. "Connection Timeout=1000;Timeout=2000;Connect Timeout=3000");
  118. Assert.AreEqual (3000, conn.ConnectionTimeout,
  119. "## The last set value shud be taken");
  120. // Test if properties are set correctly
  121. //'==' doesent work correctly in both msdotnet and mono
  122. /*
  123. conn = new SqlConnection ("server=local==host;database=tmp;");
  124. Assert.AreEqual ("local==host", conn.DataSource,
  125. "# Datasource name is set incorrectly");
  126. */
  127. string connStr = "Server='loca\"lhost';Database='''Db'; packet Size=\"512\";";
  128. connStr += "connect Timeout=20;Workstation Id=\"'\"\"desktop\";";
  129. conn = new SqlConnection (connStr);
  130. Assert.AreEqual (connStr , conn.ConnectionString , "#1");
  131. Assert.AreEqual ("loca\"lhost" , conn.DataSource , "#2");
  132. Assert.AreEqual ("'Db" , conn.Database , "#3");
  133. Assert.AreEqual (512 , conn.PacketSize , "#4");
  134. Assert.AreEqual (20 , conn.ConnectionTimeout , "#5");
  135. Assert.AreEqual ("'\"desktop" , conn.WorkstationId , "#6");
  136. Assert.AreEqual (ConnectionState.Closed , conn.State , "#7");
  137. }
  138. [Test]
  139. public void OpenTest ()
  140. {
  141. conn = new SqlConnection (connectionString);
  142. ArrayList validIncorrectConnStrings = new ArrayList();
  143. string validConnString = connectionString;
  144. validIncorrectConnStrings.Add (
  145. validConnString+"user id=invalidLogin");
  146. validIncorrectConnStrings.Add (
  147. validConnString+"database=invalidDB");
  148. validIncorrectConnStrings.Add (
  149. validConnString+";password=invalidPassword");
  150. validIncorrectConnStrings.Add (
  151. validConnString+";server=invalidServerName");
  152. int count=0;
  153. foreach (string connString in validIncorrectConnStrings) {
  154. count++;
  155. try {
  156. conn.ConnectionString = connString;
  157. conn.Open();
  158. Assert.AreEqual (typeof (SqlException), null,
  159. string.Format (
  160. "#1_{0} Incorrect Connection String",count));
  161. }catch (AssertionException e) {
  162. throw e;
  163. }catch (Exception e) {
  164. Assert.AreEqual (typeof (SqlException), e.GetType (),
  165. "#2 Incorrect Exception" + e.StackTrace);
  166. }
  167. }
  168. // Test connection is Opened for a valid Connection String
  169. conn.ConnectionString = connectionString;
  170. conn.Open ();
  171. Assert.AreEqual (ConnectionState.Open, conn.State,
  172. "#3 Connection State Should be OPEN");
  173. // Test Exception is thrown on opening an OPEN Connection
  174. try {
  175. conn.Open ();
  176. Assert.AreEqual (typeof (InvalidOperationException), null,
  177. "#1 Connection is Already Open");
  178. }catch (AssertionException e) {
  179. throw e;
  180. }catch (Exception e) {
  181. Assert.AreEqual (typeof(InvalidOperationException), e.GetType (),
  182. "#2 Incorect Exception.");
  183. }
  184. conn.Close();
  185. /*
  186. // Test if localhost is assumed when servername is empty/missing
  187. // NOTE : msdotnet contradicts doc
  188. Assumes the server is localhost .. need to test this with mono on windows
  189. conn.ConnectionString = connectionString + "server=;";
  190. try {
  191. conn.Open ();
  192. }catch (Exception e) {
  193. Assert.Fail ("## If server name is not given or empty ,localhost shud be tried");
  194. }
  195. ex = null;
  196. conn.Close ();
  197. */
  198. }
  199. [Test]
  200. public void CreateCommandTest ()
  201. {
  202. conn = new SqlConnection (connectionString);
  203. IDbCommand cmd = conn.CreateCommand ();
  204. Assert.AreSame (conn, cmd.Connection,
  205. "#1 Connection instance should be the same");
  206. }
  207. [Test]
  208. public void CloseTest ()
  209. {
  210. conn = new SqlConnection (connectionString);
  211. conn.Open ();
  212. Assert.AreEqual (ConnectionState.Open, conn.State,
  213. "#1 Connection State should be : Open");
  214. conn.Close ();
  215. Assert.AreEqual (ConnectionState.Closed, conn.State,
  216. "#1 Connection State Should : Closed");
  217. // Test Closing an already closed connection is Valid..
  218. conn.Close ();
  219. }
  220. [Test]
  221. public void DisposeTest ()
  222. {
  223. SqlConnection conn = new SqlConnection (connectionString);
  224. conn.Dispose ();
  225. Assert.AreEqual ("", conn.ConnectionString,
  226. "#1 Dispose shud make the Connection String empty");
  227. Assert.AreEqual (15, conn.ConnectionTimeout,
  228. "#2 Default ConnectionTimeout : 15" );
  229. Assert.AreEqual ("", conn.Database,
  230. "#3 Default Database : empty");
  231. Assert.AreEqual ("", conn.DataSource,
  232. "#4 Default DataSource : empty");
  233. Assert.AreEqual (8192, conn.PacketSize,
  234. "#5 Default Packet Size : 8192");
  235. Assert.AreEqual (Dns.GetHostName().ToUpper (), conn.WorkstationId.ToUpper (),
  236. "#6 Default Workstationid : hostname");
  237. Assert.AreEqual (ConnectionState.Closed, conn.State,
  238. "#7 Default State : CLOSED ");
  239. }
  240. [Test]
  241. public void ChangeDatabaseTest ()
  242. {
  243. conn = new SqlConnection (connectionString);
  244. String database = conn.Database;
  245. //Test if exception is thrown if connection is closed
  246. try {
  247. conn.ChangeDatabase ("database");
  248. Assert.AreEqual (typeof (InvalidOperationException), null,
  249. "#1 Connection is Closed");
  250. }catch (AssertionException e){
  251. throw e;
  252. }catch (Exception e) {
  253. Assert.AreEqual (typeof (InvalidOperationException), e.GetType(),
  254. "#2 Incorrect Exception : " + e.StackTrace);
  255. }
  256. //Test if exception is thrown for invalid Database Names
  257. //need to add more to the list
  258. conn.Open ();
  259. String[] InvalidDatabaseNames = {"", null, " "};
  260. for (int i = 0; i < InvalidDatabaseNames.Length ; ++i) {
  261. try {
  262. conn.ChangeDatabase (InvalidDatabaseNames[i]);
  263. Assert.AreEqual (typeof (ArgumentException), null,
  264. string.Format ("#3_{0} Exception not thrown",i));
  265. }catch (AssertionException e) {
  266. throw e;
  267. }catch (Exception e) {
  268. Assert.AreEqual (typeof(ArgumentException), e.GetType (),
  269. string.Format( "#4_{0} Incorrect Exception : {1}",
  270. i, e.StackTrace));
  271. }
  272. Assert.AreEqual (database, conn.Database,
  273. "#4 The Database shouldnt get changed if Operation Failed");
  274. }
  275. //Test if exception is thrown if database name is non-existent
  276. try {
  277. conn.ChangeDatabase ("invalidDB");
  278. Assert.Fail ("#5 Exception must be thrown if database doesent exist");
  279. }catch (AssertionException e) {
  280. throw e;
  281. }catch (Exception e) {
  282. Assert.AreEqual (typeof(SqlException), e.GetType (),
  283. "#6 Incorrect Exception" + e.StackTrace);
  284. }
  285. conn.Close ();
  286. //Test if '-' is a valid character in a database name
  287. //TODO : Check for database names that have more special Characters..
  288. conn.ConnectionString = connectionString;
  289. conn.Open ();
  290. try {
  291. conn.ChangeDatabase ("mono-test");
  292. Assert.AreEqual ("mono-test", conn.Database,
  293. "#7 Database name should be mono-test");
  294. }catch (AssertionException e) {
  295. throw e;
  296. }catch (Exception e){
  297. Assert.Fail ("#8 Unexpected Exception : DB Name can have a '-' : "
  298. + e);
  299. }
  300. }
  301. [Test]
  302. public void BeginTransactionTest()
  303. {
  304. conn = new SqlConnection (connectionString);
  305. SqlTransaction trans = null ;
  306. try {
  307. trans = conn.BeginTransaction ();
  308. Assert.Fail ("#1 Connection must be Open to Begin a Transaction");
  309. }catch (AssertionException e) {
  310. throw e;
  311. }catch (Exception e) {
  312. Assert.AreEqual (typeof (InvalidOperationException), e.GetType(),
  313. "#2 Incorrect Exception" + e.StackTrace);
  314. }
  315. conn.Open ();
  316. trans = conn.BeginTransaction ();
  317. Assert.AreSame (conn, trans.Connection,
  318. "#3 Transaction should reference the same connection");
  319. Assert.AreEqual (IsolationLevel.ReadCommitted, trans.IsolationLevel,
  320. "#4 Isolation Level shud be ReadCommitted");
  321. trans.Rollback ();
  322. try {
  323. trans = conn.BeginTransaction ();
  324. trans = conn.BeginTransaction ();
  325. conn.BeginTransaction ();
  326. Assert.Fail ("#5 Parallel Transactions are not supported");
  327. }catch (AssertionException e) {
  328. throw e;
  329. }catch (Exception e) {
  330. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  331. "#6 Incorrect Exception" + e.StackTrace);
  332. }finally {
  333. trans.Rollback();
  334. }
  335. try {
  336. trans = conn.BeginTransaction ();
  337. trans.Rollback ();
  338. trans = conn.BeginTransaction ();
  339. trans.Commit();
  340. trans = conn.BeginTransaction ();
  341. }catch (Exception e) {
  342. Assert.Fail ("#7 Transaction can be opened after a rollback/commit");
  343. }finally {
  344. trans.Rollback ();
  345. }
  346. }
  347. [Test]
  348. public void ConnectionStringPropertyTest ()
  349. {
  350. conn = new SqlConnection (connectionString) ;
  351. // Test Repeated Keyoword ..Should take the latest value
  352. conn.ConnectionString = conn.ConnectionString + ";server=RepeatedServer;" ;
  353. Assert.AreEqual ("RepeatedServer", ((SqlConnection)conn).DataSource,
  354. "#1 if keyword is repeated, the latest value should be taken");
  355. conn.ConnectionString += ";database=gen;Initial Catalog=gen1";
  356. Assert.AreEqual ("gen1", conn.Database,
  357. "#2 database and initial catalog are synonyms .. ");
  358. // Test if properties are set correctly
  359. string str = "server=localhost1;database=db;user id=user;";
  360. str += "password=pwd;Workstation ID=workstation;Packet Size=512;";
  361. str += "Connect Timeout=10";
  362. conn.ConnectionString = str;
  363. Assert.AreEqual ("localhost1", conn.DataSource,
  364. "#3 DataSource name should be same as passed");
  365. Assert.AreEqual ("db", conn.Database,
  366. "#4 Database name shud be same as passed");
  367. Assert.AreEqual (ConnectionState.Closed, conn.State,
  368. "#5 Connection shud be in closed state");
  369. Assert.AreEqual ("workstation", conn.WorkstationId,
  370. "#6 Workstation Id shud be same as passed");
  371. Assert.AreEqual (512, conn.PacketSize,
  372. "#7 Packetsize shud be same as passed");
  373. Assert.AreEqual (10, conn.ConnectionTimeout,
  374. "#8 ConnectionTimeout shud be same as passed");
  375. // Test if any leftover values exist from previous invocation.
  376. conn.ConnectionString = connectionString;
  377. conn.ConnectionString = "";
  378. Assert.AreEqual ("", conn.DataSource,
  379. "#9 Datasource shud be reset to Default : Empty");
  380. Assert.AreEqual ("", conn.Database,
  381. "#10 Database shud reset to Default : Empty");
  382. Assert.AreEqual (8192, conn.PacketSize,
  383. "#11 Packetsize shud be reset to Default : 8192");
  384. Assert.AreEqual (15, conn.ConnectionTimeout,
  385. "#12 ConnectionTimeour shud be reset to Default : 15");
  386. Assert.AreEqual (Dns.GetHostName ().ToUpper (), conn.WorkstationId.ToUpper (),
  387. "#13 WorkstationId shud be reset to Default : Hostname");
  388. // Test Argument Exception is thrown for Invalid Connection Strings
  389. foreach (string connString in invalidConnectionStrings) {
  390. try {
  391. conn.ConnectionString = connString;
  392. Assert.Fail (
  393. "#14 Exception should be thrown");
  394. }catch (AssertionException e){
  395. throw e;
  396. }catch (Exception e) {
  397. Assert.AreEqual (typeof (ArgumentException), e.GetType(),
  398. "#15 Incorrect Exception" + e.StackTrace);
  399. }
  400. }
  401. // Test if ConnectionString is read-only when Connection is OPEN
  402. conn.ConnectionString = connectionString;
  403. conn.Open() ;
  404. try {
  405. Assert.AreEqual (conn.State, ConnectionState.Open,
  406. "#16 Connection shud be open");
  407. conn.ConnectionString = "server=localhost;database=tmp;" ;
  408. Assert.Fail (
  409. "#17 ConnectionString should Read-Only when Connection is Open");
  410. }catch (AssertionException e){
  411. throw e;
  412. }catch (Exception e) {
  413. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  414. "#18 Incorrect Exception" + e.StackTrace);
  415. }
  416. conn.Close ();
  417. }
  418. [Test]
  419. public void ServerVersionTest ()
  420. {
  421. conn = new SqlConnection (connectionString);
  422. // Test InvalidOperation Exception is thrown if Connection is CLOSED
  423. try{
  424. string s = conn.ServerVersion;
  425. Assert.Fail (
  426. "#1 InvalidOperation Exception Must be thrown if conn is closed");
  427. }catch (AssertionException e){
  428. throw e;
  429. }catch (Exception e){
  430. Assert.AreEqual(typeof (InvalidOperationException), e.GetType (),
  431. "#2 Incorrect Exception" + e.StackTrace);
  432. }
  433. // Test if Release Version is as per specification.
  434. conn.Open ();
  435. String[] version = conn.ServerVersion.Split ('.') ;
  436. Assert.AreEqual (2, version[0].Length,
  437. "#2 The Major release shud be exactly 2 characters");
  438. Assert.AreEqual (2, version[1].Length,
  439. "#3 The Minor release shud be exactly 2 characters");
  440. Assert.AreEqual (4, version[2].Length,
  441. "#4 The Release version should be exactly 4 digits");
  442. }
  443. [Test]
  444. public void DatabasePropertyTest ()
  445. {
  446. conn = new SqlConnection (connectionString);
  447. string database = conn.Database ;
  448. // Test if database property is updated when a query changes database
  449. conn.Open ();
  450. SqlCommand cmd = new SqlCommand ("use [mono-test]" , conn);
  451. cmd.ExecuteNonQuery ();
  452. Assert.AreEqual ("mono-test", conn.Database,
  453. "#1 DATABASE name shud change if query changes the db");
  454. conn.Close ();
  455. Assert.AreEqual (database, conn.Database,
  456. "#2 Shud be back to default value");
  457. // Test if the database property is reset on re-opening the connection
  458. conn.ConnectionString = connectionString;
  459. conn.Open ();
  460. Assert.AreEqual (database, conn.Database,
  461. "#3 Shud be back to original value");
  462. conn.Close ();
  463. }
  464. [Test]
  465. public void StateChangeEventTest ()
  466. {
  467. conn = new SqlConnection (connectionString);
  468. conn.StateChange += new StateChangeEventHandler (
  469. StateChangeHandlerTest1);
  470. using (conn) {
  471. conn.Open ();
  472. }
  473. Assert.AreEqual (2, stateChangeEventCount,
  474. "#1 The handler shud be called twice");
  475. stateChangeEventCount =0 ;
  476. conn.StateChange -= new StateChangeEventHandler (
  477. StateChangeHandlerTest1);
  478. // NOTE : Need to check the behavior if an exception is raised
  479. // in a handler
  480. }
  481. [Test]
  482. public void DisposedEventTest ()
  483. {
  484. conn = new SqlConnection (connectionString);
  485. conn.Disposed += new EventHandler (DisposedEventHandlerTest1);
  486. conn.Dispose ();
  487. Assert.AreEqual (1, disposedEventCount,
  488. "#1 Disposed eventhandler shud be called");
  489. }
  490. void StateChangeHandlerTest1 (object sender , StateChangeEventArgs e)
  491. {
  492. Assert.IsTrue ((e.CurrentState != e.OriginalState),
  493. "#1 Current and Original state shud be different");
  494. Assert.AreEqual (e.CurrentState, conn.State,
  495. "The conn state and the arg received in event shud be same");
  496. stateChangeEventCount++ ;
  497. }
  498. void DisposedEventHandlerTest1 (object sender , EventArgs e)
  499. {
  500. disposedEventCount++;
  501. }
  502. }
  503. }