Tests.cs 14.3 KB
Newer Older
S
Sam Saffron 已提交
1 2 3
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
M
mgravell 已提交
4
using System.Linq;
5
using Dapper;
6 7
using System.Data.SqlServerCe;
using System.IO;
S
Sam Saffron 已提交
8 9 10

namespace SqlMapper
{
S
Sam Saffron 已提交
11
    static class Assert
S
Sam Saffron 已提交
12
    {
S
Sam Saffron 已提交
13

14
        public static void IsEqualTo<T>(this T obj, T other)
S
Sam Saffron 已提交
15 16 17 18 19 20 21
        {
            if (!obj.Equals(other))
            {
                throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
            }
        }

22
        public static void IsSequenceEqualTo<T>(this IEnumerable<T> obj, IEnumerable<T> other)
S
Sam Saffron 已提交
23
        {
S
Sam Saffron 已提交
24
            if (!obj.SequenceEqual(other))
S
Sam Saffron 已提交
25
            {
S
Sam Saffron 已提交
26
                throw new ApplicationException(string.Format("{0} should be equals to {1}", obj, other));
S
Sam Saffron 已提交
27 28 29
            }
        }

S
Sam Saffron 已提交
30
        public static void IsFalse(this bool b)
S
Sam Saffron 已提交
31
        {
S
Sam Saffron 已提交
32
            if (b)
S
Sam Saffron 已提交
33
            {
S
Sam Saffron 已提交
34
                throw new ApplicationException("Expected false");
S
Sam Saffron 已提交
35 36 37
            }
        }

38 39 40 41 42 43 44 45
        public static void IsTrue(this bool b)
        {
            if (b)
            {
                throw new ApplicationException("Expected true");
            }
        }

S
Sam Saffron 已提交
46 47 48 49 50 51 52
        public static void IsNull(this object obj)
        {
            if (obj != null)
            {
                throw new ApplicationException("Expected null");
            }
        }
S
Sam Saffron 已提交
53

S
Sam Saffron 已提交
54 55 56 57 58
    }

    class Tests
    {
       
S
Sam Saffron 已提交
59 60 61 62
        SqlConnection connection = Program.GetOpenConnection();

        public void SelectListInt()
        {
63
            connection.Query<int>("select 1 union all select 2 union all select 3")
64
              .IsSequenceEqualTo(new[] { 1, 2, 3 });
S
Sam Saffron 已提交
65 66 67 68
        }

        public void PassInIntArray()
        {
69
            connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 }.AsEnumerable() })
70
             .IsSequenceEqualTo(new[] { 1, 2, 3 });
S
Sam Saffron 已提交
71
        }
S
Sam Saffron 已提交
72

S
Sam Saffron 已提交
73 74 75

        public void TestDoubleParam()
        {
76
            connection.Query<double>("select @d", new { d = 0.1d }).First()
77
                .IsEqualTo(0.1d);
S
Sam Saffron 已提交
78 79 80 81
        }

        public void TestBoolParam()
        {
82
            connection.Query<bool>("select @b", new { b = false }).First()
S
Sam Saffron 已提交
83
                .IsFalse();
S
Sam Saffron 已提交
84 85 86 87
        }

        public void TestStrings()
        {
88
            connection.Query<string>(@"select 'a' a union select 'b'")
89
                .IsSequenceEqualTo(new[] { "a", "b" });
S
Sam Saffron 已提交
90 91
        }

S
Sam Saffron 已提交
92 93 94 95 96 97 98 99 100 101
        public class Dog
        {
            public int? Age { get; set; }
            public Guid Id { get; set; }
            public string Name { get; set; }
            public float? Weight { get; set; }

            public int IgnoredProperty { get { return 1; } }
        }

102 103 104
        public void TestExtraFields()
        {
            var guid = Guid.NewGuid();
105
            var dog = connection.Query<Dog>("select '' as Extra, 1 as Age, 0.1 as Name1 , Id = @id", new { Id = guid});
106 107 108 109 110 111 112 113 114 115 116 117

            dog.Count()
               .IsEqualTo(1);

            dog.First().Age
                .IsEqualTo(1);

            dog.First().Id
                .IsEqualTo(guid);
        }


