1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 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 323 324 325 326 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 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 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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Json
{
/// <summary>
/// Settings used by the <see cref="InstanceCreator"/> class.
/// </summary>
public static class CreatorSettings
{
static CreatorSettings()
{
MaxArrayLength = 10;
MaxListLength = 10;
MaxStringLength = 100;
CreateOnlyAsciiChars = false;
DontCreateSurrogateChars = false;
CreateDateTimeWithSubMilliseconds = true;
NullValueProbability = 0.01;
AvoidStackOverflowDueToTypeCycles = false;
CreatorSurrogate = null;
}
/// <summary>
/// Gets or sets the maximum length of arrays created by the <see cref="InstanceCreator"/>.
/// </summary>
public static int MaxArrayLength { get; set; }
/// <summary>
/// Gets or sets the maximum length of lists created by the <see cref="InstanceCreator"/>.
/// </summary>
public static int MaxListLength { get; set; }
/// <summary>
/// Gets or sets the maximum length of strings created by the <see cref="InstanceCreator"/>.
/// </summary>
public static int MaxStringLength { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether only ascii chars should be used when creating strings.
/// </summary>
public static bool CreateOnlyAsciiChars { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether chars in the surrogate range can be returned by the
/// <see cref="InstanceCreator"/> when creating char instances.
/// </summary>
public static bool DontCreateSurrogateChars { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether <see cref="DateTime"/> values created by the
/// <see cref="InstanceCreator"/> can have submillisecond precision.
/// </summary>
public static bool CreateDateTimeWithSubMilliseconds { get; set; }
/// <summary>
/// Gets or sets a value (0-1) indicating the probability of the <see cref="InstanceCreator"/>
/// returning a <code>null</code> value when creating instances of class types.
/// </summary>
public static double NullValueProbability { get; set; }
/// <summary>
/// Gets or sets a flag indicating whether the protection against stack overflow
/// for cyclic types is enabled. If this flag is set, whenever a type which has already
/// been created up in the stack is created again, the <see cref="InstanceCreator"/>
/// will return the default value for that type.
/// </summary>
public static bool AvoidStackOverflowDueToTypeCycles { get; set; }
/// <summary>
/// Gets or sets the instance of an <see cref="InstanceCreatorSurrogate"/> which can intercept
/// requests to create instances on the <see cref="InstanceCreator"/>.
/// </summary>
public static InstanceCreatorSurrogate CreatorSurrogate { get; set; }
}
/// <summary>
/// Utility class used to create test instances of primitive types.
/// </summary>
public static class PrimitiveCreator
{
static readonly Regex RelativeIPv6UriRegex = new Regex(@"^\/\/(.+\@)?\[\:\:\d\]");
static Dictionary<Type, MethodInfo> creators;
static PrimitiveCreator()
{
Type primitiveCreatorType = typeof(PrimitiveCreator);
creators = new Dictionary<Type, MethodInfo>();
creators.Add(typeof(bool), primitiveCreatorType.GetMethod("CreateInstanceOfBoolean", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(byte), primitiveCreatorType.GetMethod("CreateInstanceOfByte", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(char), primitiveCreatorType.GetMethod("CreateInstanceOfChar", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(DateTime), primitiveCreatorType.GetMethod("CreateInstanceOfDateTime", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(DateTimeOffset), primitiveCreatorType.GetMethod("CreateInstanceOfDateTimeOffset", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(decimal), primitiveCreatorType.GetMethod("CreateInstanceOfDecimal", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(double), primitiveCreatorType.GetMethod("CreateInstanceOfDouble", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(Guid), primitiveCreatorType.GetMethod("CreateInstanceOfGuid", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(short), primitiveCreatorType.GetMethod("CreateInstanceOfInt16", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(int), primitiveCreatorType.GetMethod("CreateInstanceOfInt32", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(long), primitiveCreatorType.GetMethod("CreateInstanceOfInt64", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(object), primitiveCreatorType.GetMethod("CreateInstanceOfObject", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(sbyte), primitiveCreatorType.GetMethod("CreateInstanceOfSByte", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(float), primitiveCreatorType.GetMethod("CreateInstanceOfSingle", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(string), primitiveCreatorType.GetMethod("CreateInstanceOfString", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Random) }, null));
creators.Add(typeof(ushort), primitiveCreatorType.GetMethod("CreateInstanceOfUInt16", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(uint), primitiveCreatorType.GetMethod("CreateInstanceOfUInt32", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(ulong), primitiveCreatorType.GetMethod("CreateInstanceOfUInt64", BindingFlags.Public | BindingFlags.Static));
creators.Add(typeof(Uri), primitiveCreatorType.GetMethod("CreateInstanceOfUri", BindingFlags.Public | BindingFlags.Static));
}
/// <summary>
/// Creates an instance of the <see cref="Boolean"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Boolean"/> type.</returns>
public static bool CreateInstanceOfBoolean(Random rndGen)
{
return rndGen.Next(2) == 0;
}
/// <summary>
/// Creates an instance of the <see cref="Byte"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Byte"/> type.</returns>
public static byte CreateInstanceOfByte(Random rndGen)
{
byte[] rndValue = new byte[1];
rndGen.NextBytes(rndValue);
return rndValue[0];
}
/// <summary>
/// Creates an instance of the <see cref="Char"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Char"/> type.</returns>
public static char CreateInstanceOfChar(Random rndGen)
{
if (CreatorSettings.CreateOnlyAsciiChars)
{
return (char)rndGen.Next(0x20, 0x7F);
}
else if (CreatorSettings.DontCreateSurrogateChars)
{
char c;
do
{
c = (char)rndGen.Next((int)Char.MinValue, (int)Char.MaxValue);
}
while (Char.IsSurrogate(c));
return c;
}
else
{
return (char)rndGen.Next((int)Char.MinValue, (int)Char.MaxValue + 1);
}
}
/// <summary>
/// Creates an instance of the <see cref="DateTime"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="DateTime"/> type.</returns>
public static System.DateTime CreateInstanceOfDateTime(Random rndGen)
{
long temp = CreateInstanceOfInt64(rndGen);
temp = Math.Abs(temp);
DateTime result;
try
{
result = new DateTime(temp % (DateTime.MaxValue.Ticks + 1));
}
catch (ArgumentOutOfRangeException)
{
result = DateTime.Now;
}
int kind = rndGen.Next(3);
switch (kind)
{
case 0:
result = DateTime.SpecifyKind(result, DateTimeKind.Local);
break;
case 1:
result = DateTime.SpecifyKind(result, DateTimeKind.Unspecified);
break;
default:
result = DateTime.SpecifyKind(result, DateTimeKind.Utc);
break;
}
if (!CreatorSettings.CreateDateTimeWithSubMilliseconds)
{
result = new DateTime(
result.Year,
result.Month,
result.Day,
result.Hour,
result.Minute,
result.Second,
result.Millisecond,
result.Kind);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="DateTimeOffset"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="DateTimeOffset"/> type.</returns>
public static System.DateTimeOffset CreateInstanceOfDateTimeOffset(Random rndGen)
{
DateTime temp = CreateInstanceOfDateTime(rndGen);
temp = DateTime.SpecifyKind(temp, DateTimeKind.Unspecified);
int offsetMinutes = rndGen.Next(-14 * 60, 14 * 60);
DateTimeOffset result = new DateTimeOffset(temp, TimeSpan.FromMinutes(offsetMinutes));
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Decimal"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Decimal"/> type.</returns>
public static decimal CreateInstanceOfDecimal(Random rndGen)
{
int low = CreateInstanceOfInt32(rndGen);
int mid = CreateInstanceOfInt32(rndGen);
int high = CreateInstanceOfInt32(rndGen);
bool isNegative = rndGen.Next(2) == 0;
const int MaxDecimalScale = 28;
byte scale = (byte)rndGen.Next(0, MaxDecimalScale + 1);
return new decimal(low, mid, high, isNegative, scale);
}
/// <summary>
/// Creates an instance of the <see cref="Double"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Double"/> type.</returns>
public static double CreateInstanceOfDouble(Random rndGen)
{
bool negative = rndGen.Next(2) == 0;
int temp = rndGen.Next(40);
double result;
switch (temp)
{
case 0: return Double.NaN;
case 1: return Double.PositiveInfinity;
case 2: return Double.NegativeInfinity;
case 3: return Double.MinValue;
case 4: return Double.MaxValue;
case 5: return Double.Epsilon;
default:
result = (double)(rndGen.NextDouble() * 100000);
if (negative)
{
result = -result;
}
return result;
}
}
/// <summary>
/// Creates an instance of the <see cref="Guid"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Guid"/> type.</returns>
public static System.Guid CreateInstanceOfGuid(Random rndGen)
{
byte[] temp = new byte[16];
rndGen.NextBytes(temp);
return new Guid(temp);
}
/// <summary>
/// Creates an instance of the <see cref="Int16"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Int16"/> type.</returns>
public static short CreateInstanceOfInt16(Random rndGen)
{
byte[] rndValue = new byte[2];
rndGen.NextBytes(rndValue);
short result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (short)(result << 8);
result = (short)(result | (short)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Int32"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Int32"/> type.</returns>
public static int CreateInstanceOfInt32(Random rndGen)
{
byte[] rndValue = new byte[4];
rndGen.NextBytes(rndValue);
int result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (int)(result << 8);
result = (int)(result | (int)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Int64"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Int64"/> type.</returns>
public static long CreateInstanceOfInt64(Random rndGen)
{
byte[] rndValue = new byte[8];
rndGen.NextBytes(rndValue);
long result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (long)(result << 8);
result = (long)(result | (long)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Object"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Object"/> type.</returns>
public static object CreateInstanceOfObject(Random rndGen)
{
return (rndGen.Next(5) == 0) ? null : new object();
}
/// <summary>
/// Creates an instance of the <see cref="SByte"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="SByte"/> type.</returns>
[CLSCompliant(false)]
public static sbyte CreateInstanceOfSByte(Random rndGen)
{
byte[] rndValue = new byte[1];
rndGen.NextBytes(rndValue);
sbyte result = (sbyte)rndValue[0];
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Single"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Single"/> type.</returns>
public static float CreateInstanceOfSingle(Random rndGen)
{
bool negative = rndGen.Next(2) == 0;
int temp = rndGen.Next(40);
float result;
switch (temp)
{
case 0: return Single.NaN;
case 1: return Single.PositiveInfinity;
case 2: return Single.NegativeInfinity;
case 3: return Single.MinValue;
case 4: return Single.MaxValue;
case 5: return Single.Epsilon;
default:
result = (float)(rndGen.NextDouble() * 100000);
if (negative)
{
result = -result;
}
return result;
}
}
/// <summary>
/// Creates an instance of the <see cref="String"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <param name="size">The size of the string to be creted.</param>
/// <param name="charsToUse">The characters to use when creating the string.</param>
/// <returns>An instance of the <see cref="String"/> type.</returns>
public static string CreateRandomString(Random rndGen, int size, string charsToUse)
{
int maxSize = CreatorSettings.MaxStringLength;
// invalid per the XML spec (http://www.w3.org/TR/REC-xml/#charsets), cannot be sent as XML
string invalidXmlChars = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u000B\u000C\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\uFFFE\uFFFF";
const int LowSurrogateMin = 0xDC00;
const int LowSurrogateMax = 0xDFFF;
const int HighSurrogateMin = 0xD800;
const int HighSurrogateMax = 0xDBFF;
if (size < 0)
{
double rndNumber = rndGen.NextDouble();
if (rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
size = (int)Math.Pow(maxSize, rndNumber); // this will create more small strings than large ones
size--;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++)
{
char c;
if (charsToUse != null)
{
c = charsToUse[rndGen.Next(charsToUse.Length)];
sb.Append(c);
}
else
{
if (CreatorSettings.CreateOnlyAsciiChars || rndGen.Next(2) == 0)
{
c = (char)rndGen.Next(0x20, 0x7F); // low-ascii chars
sb.Append(c);
}
else
{
do
{
c = (char)rndGen.Next((int)Char.MinValue, (int)Char.MaxValue + 1);
}
while ((LowSurrogateMin <= c && c <= LowSurrogateMax) || (invalidXmlChars.IndexOf(c) >= 0));
sb.Append(c);
if (HighSurrogateMin <= c && c <= HighSurrogateMax)
{
// need to add a low surrogate
c = (char)rndGen.Next(LowSurrogateMin, LowSurrogateMax + 1);
sb.Append(c);
}
}
}
}
return sb.ToString();
}
/// <summary>
/// Creates an instance of the <see cref="String"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="String"/> type.</returns>
public static string CreateInstanceOfString(Random rndGen)
{
return CreateInstanceOfString(rndGen, true);
}
/// <summary>
/// Creates an instance of the <see cref="String"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <param name="allowNull">A flag indicating whether null values can be returned.</param>
/// <returns>An instance of the <see cref="String"/> type.</returns>
public static string CreateInstanceOfString(Random rndGen, bool allowNull)
{
string result;
do
{
result = CreateRandomString(rndGen, -1, null);
}
while (result == null && !allowNull);
return result;
}
/// <summary>
/// Creates an instance of the <see cref="String"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <param name="size">The size of the string to be creted.</param>
/// <param name="charsToUse">The characters to use when creating the string.</param>
/// <returns>An instance of the <see cref="String"/> type.</returns>
public static string CreateInstanceOfString(Random rndGen, int size, string charsToUse)
{
return CreateRandomString(rndGen, size, charsToUse);
}
/// <summary>
/// Creates an instance of the <see cref="UInt16"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt16"/> type.</returns>
[CLSCompliant(false)]
public static ushort CreateInstanceOfUInt16(Random rndGen)
{
byte[] rndValue = new byte[2];
rndGen.NextBytes(rndValue);
ushort result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (ushort)(result << 8);
result = (ushort)(result | (ushort)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="UInt32"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt32"/> type.</returns>
[CLSCompliant(false)]
public static uint CreateInstanceOfUInt32(Random rndGen)
{
byte[] rndValue = new byte[4];
rndGen.NextBytes(rndValue);
uint result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (uint)(result << 8);
result = (uint)(result | (uint)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="UInt64"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt64"/> type.</returns>
[CLSCompliant(false)]
public static ulong CreateInstanceOfUInt64(Random rndGen)
{
byte[] rndValue = new byte[8];
rndGen.NextBytes(rndValue);
ulong result = 0;
for (int i = 0; i < rndValue.Length; i++)
{
result = (ulong)(result << 8);
result = (ulong)(result | (ulong)rndValue[i]);
}
return result;
}
/// <summary>
/// Creates an instance of the <see cref="Uri"/> type.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Uri"/> type.</returns>
public static System.Uri CreateInstanceOfUri(Random rndGen)
{
Uri result;
UriKind kind;
try
{
string uriString;
do
{
uriString = UriCreator.CreateUri(rndGen, out kind);
}
while (IsRelativeIPv6Uri(uriString, kind));
result = new Uri(uriString, kind);
}
catch (ArgumentException)
{
result = new Uri("my.schema://userName:password@my.domain/path1/path2?query1=123&query2=%22hello%22");
}
return result;
}
/// <summary>
/// Creates an instance of the a string which represents an <see cref="Uri"/>.
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the a string which represents an <see cref="Uri"/>.</returns>
public static string CreateInstanceOfUriString(Random rndGen)
{
UriKind kind;
return UriCreator.CreateUri(rndGen, out kind);
}
/// <summary>
/// Checks whether this creator can create an instance of the given type.
/// </summary>
/// <param name="type">The type to be created.</param>
/// <returns><code>true</code> if this creator can create an instance of the given type; <code>false</code> otherwise.</returns>
public static bool CanCreateInstanceOf(Type type)
{
return creators.ContainsKey(type);
}
/// <summary>
/// Creates an instance of the given primitive type.
/// </summary>
/// <param name="type">The type to create an instance.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given type.</returns>
public static object CreatePrimitiveInstance(Type type, Random rndGen)
{
if (creators.ContainsKey(type))
{
return creators[type].Invoke(null, new object[] { rndGen });
}
else
{
throw new ArgumentException("Type " + type.FullName + " not supported");
}
}
private static bool IsRelativeIPv6Uri(string uriString, UriKind kind)
{
return kind == UriKind.Relative && RelativeIPv6UriRegex.Match(uriString).Success;
}
/// <summary>
/// Creates URI instances based on RFC 2396
/// </summary>
internal static class UriCreator
{
static readonly string digit;
static readonly string upalpha;
static readonly string lowalpha;
static readonly string alpha;
static readonly string alphanum;
static readonly string hex;
static readonly string mark;
static readonly string unreserved;
static readonly string reserved;
static UriCreator()
{
digit = "0123456789";
upalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
lowalpha = upalpha.ToLower();
alpha = upalpha + lowalpha;
alphanum = alpha + digit;
hex = digit + "ABCDEFabcdef";
mark = "-_.!~*'()";
unreserved = alphanum + mark;
reserved = ";/?:@&=+$,";
}
internal static string CreateUri(Random rndGen, out UriKind kind)
{
StringBuilder sb = new StringBuilder();
kind = UriKind.Relative;
if (rndGen.Next(3) > 0)
{
// Add URI scheme
CreateScheme(sb, rndGen);
kind = UriKind.Absolute;
}
if (rndGen.Next(3) > 0)
{
// Add URI host
sb.Append("//");
if (rndGen.Next(10) == 0)
{
CreateUserInfo(sb, rndGen);
}
CreateHost(sb, rndGen);
if (rndGen.Next(2) > 0)
{
sb.Append(':');
sb.Append(rndGen.Next(65536));
}
}
if (rndGen.Next(4) > 0)
{
// Add URI path
for (int i = 0; i < rndGen.Next(1, 4); i++)
{
sb.Append('/');
AddPathSegment(sb, rndGen);
}
}
if (rndGen.Next(3) == 0)
{
// Add URI query string
sb.Append('?');
AddUriC(sb, rndGen);
}
return sb.ToString();
}
private static void CreateScheme(StringBuilder sb, Random rndGen)
{
int size = rndGen.Next(1, 10);
AddChars(sb, rndGen, alpha, 1);
string schemeChars = alpha + digit + "+-.";
AddChars(sb, rndGen, schemeChars, size);
sb.Append(':');
}
private static void CreateIPv4Address(StringBuilder sb, Random rndGen)
{
for (int i = 0; i < 4; i++)
{
if (i > 0)
{
sb.Append('.');
}
sb.Append(rndGen.Next(1000));
}
}
private static void AddIPv6AddressPart(StringBuilder sb, Random rndGen)
{
int size = rndGen.Next(1, 10);
if (size > 4)
{
size = 4;
}
AddChars(sb, rndGen, hex, size);
}
private static void CreateIPv6Address(StringBuilder sb, Random rndGen)
{
sb.Append('[');
int temp = rndGen.Next(6);
int i;
switch (temp)
{
case 0:
sb.Append("::");
break;
case 1:
sb.Append("::1");
break;
case 2:
sb.Append("FF01::101");
break;
case 3:
sb.Append("::1");
break;
case 4:
for (i = 0; i < 3; i++)
{
AddIPv6AddressPart(sb, rndGen);
sb.Append(':');
}
for (i = 0; i < 3; i++)
{
sb.Append(':');
AddIPv6AddressPart(sb, rndGen);
}
break;
default:
for (i = 0; i < 8; i++)
{
if (i > 0)
{
sb.Append(':');
}
AddIPv6AddressPart(sb, rndGen);
}
break;
}
sb.Append(']');
}
private static void AddChars(StringBuilder sb, Random rndGen, string validChars, int size)
{
for (int i = 0; i < size; i++)
{
sb.Append(validChars[rndGen.Next(validChars.Length)]);
}
}
private static void CreateHostName(StringBuilder sb, Random rndGen)
{
int domainLabelCount = rndGen.Next(4);
int size;
for (int i = 0; i < domainLabelCount; i++)
{
AddChars(sb, rndGen, alphanum, 1);
size = rndGen.Next(10) - 1;
if (size > 0)
{
AddChars(sb, rndGen, alphanum + "-", size);
AddChars(sb, rndGen, alphanum, 1);
}
sb.Append('.');
}
AddChars(sb, rndGen, alpha, 1);
size = rndGen.Next(10) - 1;
if (size > 0)
{
AddChars(sb, rndGen, alphanum + "-", size);
AddChars(sb, rndGen, alphanum, 1);
}
}
private static void CreateHost(StringBuilder sb, Random rndGen)
{
int temp = rndGen.Next(3);
switch (temp)
{
case 0:
CreateIPv4Address(sb, rndGen);
break;
case 1:
CreateIPv6Address(sb, rndGen);
break;
case 2:
CreateHostName(sb, rndGen);
break;
}
}
private static void CreateUserInfo(StringBuilder sb, Random rndGen)
{
AddChars(sb, rndGen, alpha, rndGen.Next(1, 10));
if (rndGen.Next(3) > 0)
{
sb.Append(':');
AddChars(sb, rndGen, alpha, rndGen.Next(1, 10));
}
sb.Append('@');
}
private static void AddEscapedChar(StringBuilder sb, Random rndGen)
{
sb.Append('%');
AddChars(sb, rndGen, hex, 2);
}
private static void AddPathSegment(StringBuilder sb, Random rndGen)
{
string pchar = unreserved + ":@&=+$,";
int size = rndGen.Next(1, 10);
for (int i = 0; i < size; i++)
{
if (rndGen.Next(pchar.Length + 1) > 0)
{
AddChars(sb, rndGen, pchar, 1);
}
else
{
AddEscapedChar(sb, rndGen);
}
}
}
private static void AddUriC(StringBuilder sb, Random rndGen)
{
int size = rndGen.Next(20);
string reservedPlusUnreserved = reserved + unreserved;
for (int i = 0; i < size; i++)
{
if (rndGen.Next(5) > 0)
{
AddChars(sb, rndGen, reservedPlusUnreserved, 1);
}
else
{
AddEscapedChar(sb, rndGen);
}
}
}
}
}
/// <summary>
/// Utility class used to create test instances of arbitrary types.
/// </summary>
public static class InstanceCreator
{
private static Stack<Type> typesInCreationStack = new Stack<Type>();
/// <summary>
/// Creates an instance of an array type.
/// </summary>
/// <param name="arrayType">The array type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given array type.</returns>
public static object CreateInstanceOfArray(Type arrayType, Random rndGen)
{
Type type = arrayType.GetElementType();
double rndNumber = rndGen.NextDouble();
if (rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
int size = (int)Math.Pow(CreatorSettings.MaxArrayLength, rndNumber); // this will create more small arrays than large ones
size--;
Array result = Array.CreateInstance(type, size);
for (int i = 0; i < size; i++)
{
result.SetValue(CreateInstanceOf(type, rndGen), i);
}
return result;
}
/// <summary>
/// Creates an instance of a <see cref="List{T}"/>.
/// </summary>
/// <param name="listType">The List<T> type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given list type.</returns>
public static object CreateInstanceOfListOfT(Type listType, Random rndGen)
{
Type type = listType.GetGenericArguments()[0];
double rndNumber = rndGen.NextDouble();
if (rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
int size = (int)Math.Pow(CreatorSettings.MaxListLength, rndNumber); // this will create more small lists than large ones
size--;
object result = Activator.CreateInstance(listType);
MethodInfo addMethod = listType.GetMethod("Add");
for (int i = 0; i < size; i++)
{
addMethod.Invoke(result, new object[] { CreateInstanceOf(type, rndGen) });
}
return result;
}
/// <summary>
/// Creates an instance of a <see cref="LinkedList{T}"/>.
/// </summary>
/// <param name="listType">The LinkedList<T> type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given list type.</returns>
public static object CreateInstanceOfLinkedListOfT(Type listType, Random rndGen)
{
Type type = listType.GetGenericArguments()[0];
double rndNumber = rndGen.NextDouble();
if (rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
int size = (int)Math.Pow(CreatorSettings.MaxListLength, rndNumber); // this will create more small lists than large ones
size--;
object result = Activator.CreateInstance(listType);
MethodInfo addMethod = listType.GetMethod("AddLast", new Type[] { type });
for (int i = 0; i < size; i++)
{
addMethod.Invoke(result, new object[] { CreateInstanceOf(type, rndGen) });
}
return result;
}
/// <summary>
/// Creates an instance of a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="enumerableOfTType">The IEnumerable<T> type.</param>
/// <param name="enumeredType">The type to be enumerated.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given enumerable type.</returns>
public static object CreateInstanceOfIEnumerableOfT(Type enumerableOfTType, Type enumeredType, Random rndGen)
{
double rndNumber = rndGen.NextDouble();
if (!enumerableOfTType.IsValueType && rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
int size = (int)Math.Pow(CreatorSettings.MaxListLength, rndNumber); // this will create more small lists than large ones
size--;
object result = Activator.CreateInstance(enumerableOfTType);
MethodInfo addMethod = enumerableOfTType.GetMethod("Add", new Type[] { enumeredType });
if (addMethod == null)
{
throw new ArgumentException("Cannot create an instance of an IEnumerable<T> type which does not have a public Add method");
}
for (int i = 0; i < size; i++)
{
addMethod.Invoke(result, new object[] { CreateInstanceOf(enumeredType, rndGen) });
}
return result;
}
/// <summary>
/// Creates an instance of a <see cref="Nullable{T}"/>.
/// </summary>
/// <param name="nullableOfTType">The Nullable<T> type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given nullable type.</returns>
public static object CreateInstanceOfNullableOfT(Type nullableOfTType, Random rndGen)
{
if (rndGen.Next(5) == 0)
{
return null;
}
Type type = nullableOfTType.GetGenericArguments()[0];
return CreateInstanceOf(type, rndGen);
}
/// <summary>
/// Creates an instance of an enum type..
/// </summary>
/// <param name="enumType">The enum type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given enum type.</returns>
public static object CreateInstanceOfEnum(Type enumType, Random rndGen)
{
bool hasFlags = enumType.GetCustomAttributes(typeof(FlagsAttribute), true).Length > 0;
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length == 0)
{
return 0;
}
if (!hasFlags)
{
return possibleValues.GetValue(rndGen.Next(possibleValues.Length));
}
else
{
Type underlyingType = Enum.GetUnderlyingType(enumType);
string strResult;
if (underlyingType.FullName == typeof(ulong).FullName)
{
ulong result = 0;
if (rndGen.Next(10) > 0)
{
// 10% chance of value zero
foreach (object value in possibleValues)
{
if (rndGen.Next(2) == 0)
{
result |= ((IConvertible)value).ToUInt64(null);
}
}
}
strResult = result.ToString();
}
else
{
long result = 0;
if (rndGen.Next(10) > 0)
{
// 10% chance of value zero
foreach (object value in possibleValues)
{
if (rndGen.Next(2) == 0)
{
result |= ((IConvertible)value).ToInt64(null);
}
}
}
strResult = result.ToString();
}
return Enum.Parse(enumType, strResult, true);
}
}
/// <summary>
/// Creates an instance of a <see cref="Dictionary{K,V}"/>.
/// </summary>
/// <param name="dictionaryType">The Dictionary<K,V> type.</param>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the given dictionary type.</returns>
public static object CreateInstanceOfDictionaryOfKAndV(Type dictionaryType, Random rndGen)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
double rndNumber = rndGen.NextDouble();
if (rndNumber < CreatorSettings.NullValueProbability)
{
return null; // 1% chance of null value
}
int size = (int)Math.Pow(CreatorSettings.MaxListLength, rndNumber); // this will create more small dictionaries than large ones
size--;
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add");
MethodInfo containsKeyMethod = dictionaryType.GetMethod("ContainsKey");
for (int i = 0; i < size; i++)
{
object newKey;
do
{
newKey = CreateInstanceOf(typeK, rndGen);
}
while (newKey == null);
bool containsKey = (bool)containsKeyMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = CreateInstanceOf(typeV, rndGen);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
/// <summary>
/// Creates an instance of the given type.
/// </summary>
/// <typeparam name="T">The type to create an instance from.</typeparam>
/// <param name="rndGen">A random generator used to populate the instance.</param>
/// <returns>An instance of the given type.</returns>
public static T CreateInstanceOf<T>(Random rndGen)
{
return (T)InstanceCreator.CreateInstanceOf(typeof(T), rndGen);
}
/// <summary>
/// Creates an instance of the given type.
/// </summary>
/// <param name="type">The type to create an instance from.</param>
/// <param name="rndGen">A random generator used to populate the instance.</param>
/// <param name="allowNulls">A flag indicating whether null values can be returned by this method.</param>
/// <returns>An instance of the given type.</returns>
public static object CreateInstanceOf(Type type, Random rndGen, bool allowNulls)
{
double currentNullProbability = CreatorSettings.NullValueProbability;
if (!allowNulls)
{
CreatorSettings.NullValueProbability = 0;
}
object result = CreateInstanceOf(type, rndGen);
if (!allowNulls)
{
CreatorSettings.NullValueProbability = currentNullProbability;
}
return result;
}
/// <summary>
/// Creates an instance of the given type.
/// </summary>
/// <param name="type">The type to create an instance from.</param>
/// <param name="rndGen">A random generator used to populate the instance.</param>
/// <returns>An instance of the given type.</returns>
public static object CreateInstanceOf(Type type, Random rndGen)
{
if (CreatorSettings.CreatorSurrogate != null)
{
if (CreatorSettings.CreatorSurrogate.CanCreateInstanceOf(type))
{
return CreatorSettings.CreatorSurrogate.CreateInstanceOf(type, rndGen);
}
}
ConstructorInfo randomConstructor = type.GetConstructor(new Type[] { typeof(Random) });
if (randomConstructor != null)
{
// it's possible that a class with a Type.GetConstructor will return a constructor
// which takes a System.Object; we only want to use if it really takes a Random argument.
ParameterInfo[] ctorParameters = randomConstructor.GetParameters();
if (ctorParameters.Length == 1 && ctorParameters[0].ParameterType == typeof(Random))
{
return randomConstructor.Invoke(new object[] { rndGen });
}
}
// Allow for a static factory method (called 'CreateInstance' to allow for inheritance scenarios
MethodInfo randomFactoryMethod = type.GetMethod("CreateInstance", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Random) }, null);
if (randomFactoryMethod != null)
{
ParameterInfo[] methodParameters = randomFactoryMethod.GetParameters();
if (methodParameters.Length == 1 && methodParameters[0].ParameterType == typeof(Random))
{
return randomFactoryMethod.Invoke(null, new object[] { rndGen });
}
}
object result = null;
Type genericElementType = null;
if (CreatorSettings.AvoidStackOverflowDueToTypeCycles)
{
if (typesInCreationStack.Contains(type))
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
else
{
return null;
}
}
typesInCreationStack.Push(type);
}
if (PrimitiveCreator.CanCreateInstanceOf(type))
{
result = PrimitiveCreator.CreatePrimitiveInstance(type, rndGen);
}
else if (type.IsEnum)
{
result = CreateInstanceOfEnum(type, rndGen);
}
else if (type.IsArray)
{
result = CreateInstanceOfArray(type, rndGen);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
result = CreateInstanceOfNullableOfT(type, rndGen);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
result = CreateInstanceOfListOfT(type, rndGen);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(LinkedList<>))
{
result = CreateInstanceOfLinkedListOfT(type, rndGen);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
result = CreateInstanceOfDictionaryOfKAndV(type, rndGen);
}
else if (ContainsAttribute(type, typeof(DataContractAttribute)))
{
result = ClassInstanceCreator.DataContractCreator.CreateInstanceOf(type, rndGen);
}
else if (IsIEnumerableOfT(type, out genericElementType))
{
result = CreateInstanceOfIEnumerableOfT(type, genericElementType, rndGen);
}
else if (type.IsPublic || type.IsNestedPublic)
{
result = ClassInstanceCreator.POCOCreator.CreateInstanceOf(type, rndGen);
}
else
{
result = Activator.CreateInstance(type);
}
if (CreatorSettings.AvoidStackOverflowDueToTypeCycles)
{
typesInCreationStack.Pop();
}
return result;
}
internal static bool ContainsAttribute(MemberInfo member, Type attributeType)
{
object[] attributes = member.GetCustomAttributes(attributeType, false);
return attributes != null && attributes.Length > 0;
}
static bool IsIEnumerableOfT(Type type, out Type genericArgumentType)
{
genericArgumentType = null;
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
genericArgumentType = interfaceType.GetGenericArguments()[0];
return true;
}
}
return false;
}
}
/// <summary>
/// Helper class used to create test instances.
/// </summary>
public class ClassInstanceCreator
{
static ClassInstanceCreator dataContractCreatorWithNonPublicMembers;
static ClassInstanceCreator dataContractCreator;
static ClassInstanceCreator pocoCreator;
bool includeNonPublicMembers;
GetMemberNameDelegate getMemberNameDelegate;
ShouldBeIncludedDelegate shouldBeIncludedDelegate;
private ClassInstanceCreator(GetMemberNameDelegate getMemberNameDelegate, ShouldBeIncludedDelegate shouldBeIncludedDelegate, bool includeNonPublicMembers)
: this(getMemberNameDelegate, shouldBeIncludedDelegate)
{
this.includeNonPublicMembers = includeNonPublicMembers;
}
private ClassInstanceCreator(GetMemberNameDelegate getMemberNameDelegate, ShouldBeIncludedDelegate shouldBeIncludedDelegate)
{
this.getMemberNameDelegate = getMemberNameDelegate;
this.shouldBeIncludedDelegate = shouldBeIncludedDelegate;
}
delegate string GetMemberNameDelegate(MemberInfo member);
delegate bool ShouldBeIncludedDelegate(MemberInfo member);
/// <summary>
/// Gets an instance of a creator which knows how to create instance of types
/// decorated with the <see cref="DataContractAttribute"/>.
/// </summary>
public static ClassInstanceCreator DataContractCreator
{
get
{
if (dataContractCreator == null)
{
dataContractCreator = new ClassInstanceCreator(GetDataMemberName, IncludeDataMembersOnly);
}
return dataContractCreator;
}
}
/// <summary>
/// Gets an instance of a creator which knows how to create instance of types
/// which only sets members decorated with the <see cref="DataMemberAttribute"/>.
/// </summary>
public static ClassInstanceCreator DataContractCreatorWithNonPublicMembers
{
get
{
if (dataContractCreatorWithNonPublicMembers == null)
{
dataContractCreatorWithNonPublicMembers = new ClassInstanceCreator(GetDataMemberName, IncludeDataMembersOnly, true);
}
return dataContractCreatorWithNonPublicMembers;
}
}
/// <summary>
/// Gets an instance of a creator which knows how to create instances of POCO
/// types (public types, not decorated with the <see cref="DataContractAttribute"/> and
/// which have a parameterless public constructor).
/// </summary>
public static ClassInstanceCreator POCOCreator
{
get
{
if (pocoCreator == null)
{
pocoCreator = new ClassInstanceCreator(
delegate(MemberInfo member) { return member.Name; },
DoNotIncludeExcludedMembers);
}
return pocoCreator;
}
}
/// <summary>
/// Creates an instance of the given type.
/// </summary>
/// <param name="type">The type to create an instance from.</param>
/// <param name="rndGen">A random generator used to populate the instance.</param>
/// <returns>An instance of the given type.</returns>
public object CreateInstanceOf(Type type, Random rndGen)
{
object result = null;
if (rndGen.NextDouble() < CreatorSettings.NullValueProbability && !type.IsValueType)
{
// 1% chance of null object, if it is not a struct
return null;
}
ConstructorInfo randomConstructor = type.GetConstructor(new Type[] { typeof(Random) });
if (randomConstructor != null && randomConstructor.GetParameters()[0].ParameterType == typeof(Random))
{
result = randomConstructor.Invoke(new object[] { rndGen });
}
else
{
ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]);
if (defaultConstructor != null || type.IsValueType)
{
result = Activator.CreateInstance(type);
this.SetFieldsAndProperties(type, result, rndGen);
}
else
{
throw new ArgumentException("Don't know how to create an instance of " + type.FullName);
}
}
return result;
}
private static string GetDataMemberName(MemberInfo member)
{
DataMemberAttribute[] dataMemberAttr = (DataMemberAttribute[])member.GetCustomAttributes(typeof(DataMemberAttribute), false);
if (dataMemberAttr == null || dataMemberAttr.Length == 0 || dataMemberAttr[0].Name == null)
{
return member.Name;
}
else
{
return dataMemberAttr[0].Name;
}
}
private static bool ContainsAttribute(MemberInfo member, string attributeName)
{
object[] customAttributes = member.GetCustomAttributes(false);
foreach (object attribute in customAttributes)
{
if (attribute != null && attribute.GetType().Name == attributeName)
{
return true;
}
}
return false;
}
private static bool IncludeDataMembersOnly(MemberInfo member)
{
return ContainsAttribute(member, "DataMemberAttribute");
}
private static bool DoNotIncludeExcludedMembers(MemberInfo member)
{
return !ContainsAttribute(member, "IgnoreDataMemberAttribute");
}
int CompareDataMembers(MemberInfo member1, MemberInfo member2)
{
return this.getMemberNameDelegate(member1).CompareTo(this.getMemberNameDelegate(member2));
}
private void SetFieldsAndProperties(Type type, object obj, Random rndGen)
{
List<MemberInfo> members = new List<MemberInfo>();
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (this.includeNonPublicMembers)
{
bindingFlags |= BindingFlags.NonPublic;
}
FieldInfo[] fields = type.GetFields(bindingFlags);
PropertyInfo[] properties = type.GetProperties(bindingFlags);
foreach (FieldInfo field in fields)
{
if (this.shouldBeIncludedDelegate(field))
{
members.Add(field);
}
}
foreach (PropertyInfo prop in properties)
{
if (this.shouldBeIncludedDelegate(prop))
{
members.Add(prop);
}
}
members.Sort(new Comparison<MemberInfo>(this.CompareDataMembers));
foreach (MemberInfo member in members)
{
if (member is FieldInfo)
{
object fieldValue = InstanceCreator.CreateInstanceOf(((FieldInfo)member).FieldType, rndGen);
((FieldInfo)member).SetValue(obj, fieldValue);
}
else
{
PropertyInfo propInfo = (PropertyInfo)member;
if (propInfo.CanWrite)
{
object propertyValue = InstanceCreator.CreateInstanceOf(propInfo.PropertyType, rndGen);
propInfo.SetValue(obj, propertyValue, null);
}
else
{
if (!this.TrySettingMembersOfGetOnlyCollection(rndGen, propInfo, obj))
{
throw new ArgumentException("Cannot set property " + propInfo.Name + " of type " + type.FullName);
}
}
}
}
}
private bool TrySettingMembersOfGetOnlyCollection(Random rndGen, PropertyInfo propInfo, object obj)
{
Type propType = propInfo.PropertyType;
object propValue = propInfo.GetValue(obj, null);
if (propValue == null)
{
// need something to set the value to
return false;
}
if (propType.IsArray)
{
Array propArray = (Array)propValue;
Type arrayType = propType.GetElementType();
for (int i = 0; i < propArray.Length; i++)
{
object elementValue = InstanceCreator.CreateInstanceOf(arrayType, rndGen);
propArray.SetValue(elementValue, i);
}
return true;
}
else if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(List<>))
{
Type listType = propType.GetGenericArguments()[0];
MethodInfo addMethod = propType.GetMethod("Add", new Type[] { listType });
double rndNumber = rndGen.NextDouble();
int size = (int)Math.Pow(CreatorSettings.MaxListLength, rndNumber); // this will create more small lists than large ones
size--;
for (int i = 0; i < size; i++)
{
object listValue = InstanceCreator.CreateInstanceOf(listType, rndGen);
addMethod.Invoke(propValue, new object[] { listValue });
}
return true;
}
return false;
}
}
/// <summary>
/// Enables tests to create specific instances of certain types.
/// </summary>
public abstract class InstanceCreatorSurrogate
{
/// <summary>
/// Checks whether this surrogate can create instances of a given type.
/// </summary>
/// <param name="type">The type which needs to be created.</param>
/// <returns>A true value if this surrogate can create the given type; a
/// false value otherwise.</returns>
public abstract bool CanCreateInstanceOf(Type type);
/// <summary>
/// Creates an instance of the given type.
/// </summary>
/// <param name="type">The type to create an instance for.</param>
/// <param name="rndGen">A Random generator to assist in creating the instance.</param>
/// <returns>An instance of the given type.</returns>
public abstract object CreateInstanceOf(Type type, Random rndGen);
}
}
|