SqlConnectionTest.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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.Fail (String.Format (
  159. "#1_{0} Incorrect Connection String",count));
  160. }catch (AssertionException e) {
  161. throw e;
  162. }catch (Exception e) {
  163. Assert.AreEqual (typeof (SqlException), e.GetType (),
  164. "#2 Incorrect Exception" + e.StackTrace);
  165. }
  166. }
  167. // Test connection is Opened for a valid Connection String
  168. conn.ConnectionString = connectionString;
  169. conn.Open ();
  170. Assert.AreEqual (ConnectionState.Open, conn.State,
  171. "#3 Connection State Should be OPEN");
  172. // Test Exception is thrown on opening an OPEN Connection
  173. try {
  174. conn.Open ();
  175. Assert.AreEqual (typeof (InvalidOperationException), null,
  176. "#1 Connection is Already Open");
  177. }catch (AssertionException e) {
  178. throw e;
  179. }catch (Exception e) {
  180. Assert.AreEqual (typeof(InvalidOperationException), e.GetType (),
  181. "#2 Incorect Exception.");
  182. }
  183. conn.Close();
  184. /*
  185. // Test if localhost is assumed when servername is empty/missing
  186. // NOTE : msdotnet contradicts doc
  187. Assumes the server is localhost .. need to test this with mono on windows
  188. conn.ConnectionString = connectionString + "server=;";
  189. try {
  190. conn.Open ();
  191. }catch (Exception e) {
  192. Assert.Fail ("## If server name is not given or empty ,localhost shud be tried");
  193. }
  194. ex = null;
  195. conn.Close ();
  196. */
  197. }
  198. [Test]
  199. public void OpenTest_1 ()
  200. {
  201. SqlConnection conn = new SqlConnection ();
  202. conn.ConnectionString = "";
  203. try {
  204. conn.Open ();
  205. Assert.Fail ("#1 Should throw ArgumentException and not SqlException");
  206. } catch (InvalidOperationException) {
  207. }
  208. conn.ConnectionString = " ";
  209. try {
  210. conn.Open ();
  211. Assert.Fail ("#2 Should throw ArgumentException and not SqlException");
  212. } catch (InvalidOperationException) {
  213. }
  214. }
  215. [Test]
  216. public void CreateCommandTest ()
  217. {
  218. conn = new SqlConnection (connectionString);
  219. IDbCommand cmd = conn.CreateCommand ();
  220. Assert.AreSame (conn, cmd.Connection,
  221. "#1 Connection instance should be the same");
  222. }
  223. [Test]
  224. public void CloseTest ()
  225. {
  226. conn = new SqlConnection (connectionString);
  227. conn.Open ();
  228. Assert.AreEqual (ConnectionState.Open, conn.State,
  229. "#1 Connection State should be : Open");
  230. conn.Close ();
  231. Assert.AreEqual (ConnectionState.Closed, conn.State,
  232. "#1 Connection State Should : Closed");
  233. // Test Closing an already closed connection is Valid..
  234. conn.Close ();
  235. }
  236. [Test]
  237. public void DisposeTest ()
  238. {
  239. SqlConnection conn = new SqlConnection (connectionString);
  240. conn.Dispose ();
  241. Assert.AreEqual ("", conn.ConnectionString,
  242. "#1 Dispose shud make the Connection String empty");
  243. Assert.AreEqual (15, conn.ConnectionTimeout,
  244. "#2 Default ConnectionTimeout : 15" );
  245. Assert.AreEqual ("", conn.Database,
  246. "#3 Default Database : empty");
  247. Assert.AreEqual ("", conn.DataSource,
  248. "#4 Default DataSource : empty");
  249. Assert.AreEqual (8192, conn.PacketSize,
  250. "#5 Default Packet Size : 8192");
  251. Assert.AreEqual (Dns.GetHostName().ToUpper (), conn.WorkstationId.ToUpper (),
  252. "#6 Default Workstationid : hostname");
  253. Assert.AreEqual (ConnectionState.Closed, conn.State,
  254. "#7 Default State : CLOSED ");
  255. conn = new SqlConnection ();
  256. //shud not throw exception
  257. conn.Dispose ();
  258. }
  259. [Test]
  260. public void ChangeDatabaseTest ()
  261. {
  262. conn = new SqlConnection (connectionString);
  263. String database = conn.Database;
  264. //Test if exception is thrown if connection is closed
  265. try {
  266. conn.ChangeDatabase ("database");
  267. Assert.AreEqual (typeof (InvalidOperationException), null,
  268. "#1 Connection is Closed");
  269. }catch (AssertionException e){
  270. throw e;
  271. }catch (Exception e) {
  272. Assert.AreEqual (typeof (InvalidOperationException), e.GetType(),
  273. "#2 Incorrect Exception : " + e.StackTrace);
  274. }
  275. //Test if exception is thrown for invalid Database Names
  276. //need to add more to the list
  277. conn.Open ();
  278. String[] InvalidDatabaseNames = {"", null, " "};
  279. for (int i = 0; i < InvalidDatabaseNames.Length ; ++i) {
  280. try {
  281. conn.ChangeDatabase (InvalidDatabaseNames[i]);
  282. Assert.AreEqual (typeof (ArgumentException), null,
  283. string.Format ("#3_{0} Exception not thrown",i));
  284. }catch (AssertionException e) {
  285. throw e;
  286. }catch (Exception e) {
  287. Assert.AreEqual (typeof(ArgumentException), e.GetType (),
  288. string.Format( "#4_{0} Incorrect Exception : {1}",
  289. i, e.StackTrace));
  290. }
  291. Assert.AreEqual (database, conn.Database,
  292. "#4 The Database shouldnt get changed if Operation Failed");
  293. }
  294. //Test if exception is thrown if database name is non-existent
  295. try {
  296. conn.ChangeDatabase ("invalidDB");
  297. Assert.Fail ("#5 Exception must be thrown if database doesent exist");
  298. }catch (AssertionException e) {
  299. throw e;
  300. }catch (Exception e) {
  301. Assert.AreEqual (typeof(SqlException), e.GetType (),
  302. "#6 Incorrect Exception" + e.StackTrace);
  303. }
  304. conn.Close ();
  305. //Test if '-' is a valid character in a database name
  306. //TODO : Check for database names that have more special Characters..
  307. conn.ConnectionString = connectionString;
  308. conn.Open ();
  309. try {
  310. conn.ChangeDatabase ("mono-test");
  311. Assert.AreEqual ("mono-test", conn.Database,
  312. "#7 Database name should be mono-test");
  313. }catch (AssertionException e) {
  314. throw e;
  315. }catch (Exception e){
  316. Assert.Fail ("#8 Unexpected Exception : DB Name can have a '-' : "
  317. + e);
  318. }
  319. }
  320. [Test]
  321. public void BeginTransactionTest()
  322. {
  323. conn = new SqlConnection (connectionString);
  324. SqlTransaction trans = null ;
  325. try {
  326. trans = conn.BeginTransaction ();
  327. Assert.Fail ("#1 Connection must be Open to Begin a Transaction");
  328. }catch (AssertionException e) {
  329. throw e;
  330. }catch (Exception e) {
  331. Assert.AreEqual (typeof (InvalidOperationException), e.GetType(),
  332. "#2 Incorrect Exception" + e.StackTrace);
  333. }
  334. conn.Open ();
  335. trans = conn.BeginTransaction ();
  336. Assert.AreSame (conn, trans.Connection,
  337. "#3 Transaction should reference the same connection");
  338. Assert.AreEqual (IsolationLevel.ReadCommitted, trans.IsolationLevel,
  339. "#4 Isolation Level shud be ReadCommitted");
  340. trans.Rollback ();
  341. try {
  342. trans = conn.BeginTransaction ();
  343. trans = conn.BeginTransaction ();
  344. conn.BeginTransaction ();
  345. Assert.Fail ("#5 Parallel Transactions are not supported");
  346. }catch (AssertionException e) {
  347. throw e;
  348. }catch (Exception e) {
  349. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  350. "#6 Incorrect Exception" + e.StackTrace);
  351. }finally {
  352. trans.Rollback();
  353. }
  354. try {
  355. trans = conn.BeginTransaction ();
  356. trans.Rollback ();
  357. trans = conn.BeginTransaction ();
  358. trans.Commit();
  359. trans = conn.BeginTransaction ();
  360. }catch (Exception e) {
  361. Assert.Fail ("#7 Transaction can be opened after a rollback/commit");
  362. }finally {
  363. trans.Rollback ();
  364. }
  365. }
  366. [Test]
  367. public void ConnectionStringPropertyTest ()
  368. {
  369. conn = new SqlConnection (connectionString) ;
  370. // Test Repeated Keyoword ..Should take the latest value
  371. conn.ConnectionString = conn.ConnectionString + ";server=RepeatedServer;" ;
  372. Assert.AreEqual ("RepeatedServer", ((SqlConnection)conn).DataSource,
  373. "#1 if keyword is repeated, the latest value should be taken");
  374. conn.ConnectionString += ";database=gen;Initial Catalog=gen1";
  375. Assert.AreEqual ("gen1", conn.Database,
  376. "#2 database and initial catalog are synonyms .. ");
  377. // Test if properties are set correctly
  378. string str = "server=localhost1;database=db;user id=user;";
  379. str += "password=pwd;Workstation ID=workstation;Packet Size=512;";
  380. str += "Connect Timeout=10";
  381. conn.ConnectionString = str;
  382. Assert.AreEqual ("localhost1", conn.DataSource,
  383. "#3 DataSource name should be same as passed");
  384. Assert.AreEqual ("db", conn.Database,
  385. "#4 Database name shud be same as passed");
  386. Assert.AreEqual (ConnectionState.Closed, conn.State,
  387. "#5 Connection shud be in closed state");
  388. Assert.AreEqual ("workstation", conn.WorkstationId,
  389. "#6 Workstation Id shud be same as passed");
  390. Assert.AreEqual (512, conn.PacketSize,
  391. "#7 Packetsize shud be same as passed");
  392. Assert.AreEqual (10, conn.ConnectionTimeout,
  393. "#8 ConnectionTimeout shud be same as passed");
  394. // Test if any leftover values exist from previous invocation.
  395. conn.ConnectionString = connectionString;
  396. conn.ConnectionString = "";
  397. Assert.AreEqual ("", conn.DataSource,
  398. "#9 Datasource shud be reset to Default : Empty");
  399. Assert.AreEqual ("", conn.Database,
  400. "#10 Database shud reset to Default : Empty");
  401. Assert.AreEqual (8192, conn.PacketSize,
  402. "#11 Packetsize shud be reset to Default : 8192");
  403. Assert.AreEqual (15, conn.ConnectionTimeout,
  404. "#12 ConnectionTimeour shud be reset to Default : 15");
  405. Assert.AreEqual (Dns.GetHostName ().ToUpper (), conn.WorkstationId.ToUpper (),
  406. "#13 WorkstationId shud be reset to Default : Hostname");
  407. // Test Argument Exception is thrown for Invalid Connection Strings
  408. foreach (string connString in invalidConnectionStrings) {
  409. try {
  410. conn.ConnectionString = connString;
  411. Assert.Fail (
  412. "#14 Exception should be thrown");
  413. }catch (AssertionException e){
  414. throw e;
  415. }catch (Exception e) {
  416. Assert.AreEqual (typeof (ArgumentException), e.GetType(),
  417. "#15 Incorrect Exception" + e.StackTrace);
  418. }
  419. }
  420. // Test if ConnectionString is read-only when Connection is OPEN
  421. conn.ConnectionString = connectionString;
  422. conn.Open() ;
  423. try {
  424. Assert.AreEqual (conn.State, ConnectionState.Open,
  425. "#16 Connection shud be open");
  426. conn.ConnectionString = "server=localhost;database=tmp;" ;
  427. Assert.Fail (
  428. "#17 ConnectionString should Read-Only when Connection is Open");
  429. }catch (AssertionException e){
  430. throw e;
  431. }catch (Exception e) {
  432. Assert.AreEqual (typeof(InvalidOperationException), e.GetType(),
  433. "#18 Incorrect Exception" + e.StackTrace);
  434. }
  435. conn.Close ();
  436. }
  437. [Test]
  438. public void ServerVersionTest ()
  439. {
  440. conn = new SqlConnection (connectionString);
  441. // Test InvalidOperation Exception is thrown if Connection is CLOSED
  442. try{
  443. string s = conn.ServerVersion;
  444. Assert.Fail (
  445. "#1 InvalidOperation Exception Must be thrown if conn is closed");
  446. }catch (AssertionException e){
  447. throw e;
  448. }catch (Exception e){
  449. Assert.AreEqual(typeof (InvalidOperationException), e.GetType (),
  450. "#2 Incorrect Exception" + e.StackTrace);
  451. }
  452. // Test if Release Version is as per specification.
  453. conn.Open ();
  454. String[] version = conn.ServerVersion.Split ('.') ;
  455. Assert.AreEqual (2, version[0].Length,
  456. "#2 The Major release shud be exactly 2 characters");
  457. Assert.AreEqual (2, version[1].Length,
  458. "#3 The Minor release shud be exactly 2 characters");
  459. Assert.AreEqual (4, version[2].Length,
  460. "#4 The Release version should be exactly 4 digits");
  461. }
  462. [Test]
  463. public void DatabasePropertyTest ()
  464. {
  465. conn = new SqlConnection (connectionString);
  466. string database = conn.Database ;
  467. // Test if database property is updated when a query changes database
  468. conn.Open ();
  469. SqlCommand cmd = new SqlCommand ("use [mono-test]" , conn);
  470. cmd.ExecuteNonQuery ();
  471. Assert.AreEqual ("mono-test", conn.Database,
  472. "#1 DATABASE name shud change if query changes the db");
  473. conn.Close ();
  474. Assert.AreEqual (database, conn.Database,
  475. "#2 Shud be back to default value");
  476. // Test if the database property is reset on re-opening the connection
  477. conn.ConnectionString = connectionString;
  478. conn.Open ();
  479. Assert.AreEqual (database, conn.Database,
  480. "#3 Shud be back to original value");
  481. conn.Close ();
  482. }
  483. [Test]
  484. public void StateChangeEventTest ()
  485. {
  486. conn = new SqlConnection (connectionString);
  487. conn.StateChange += new StateChangeEventHandler (
  488. StateChangeHandlerTest1);
  489. using (conn) {
  490. conn.Open ();
  491. }
  492. Assert.AreEqual (2, stateChangeEventCount,
  493. "#1 The handler shud be called twice");
  494. stateChangeEventCount =0 ;
  495. conn.StateChange -= new StateChangeEventHandler (
  496. StateChangeHandlerTest1);
  497. // NOTE : Need to check the behavior if an exception is raised
  498. // in a handler
  499. }
  500. [Test]
  501. public void DisposedEventTest ()
  502. {
  503. conn = new SqlConnection (connectionString);
  504. conn.Disposed += new EventHandler (DisposedEventHandlerTest1);
  505. conn.Dispose ();
  506. Assert.AreEqual (1, disposedEventCount,
  507. "#1 Disposed eventhandler shud be called");
  508. }
  509. void StateChangeHandlerTest1 (object sender , StateChangeEventArgs e)
  510. {
  511. Assert.IsTrue ((e.CurrentState != e.OriginalState),
  512. "#1 Current and Original state shud be different");
  513. Assert.AreEqual (e.CurrentState, conn.State,
  514. "The conn state and the arg received in event shud be same");
  515. stateChangeEventCount++ ;
  516. }
  517. void DisposedEventHandlerTest1 (object sender , EventArgs e)
  518. {
  519. disposedEventCount++;
  520. }
  521. }
  522. }