118
        public void TestStrongType()
S
Sam Saffron 已提交
119
        {
120
            var guid = Guid.NewGuid();
121
            var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
S
Sam Saffron 已提交
122 123
            
            dog.Count()
124
                .IsEqualTo(1);
S
Sam Saffron 已提交
125 126 127

            dog.First().Age
                .IsNull();
128 129

            dog.First().Id
130
                .IsEqualTo(guid);
S
Sam Saffron 已提交
131 132
        }

S
Sam Saffron 已提交
133 134
        public void TestSimpleNull()
        {
135
            connection.Query<DateTime?>("select null").First().IsNull();
S
Sam Saffron 已提交
136
        }
137

S
Sam Saffron 已提交
138 139
        public void TestExpando()
        {
140 141
            var rows = connection.Query("select 1 A, 2 B union all select 3, 4").ToList();
            
S
Sam Saffron 已提交
142
            ((int)rows[0].A)
143
                .IsEqualTo(1);
S
Sam Saffron 已提交
144 145

            ((int)rows[0].B)
146
                .IsEqualTo(2);
S
Sam Saffron 已提交
147 148

            ((int)rows[1].A)
149
                .IsEqualTo(3);
S
Sam Saffron 已提交
150 151

            ((int)rows[1].B)
152
                .IsEqualTo(4);
S
Sam Saffron 已提交
153
        }
S
Sam Saffron 已提交
154 155

        public void TestStringList()
S
Sam Saffron 已提交
156
        {
157
            connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new {strings = new[] {"a","b","c"}})
158
                .IsSequenceEqualTo(new[] {"a","b","c"});
S
Sam Saffron 已提交
159 160 161

             connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new { strings = new string[0] })
	                .IsSequenceEqualTo(new string[0]);
S
Sam Saffron 已提交
162 163
        }

S
Sam Saffron 已提交
164 165
        public void TestExecuteCommand()
        {
166
            connection.Execute(@"
S
Sam Saffron 已提交
167 168 169 170 171 172
    set nocount on 
    create table #t(i int) 
    set nocount off 
    insert #t 
    select @a a union all select @b 
    set nocount on 
173
    drop table #t", new {a=1, b=2 }).IsEqualTo(2);
S
Sam Saffron 已提交
174 175
        }

S
Sam Saffron 已提交
176 177 178
        public void TestMassiveStrings()
        { 
            var str = new string('X', 20000);
179
            connection.Query<string>("select @a", new { a = str }).First()
180
                .IsEqualTo(str);
S
Sam Saffron 已提交
181 182
        }

183 184 185 186 187 188 189 190 191 192 193
        class TestObj
        {
            public int _internal;
            internal int Internal { set { _internal = value; } }

            public int _priv;
            internal int Priv { set { _priv = value; } }
        }

        public void TestSetInternal()
        {
194
            connection.Query<TestObj>("select 10 as [Internal]").First()._internal.IsEqualTo(10);
195 196 197 198
        }

        public void TestSetPrivate()
        {
199
            connection.Query<TestObj>("select 10 as [Priv]").First()._priv.IsEqualTo(10);
200 201
        }

202 203
        public void TestEnumeration()
        {
204
            var en = connection.Query<int>("select 1 as one", buffered: false);
205 206 207
            bool gotException = false;
            try
            {
208
                connection.Query<int>("select 1 as one", buffered: false);
209 210 211 212 213 214 215 216 217
            }
            catch (Exception)
            {
                gotException = true;
            }

            var realItems = en.ToList();

            // should not exception, since enumertated
218
            en = connection.Query<int>("select 1 as one", buffered: false);
219 220 221 222 223 224

            gotException.IsTrue();
        }

        public void TestEnumerationDynamic()
        {
225
            var en = connection.Query("select 1 as one", buffered: false);
226 227 228
            bool gotException = false;
            try
            {
229
                connection.Query("select 1 as one", buffered: false);
230 231 232 233 234 235 236 237 238 239
            }
            catch (Exception)
            {
                gotException = true;
            }

            int i = en.First().one;
            i.IsEqualTo(1);

            // should not exception, since enumertated
240
            en = connection.Query("select 1 as one",buffered:false);
241 242 243

            gotException.IsTrue();
        }
244

S
Sam Saffron 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258

        class User 
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        class Post 
        {
            public int Id { get; set; }
            public User Owner { get; set; }
            public string Content { get; set; }
        }
        public void TestMultiMap()
        {
S
Sam Saffron 已提交
259 260 261
            var createSql = @"
                create table #Users (Id int, Name varchar(20))
                create table #Posts (Id int, OwnerId int, Content varchar(20))
S
Sam Saffron 已提交
262

S
style  
Sam Saffron 已提交
263
                insert #Users values(99, 'Sam')
S
Sam Saffron 已提交
264 265
                insert #Users values(2, 'I am')

S
style  
Sam Saffron 已提交
266 267
                insert #Posts values(1, 99, 'Sams Post1')
                insert #Posts values(2, 99, 'Sams Post2')
S
Sam Saffron 已提交
268 269 270 271
                insert #Posts values(3, null, 'no ones post')
";
            connection.Execute(createSql);

S
style  
Sam Saffron 已提交
272 273 274 275 276
            var sql = 
@"select * from #Posts p 
left join #Users u on u.Id = p.OwnerId 
Order by p.Id";

277
            var data = connection.Query<Post, User>(sql, (post, user) => { post.Owner = user; }).ToList();
S
style  
Sam Saffron 已提交
278 279 280 281 282 283
            var p = data.First();
           
            p.Content.IsEqualTo("Sams Post1");
            p.Id.IsEqualTo(1);
            p.Owner.Name.IsEqualTo("Sam");
            p.Owner.Id.IsEqualTo(99);
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

            data[2].Owner.IsNull();

            connection.Execute("drop table #Users drop table #Posts");
        }


        public void TestMultiMapDynamic()
        {
            var createSql = @"
                create table #Users (Id int, Name varchar(20))
                create table #Posts (Id int, OwnerId int, Content varchar(20))

                insert #Users values(99, 'Sam')
                insert #Users values(2, 'I am')

                insert #Posts values(1, 99, 'Sams Post1')
                insert #Posts values(2, 99, 'Sams Post2')
                insert #Posts values(3, null, 'no ones post')
";
            connection.Execute(createSql);

            var sql =
@"select * from #Posts p 
left join #Users u on u.Id = p.OwnerId 
Order by p.Id";

            var data = connection.Query<dynamic, dynamic>(sql, (post, user) => { post.Owner = user; }).ToList();
            var p = data.First();

            // hairy extension method support for dynamics
            ((string)p.Content).IsEqualTo("Sams Post1");
            ((int)p.Id).IsEqualTo(1);
            ((string)p.Owner.Name).IsEqualTo("Sam");
            ((int)p.Owner.Id).IsEqualTo(99);

            ((object)data[2].Owner).IsNull();

            connection.Execute("drop table #Users drop table #Posts");
S
Sam Saffron 已提交
323
        }
324

S
Sam Saffron 已提交
325 326
        public void TestMultiMappingVariations()
        {
S
Sam Saffron 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
            var sql = @"select 1 as Id, 'a' as Content, 2 as Id, 'b' as Content, 3 as Id, 'c' as Content, 4 as Id, 'd' as Content, 5 as Id, 'e' as Content";
            
            var order = connection.Query<dynamic, dynamic, dynamic>(sql, (o, owner, creator) => { o.Owner = owner; o.Creator = creator; }).First();

            Assert.IsEqualTo(order.Id, 1);
            Assert.IsEqualTo(order.Content, "a");
            Assert.IsEqualTo(order.Owner.Id, 2);
            Assert.IsEqualTo(order.Owner.Content, "b");
            Assert.IsEqualTo(order.Creator.Id, 3);
            Assert.IsEqualTo(order.Creator.Content, "c");

            order = connection.Query<dynamic, dynamic, dynamic, dynamic>(sql, (o, owner, creator, address) => 
                { 
                  o.Owner = owner; 
                  o.Creator = creator; 
                  o.Owner.Address = address;
                }).First();

            Assert.IsEqualTo(order.Id, 1);
            Assert.IsEqualTo(order.Content, "a");
            Assert.IsEqualTo(order.Owner.Id, 2);
            Assert.IsEqualTo(order.Owner.Content, "b");
            Assert.IsEqualTo(order.Creator.Id, 3);
            Assert.IsEqualTo(order.Creator.Content, "c");
            Assert.IsEqualTo(order.Owner.Address.Id, 4);
            Assert.IsEqualTo(order.Owner.Address.Content, "d");

            order = connection.Query<dynamic, dynamic, dynamic, dynamic, dynamic>(sql, (a, b, c, d, e) => { a.B = b; a.C = c; a.C.D = d; a.E = e; }).First();

            Assert.IsEqualTo(order.Id, 1);
            Assert.IsEqualTo(order.Content, "a");
            Assert.IsEqualTo(order.B.Id, 2);
            Assert.IsEqualTo(order.B.Content, "b");
            Assert.IsEqualTo(order.C.Id, 3);
            Assert.IsEqualTo(order.C.Content, "c");
            Assert.IsEqualTo(order.C.D.Id, 4);
            Assert.IsEqualTo(order.C.D.Content, "d");
            Assert.IsEqualTo(order.E.Id, 5);
            Assert.IsEqualTo(order.E.Content, "e");
S
Sam Saffron 已提交
366 367 368

        }

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        class InheritanceTest1
        {
            public string Base1 { get; set; }
            public string Base2 { get; private set; }
        }

        class InheritanceTest2 : InheritanceTest1
        {
            public string Derived1 { get; set; }
            public string Derived2 { get; private set; }
        }

        public void TestInheritance()
        {
            // Test that inheritance works.
            var list = connection.Query<InheritanceTest2>("select 'One' as Derived1, 'Two' as Derived2, 'Three' as Base1, 'Four' as Base2");
            list.First().Derived1.IsEqualTo("One");
            list.First().Derived2.IsEqualTo("Two");
            list.First().Base1.IsEqualTo("Three");
            list.First().Base2.IsEqualTo("Four");
        }

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

        public class PostCE
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public string Body { get; set; }

            public AuthorCE Author { get; set; }
        }

        public class AuthorCE
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }

        public void MultiRSSqlCE()
        {
            if (File.Exists("Test.sdf"))
                File.Delete("Test.sdf");

            var cnnStr = "Data Source = Test.sdf;";
            var engine = new SqlCeEngine(cnnStr);
            engine.CreateDatabase();
            
            using (var cnn = new SqlCeConnection(cnnStr))
            {
                cnn.Open();

                cnn.Execute("create table Posts (ID int, Title nvarchar(50), Body nvarchar(50), AuthorID int)");
                cnn.Execute("create table Authors (ID int, Name nvarchar(50))");

                cnn.Execute("insert Posts values (1,'title','body',1)");
                cnn.Execute("insert Posts values(2,'title2','body2',null)");
                cnn.Execute("insert Authors values(1,'sam')");

S
Sam Saffron 已提交
427
                var data = cnn.Query<PostCE, AuthorCE>(@"select * from Posts p left join Authors a on a.ID = p.AuthorID", (post, author) => { post.Author = author; }).ToList();
428
                var firstPost = data.First();
S
Sam Saffron 已提交
429 430 431
                firstPost.Title.IsEqualTo("title");
                firstPost.Author.Name.IsEqualTo("sam");
                data[1].Author.IsNull();
432 433 434
                cnn.Close();
            }
        }
S
Sam Saffron 已提交
435 436
        /* TODO:
         * 
S
Sam Saffron 已提交
437 438 439 440 441 442 443 444
        public void TestMagicParam()
        {
            // magic params allow you to pass in single params without using an anon class
            // this test fails for now, but I would like to support a single param by parsing the sql with regex and remapping. 

            var first = connection.Query("select @a as a", 1).First();
            Assert.IsEqualTo(first.a, 1);
        }
S
Sam Saffron 已提交
445
         * */
S
Sam Saffron 已提交
446

S
Sam Saffron 已提交
447 448
    }
}