public void WriteToFile_WhenPathIsNotNullOrWhiteSpace_WriteTextFile()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                FakesForSpSecurity();
                FakesForConstructor();
                SetupParameters();

                var guid    = Guid.NewGuid();
                var epmData = new EPMData(guid);
                _privateObject = new PrivateObject(epmData);

                var testResult = string.Empty;
                ShimEPMData.AllInstances.WriteToFileString = (path, text) => { testResult = text; };

                // Act
                epmData.WriteToFile(DummyCommand);

                // Assert
                Assert.AreEqual(testResult, DummyCommand);
            }
        }
 public void TestCacheAddFeature()
 {
     using (ShimsContext.Create())
     {
         client.Geometry.MapPoint           p          = new client.Geometry.MapPoint(0.0, 0.0);
         clientfake.ShimGraphic             g          = new clientfake.ShimGraphic();
         clientfake.ShimUniqueValueRenderer r          = new clientfake.ShimUniqueValueRenderer();
         Dictionary <String, Object>        attributes = new Dictionary <String, Object>();
         attributes["uniquedesignation"] = "1-1";
         attributes["higherformation"]   = "1";
         g.AttributesGet = () => { return(attributes); };
         g.GeometryGet   = () => { return(p); };
         Dictionary <String, String> fields = new Dictionary <String, String>();
         fields["UID"]       = "uniquedesignation";
         fields["HF"]        = "higherformation";
         fields["LABELS"]    = "uniquedesignation";
         fields["DESCFLDS"]  = null;
         fields["DESCFIELD"] = null;
         int count = cache.RetrieveFeatureCache("UNITS").Count;
         cache.AddFeature("UNITS", g, "", "{uniquedesignation}", fields, r);
         Assert.IsTrue(cache.RetrieveFeatureCache("UNITS").Count > count);
     }
 }
        public void Calc_IsWeekend()
        {
            var calc = new Calc();

            using (ShimsContext.Create())
            {
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 13);
                Assert.IsFalse(calc.IsWeekend()); //Mo
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 14);
                Assert.IsFalse(calc.IsWeekend()); //Di
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 15);
                Assert.IsFalse(calc.IsWeekend()); //Mi
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 16);
                Assert.IsFalse(calc.IsWeekend()); //Do
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 17);
                Assert.IsFalse(calc.IsWeekend()); //Fr
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 18);
                Assert.IsTrue(calc.IsWeekend());  //Sa
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 19);
                Assert.IsTrue(calc.IsWeekend());  //So
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 5, 20);
            }
        }
        public void IsValidFileName_ShouldSetLastInvalidFileNameDate_WhenNameIsIncorrect()
        {
            using (ShimsContext.Create())
            {
                //Arrange
                var expectedDate = new DateTime(2000, 1, 1);
                System.Fakes.ShimDateTime.UtcNowGet = () => expectedDate;

                Mock <IExtensionManager> extensionManager = new Mock <IExtensionManager>();
                extensionManager
                .Setup(e => e.IsValid(It.IsAny <string>()))
                .Returns(false);

                Mock <ILogger> logger      = new Mock <ILogger>();
                var            logAnalyzer = new LogAnalyzer(extensionManager.Object, logger.Object);

                //Act
                var result = logAnalyzer.IsValidFileName("Invalid_LGO.xlsx");

                //Assert
                Assert.AreEqual(expectedDate, logAnalyzer.LastInvalidFileNameDate);
            }
        }
Example #5
0
 public void TestGetPermissableEntities_EntitiesNotPermissable()
 {
     using (ShimsContext.Create())
     {
         var entity = new StandardEntity
         {
             S = "string"
         };
         System.Data.Entity.Infrastructure.Fakes.ShimDbChangeTracker.AllInstances.Entries = (tracker) =>
         {
             var entries = new List <DbEntityEntry>();
             entries.Add(new System.Data.Entity.Infrastructure.Fakes.ShimDbEntityEntry
             {
                 EntityGet = () => entity,
                 StateGet  = () => EntityState.Added
             });
             return(entries);
         };
         context.StandardEntities.Add(entity);
         var entities = saveAction.GetPermissableEntities(context, EntityState.Added);
         Assert.AreEqual(0, entities.Count);
     }
 }
Example #6
0
        public void MWQMPlanSubsectorSiteService_PostAddMWQMPlanSubsectorSiteDB_Add_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        //string ErrorText = "ErrorText";
                        shimMWQMPlanSubsectorSiteService.FillMWQMPlanSubsectorSiteMWQMPlanSubsectorSiteMWQMPlanSubsectorSiteModelContactOK = (a, b, c) =>
                        {
                            return("");
                        };

                        MWQMPlanSubsectorSiteModel labContractSubsectorSiteModelRet = AddMWQMPlanSubsectorSiteModel();
                        Assert.IsTrue(labContractSubsectorSiteModelRet.Error.StartsWith(string.Format(ServiceRes.CouldNotAddError_, "").Substring(0, 10)));
                    }
                }
            }
        }
        private async Task GetJsonAsyncUriTestAsync()
        {
            using (ShimsContext.Create())
            {
                ShimHttpClient.AllInstances.GetAsyncUriHttpCompletionOptionCancellationToken = (httpClient, uri, arg3, arg4) =>
                {
                    return(Task.FromResult(new HttpResponseMessage()
                    {
                        Content = new StringContent(JsonConvert.SerializeObject(_person)),
                        StatusCode = HttpStatusCode.OK
                    }));
                };

                using (var client = new UncommonHttpClient())
                {
                    var result = await client.GetJsonAsync <Person>(new Uri("http://www.xciles.com/"));

                    Assert.AreEqual(_person.Firstname, result.Firstname);
                    Assert.AreEqual(_person.Lastname, result.Lastname);
                    Assert.AreEqual(_person.PhoneNumber, result.PhoneNumber);
                }
            }
        }
Example #8
0
        public void GenerateAndAddRule_ReceivesAllParameters_AddsRule()
        {
            ResultsFileSarifMapper.RuleList.Clear();
            RuleResult ruleResult = GenerateRuleResult();

            using (ShimsContext.Create())
            {
                ShimResultsFileSarifMapper.FetchOrAddStandardsRuleResult = (_) =>
                {
                    return(new string[] { Standard });
                };
                Rule returnedRule = ResultsFileSarifMapper.GenerateAndAddRule(ruleResult);
                Assert.IsNotNull(returnedRule);
                Assert.IsTrue(ResultsFileSarifMapper.RuleList.ContainsKey(ruleResult.Rule.ToString()));
                Assert.AreEqual(ruleResult.Rule.ToString(), returnedRule.Id);
                Assert.AreEqual(ruleResult.Description, returnedRule.Name.Text);
                Assert.AreEqual(ruleResult.Description, returnedRule.FullDescription.Text);
                Assert.AreEqual(ruleResult.HelpUrl.Url, returnedRule.HelpUri.ToString());
                string[] standards = null;
                Assert.IsTrue(returnedRule.TryGetProperty <string[]>(StandardsKey, out standards));
                Assert.AreEqual(Standard, standards[0]);
            }
        }
        public void TestPolicySucceeds_If_OneWorkItem_OfType_Associated()
        {
            var policy = new OneWorkItemPolicy()
            {
                Config = new OneWorkItemPolicyConfig()
                {
                    WorkItemType = "Task", ExactlyOne = true
                }
            };

            using (var context = ShimsContext.Create())
            {
                var list = new List <ShimWorkItem>()
                {
                    FakeUtils.CreateWorkItem("Task", "Bob")
                };
                var checkin = FakeUtils.CreatePendingCheckin(list);

                policy.Initialize(checkin);
                var failures = policy.Evaluate();
                Assert.AreEqual(0, failures.Length);
            }
        }
        public void TestPolicyFails_IfNoWorkItemsAssociated()
        {
            var policy = new OneWorkItemPolicy()
            {
                Config = new OneWorkItemPolicyConfig()
                {
                    WorkItemType = "Task", ExactlyOne = true
                }
            };

            using (var context = ShimsContext.Create())
            {
                var checkin = FakeUtils.CreatePendingCheckin(new List <ShimWorkItem>()
                {
                    null
                });

                policy.Initialize(checkin);
                var failures = policy.Evaluate();
                Assert.AreEqual(1, failures.Length);
                Assert.IsTrue(failures[0].Message.StartsWith("Changeset is required to be associated with exactly one work item of type 'Task' that has been assigned to you."));
            }
        }
        public void test_isStairPressureAirSystemIndependent_unPass()
        {
            using (ShimsContext.Create())
            {
                HVAC_CheckEngine.Fakes.ShimHVACFunction.GetRoomContainAirTerminalRoom = FakeHVACFunction.GetRoomContainAirTerminal_new;

                HVAC_CheckEngine.Fakes.ShimHVACFunction.GetFanConnectingAirterminalAirTerminal = FakeHVACFunction.GetFanConnectingAirterminal_new;

                HVAC_CheckEngine.Fakes.ShimHVACFunction.GetOutletsOfFanFan = FakeHVACFunction.GetOutputLetsOfFan_new;

                //arrange
                FakeHVACFunction.ExcelPath_new = @"D:\wangT\HVAC-Checker\UnitTestHVACChecker\测试数据\测试数据_GB51251_2017_3_1_5.xlsx";
                Room stairCase = new Room(2);
                //打开测试数据文件

                //act
                bool isIndependent = assistantFunctions.isStairPressureAirSystemIndependent(stairCase);

                //assert

                Assert.IsFalse(isIndependent);
            }
        }
Example #12
0
        public void SpillService_PostAddSpillDB_DoAddChanges_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        string ErrorText = "ErrorText";
                        shimSpillService.DoAddChanges = () =>
                        {
                            return(ErrorText);
                        };

                        SpillModel spillModelRet = AddSpillModel();
                        Assert.AreEqual(ErrorText, spillModelRet.Error);
                    }
                }
            }
        }
Example #13
0
        public void SpillService_PostAddSpillDB_GetSpillExistDB_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        //string ErrorText = "ErrorText";
                        shimSpillService.GetSpillExistDBSpillModel = (a) =>
                        {
                            return(new Spill());
                        };

                        SpillModel spillModelRet = AddSpillModel();
                        Assert.AreEqual(string.Format(ServiceRes._AlreadyExists, ServiceRes.Spill), spillModelRet.Error);
                    }
                }
            }
        }
        public void GettingContentsOfRunningEnvironmentVariableGroupTest()
        {
            using (ShimsContext.Create())
            {
                MockClients clients = new MockClients();

                string json = @"{
  ""abc"": 123,
  ""do-re-me"": ""far-so-la-tee""
}";
                clients.JsonResponse = json;

                clients.ExpectedStatusCode = (HttpStatusCode)200;
                var cfClient = clients.CreateCloudFoundryClient();


                var obj = cfClient.EnvironmentVariableGroups.GettingContentsOfRunningEnvironmentVariableGroup().Result;


                Assert.AreEqual("123", TestUtil.ToTestableString(obj.Abc), true);
                Assert.AreEqual("far-so-la-tee", TestUtil.ToTestableString(obj.Doreme), true);
            }
        }
Example #15
0
        public void MWQMPlanSubsectorSiteService_PostAddMWQMPlanSubsectorSiteDB_GetMWQMPlanSubsectorSiteExistDB_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        //string ErrorText = "ErrorText";
                        shimMWQMPlanSubsectorSiteService.GetMWQMPlanSubsectorSiteModelExistDBMWQMPlanSubsectorSiteModel = (a) =>
                        {
                            return(new MWQMPlanSubsectorSiteModel());
                        };

                        MWQMPlanSubsectorSiteModel labContractSubsectorSiteModelRet = AddMWQMPlanSubsectorSiteModel();
                        Assert.AreEqual(string.Format(ServiceRes._AlreadyExists, ServiceRes.MWQMPlanSubsectorSite), labContractSubsectorSiteModelRet.Error);
                    }
                }
            }
        }
        public void GetCurrentRenderingDatasource_NestingEnabled_NoDirectDatasourceOrStaticItem_WithAlwaysNesting_ReturnsNestedItem()
        {
            var props = new RenderingProperties(_rendering);

            using (ShimsContext.Create())
            {
                var fakeItem = CreateFakeItem(_nestedItemDatasource._Id);

                // Setup rendering params: no direct datasource, static item is set
                _rendering.DataSource.Returns(ci => null);
                _rendering.Properties.Returns(ci => props);
                props["ItemId"] = null;                          // simulates no StaticItem
                _renderingContext.ContextItem.Returns(fakeItem); // sets the nested datasource

                _sitecoreContext.GetItem <IGlassBase>(_nestedItemDatasource._Id, inferType: true)
                .Returns(_nestedItemDatasource);

                var datasource =
                    _renderingService.GetCurrentRenderingDatasource <IGlassBase>(DatasourceNestingOptions.Always);

                Assert.AreEqual(_nestedItemDatasource._Id, datasource._Id);
            }
        }
Example #17
0
        public void MWQMPlanSubsectorSiteService_PostAddMWQMPlanSubsectorSiteDB_DoAddChanges_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        string ErrorText = "ErrorText";
                        shimMWQMPlanSubsectorSiteService.DoAddChanges = () =>
                        {
                            return(ErrorText);
                        };

                        MWQMPlanSubsectorSiteModel labContractSubsectorSiteModelRet = AddMWQMPlanSubsectorSiteModel();
                        Assert.AreEqual(ErrorText, labContractSubsectorSiteModelRet.Error);
                    }
                }
            }
        }
        public void ShouldRouteToImagesGetProductImage()
        {
            // Arrange
            var config = new HttpConfiguration();

            using (var context = ShimsContext.Create())
            {
                ShimConfigurationManager.AppSettingsGet = () => new NameValueCollection {
                    { CorsHandler.CORSHandlerAllowerHostsSettings, "dummy" }
                };
                WebApiConfig.Register(config);
            }

            // Act
            var routeData = config.Routes.GetRouteData(new HttpRequestMessage(HttpMethod.Get, "http://foo/api/images/products/1"));

            // Assert
            Assert.IsNotNull(routeData);
            Assert.AreEqual("api/{controller}/{action}/{id}", routeData.Route.RouteTemplate);
            Assert.AreEqual("Images", (string)routeData.Values["controller"], true);
            Assert.AreEqual("Products", (string)routeData.Values["action"], true);
            Assert.AreEqual("1", (string)routeData.Values["id"], true);
        }
Example #19
0
        public void GetHashCode_DifferentComplexContributions_ReturnsSameHashCode()
        {
            using (ShimsContext.Create())
            {
                A11yElement element1 = new ShimA11yElement
                {
                    NameGet         = () => "ElementName",
                    CultureGet      = () => "ElementCulture",
                    AutomationIdGet = () => "ElementAutomationId",
                };
                A11yElement element2 = new ShimA11yElement
                {
                    NameGet         = () => " ElementName",
                    CultureGet      = () => "ElementCulture",
                    AutomationIdGet = () => "ElementAutomationId",
                };

                IFingerprint fingerprint1 = new ScanResultFingerprint(element1, DefaultRule, DefaultScanStatus);
                IFingerprint fingerprint2 = new ScanResultFingerprint(element2, DefaultRule, DefaultScanStatus);

                Assert.AreNotEqual(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());
            }
        }
        public void MWQMSiteStartEndDateService_PostAddMWQMSiteStartEndDateDB_FillMWQMSiteStartEndDateModel_ErrorTest()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        string ErrorText = "ErrorText";
                        shimMWQMSiteStartEndDateService.FillMWQMSiteStartEndDateMWQMSiteStartEndDateMWQMSiteStartEndDateModelContactOK = (a, b, c) =>
                        {
                            return(ErrorText);
                        };

                        MWQMSiteStartEndDateModel mwqmSiteStartEndDateModelRet = AddMWQMSiteStartEndDateModel();
                        Assert.AreEqual(ErrorText, mwqmSiteStartEndDateModelRet.Error);
                    }
                }
            }
        }
        public void GetSecret()
        {
            const string VaultName     = "fakevault1";
            const string SecretName    = "secretname1";
            const string SecretVersion = "1aaaaaaa1aa11a1111aaaa11111a1111";
            const string SecretValue   = "This is the value fake";
            const string TenantId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientId      = "11111111-1111-1111-aa1a-a1a11a111111";
            const string ClientSecret  = "a.u8w3FFgwy9v_-5R_5gsT~qf96T~a7e6y";

            var    getSecretInvoked = false;
            string key = null;

            using (var context = ShimsContext.Create())
            {
                var secret   = new KeyVaultSecretFake($"{VaultName}.vault.azure.net", SecretName, SecretVersion, SecretValue);
                var response = new FakeResponse <KeyVaultSecret>(secret, 200, "OK", null);

                SetupSecretClientConstructorFakes();
                ShimSecretClient.AllInstances.GetSecretAsyncStringStringCancellationToken = new FakesDelegates.Func <SecretClient, string, string, CancellationToken, Task <Response <KeyVaultSecret> > >((client, name, version, cancellationToken) =>
                {
                    getSecretInvoked = true;

                    var fakeResponse = response as Response <KeyVaultSecret>;
                    return(Task.FromResult(fakeResponse));
                });

                var vault       = new KeyVault(VaultName, AzureOauthTokenAuthentication.GetOauthTokenCredentialFromClientSecret(TenantId, ClientId, ClientSecret), 3, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(10));
                var client      = vault.GetSecretsClient(SecretClientOptions.ServiceVersion.V7_1);
                var secretValue = client.GetAsync(SecretName).GetAwaiter().GetResult();

                key = secretValue.Value.SecureStringToString();
            }

            Assert.IsTrue(getSecretInvoked, "The fake should be used");
            Assert.IsTrue(string.Equals(key, SecretValue, StringComparison.Ordinal), "Value not expected");
        }
        public void TestInitialize()
        {
            _shimContext   = ShimsContext.Create();
            _testEntity    = new sitepermissions();
            _privateObject = new PrivateObject(_testEntity);

            var gridView = new GridView();

            gridView.Columns.Add(new TemplateField()
            {
            });
            gridView.Columns.Add(new BoundField()
            {
                DataField = "name"
            });
            gridView.Columns.Add(new BoundField()
            {
                DataField = "email"
            });
            gridView.Columns.Add(new BoundField()
            {
                DataField = "group"
            });
            gridView.Columns.Add(new TemplateField()
            {
            });
            _privateObject.SetField(GridView1FieldName, gridView);
            _privateObject.SetField(LabelDescFieldName, new Label());
            _privateObject.SetField(LabelTitleFieldName, new Label());
            _privateObject.SetField(LabelNameFieldName, new Label());
            _privateObject.SetField(LabelUserNameFieldName, new Label());
            _privateObject.SetField(LabelEmailFieldName, new Label());
            _privateObject.SetField(PanelEditFieldName, new Panel());
            _privateObject.SetField(PanelFieldName, new Panel());
            _privateObject.SetField(PanelGroupdsFieldName, new Panel());
            _privateObject.SetField(PanelGroupdsFieldName, new Panel());
        }
Example #23
0
        public void CaptureScreenShot_ElementWithoutBoundingRectangle_NoScreenShot()
        {
            using (ShimsContext.Create())
            {
                bool bitmapsetcalled = false;

                // no bounding rectangle.
                A11yElement element = new ShimA11yElement
                {
                    ParentGet            = () => null,
                    BoundingRectangleGet = () => Rectangle.Empty,
                };

                ElementDataContext dc = new ShimElementDataContext()
                {
                    ScreenshotSetBitmap = (_) => bitmapsetcalled = true,
                };

                ElementContext elementContext = new ShimElementContext
                {
                    ElementGet     = () => element,
                    DataContextGet = () => dc,
                };

                ShimDataManager.GetDefaultInstance = () => new ShimDataManager
                {
                    GetElementContextGuid = (_) => elementContext,
                };

                ScreenShotAction.CaptureScreenShot(Guid.NewGuid());

                // screenshot is not set(null)
                Assert.IsNull(dc.Screenshot);
                // ScreenShotSet was not called.
                Assert.IsFalse(bitmapsetcalled);
            }
        }
        public void DeleteRoomPoints_NotFail_Test()
        {
            bool called = false;
            int  expectedEventDefinitionId = 1;
            int  expectedRoomNumber        = 20;

            IEventDefinitionRepository eventDefinitionService = new StubIEventDefinitionRepository()
            {
                DeleteRoomPointsInt32Int32 = (eventDefinitionId, roomNumber) =>
                {
                    Assert.AreEqual(expectedEventDefinitionId, eventDefinitionId);
                    Assert.AreEqual(expectedRoomNumber, roomNumber);
                    called = true;
                },
                GetByIdInt32 = (id) =>
                {
                    Assert.IsTrue(id == expectedEventDefinitionId);
                    return(new EventDefinition()
                    {
                        OrganizerId = 1
                    });
                }
            };

            using (ShimsContext.Create())
            {
                MyEvents.Api.Authentication.Fakes.ShimMyEventsToken myeventToken = new Authentication.Fakes.ShimMyEventsToken();
                myeventToken.RegisteredUserIdGet     = () => { return(1); };
                ShimMyEventsToken.GetTokenFromHeader = () => { return(myeventToken); };

                var target = new RoomPointsController(eventDefinitionService);

                target.DeleteRoomPoints(expectedEventDefinitionId, expectedRoomNumber);

                Assert.IsTrue(called);
            }
        }
Example #25
0
        public void Index_Not_Authenticated()
        {
            // Arrange:
            using (ShimsContext.Create())
            {
                using (HomeController controller = new HomeController())
                {
                    StubHttpContextBase stubHttpContext = new StubHttpContextBase();

                    controller.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), controller);

                    // Shim the HttpContext.Current
                    var httpRequest      = new HttpRequest("", "http://localhost", "");
                    var httpContext      = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                    var applicationState = httpContext.Application;
                    ShimHttpContext.CurrentGet = () => httpContext;

                    // Stub the Current.User
                    StubIPrincipal principal = new StubIPrincipal();
                    principal.IdentityGet = () =>
                    {
                        return(new StubIIdentity
                        {
                            NameGet = () => "antonio",
                            IsAuthenticatedGet = () => false
                        });
                    };
                    stubHttpContext.UserGet = () => principal;

                    // Act:
                    ActionResult result = controller.Index();

                    // Assert:
                    Assert.IsNotNull(result);
                }
            }
        }
Example #26
0
        public void DeleteTest()
        {
            //Insert first
            InsertTest();

            using (ShimsContext.Create())
            {
                //Verify the ExecuteNonQuery will call SqlCommand.ExecuteNonQuery
                System.Data.SqlClient.Fakes.ShimSqlCommand.AllInstances.ExecuteNonQuery =
                    c =>
                {
                    if (!c.CommandText.StartsWithIgnoreCase("DELETE FROM [dbo].[Categories]"))
                    {
                        return(0);
                    }
                    if (!c.CommandText.ContainsIgnoreCase("WHERE ([CategoryName] LIKE @CategoryName)"))
                    {
                        return(0);
                    }
                    if (c.Parameters.Count != 1)
                    {
                        return(0);
                    }
                    return(1);
                };

                using (var sql = new SqlQueryBuilderContext(ConnectionName))
                {
                    var delete = sql.CreateDeleteQuery();
                    delete.From("Categories")
                    .Where(c => c.Field("CategoryName").Contains("Category"));

                    var v = sql.ExecuteNonQuery(delete);
                    Assert.IsTrue(v > 0);
                }
            }
        }
Example #27
0
        public void CalculateLightCommands_Brightness_Single(byte currentBrightness)
        {
            Primitives.Brightness newBrightness = 128;

            using (ShimsContext.Create())
            {
                Hue hue = new Hue(null);

                hue.UpdateFluxStatus(currentBrightness, CurrentColorTemperature);

                Dictionary <LightCommand, IList <string> > result = hue.CalculateLightCommands(
                    new List <Light>()
                {
                    new Light()
                    {
                        Name  = "Test",
                        Type  = LightExtensions.LightTypeToNameMapping[LightType.WhiteAmbiance],
                        State = new State()
                        {
                            On = true, Brightness = currentBrightness, ColorTemperature = CurrentColorTemperature
                        }
                    },
                },
                    CurrentColorTemperature,
                    newBrightness);

                bool brightnessChangeExpected = currentBrightness == 0 || currentBrightness != newBrightness;

                Assert.AreEqual(brightnessChangeExpected ? 1 : 0, result.Count(), $"One light group expected since change is expected.");

                if (brightnessChangeExpected)
                {
                    Assert.AreEqual((byte?)newBrightness, result.First().Key.Brightness, $"Brightness level should be new level.");
                    Assert.AreEqual(1, result.First().Value.Count, $"1 light in group expected.");
                }
            }
        }
Example #28
0
        public async Task GetReleaseDefinitionsAsyncTest()
        {
            var accountName = "myaccount";
            var projectName = "myproject";
            var service     = new VstsService();

            var expected = new List <ReleaseDefinition>();

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await service.GetBuildDefinitionsAsync(null, projectName, this.token));

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await service.GetBuildDefinitionsAsync(accountName, null, this.token));

            await Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await service.GetBuildDefinitionsAsync(accountName, projectName, null));

            using (ShimsContext.Create())
            {
                var client = new ShimReleaseHttpClientBase(new ShimReleaseHttpClient2())
                {
                    GetReleaseDefinitionsAsyncStringStringNullableOfReleaseDefinitionExpandsStringStringNullableOfInt32StringNullableOfReleaseDefinitionQueryOrderStringNullableOfBooleanIEnumerableOfStringIEnumerableOfStringIEnumerableOfStringObjectCancellationToken
                        = (teamProject, s1, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, cancellationToken) =>
                          Task.Run(
                              () =>
                    {
                        teamProject.Should().Be(projectName);

                        return(expected);
                    },
                              cancellationToken)
                };

                InitializeConnectionShim(client);

                var actual = await service.GetReleaseDefinitionsAsync(accountName, projectName, this.token);

                actual.ShouldBeEquivalentTo(expected);
            }
        }
        public void AppTaskLanguageService_PostUpdateAppTaskLanguageDB_IsContactOK_Error_Test()
        {
            foreach (CultureInfo culture in setupData.cultureListGood)
            {
                SetupTest(contactModelListGood[0], culture);

                using (TransactionScope ts = new TransactionScope())
                {
                    AppTaskModel appTaskModel = appTaskServiceTest.AddAppTaskModel();

                    LanguageEnum LangToAdd = LanguageEnum.es;

                    appTaskLanguageModelNew.AppTaskID = appTaskModel.AppTaskID;
                    FillAppTaskLanguageModel(LangToAdd, appTaskLanguageModelNew);

                    AppTaskLanguageModel appTaskLanguageModelRet = appTaskLanguageService.PostAddAppTaskLanguageDB(appTaskLanguageModelNew);

                    using (ShimsContext.Create())
                    {
                        SetupShim();
                        FillAppTaskLanguageModel(LangToAdd, appTaskLanguageModelRet);

                        string ErrorText = "ErrorText";
                        shimAppTaskLanguageService.IsContactOK = () =>
                        {
                            return(new ContactOK()
                            {
                                Error = ErrorText
                            });
                        };

                        AppTaskLanguageModel appTaskLanguageModelRet2 = UpdateAppTaskLanguageModel(LangToAdd, appTaskLanguageModelRet);
                        Assert.AreEqual(ErrorText, appTaskLanguageModelRet2.Error);
                    }
                }
            }
        }
        public void Open_ProcessStartThrowsEnumeratedException_ReturnsFalse()
        {
            const string fileName = @"c:\xyz\abc";
            const int    id       = 24680;

            using (ShimsContext.Create())
            {
                ShimFile.ExistsString = (f) =>
                {
                    return((f == fileName) ? true : ShimsContext.ExecuteWithoutShims(() => File.Exists(f)));
                };

                A11yElement element = new ShimA11yElement
                {
                    UniqueIdGet = () => id,
                };

                List <Exception> enumeratedExceptions = new List <Exception>
                {
                    new InvalidOperationException(),
                    new ArgumentException(),
                    new ObjectDisposedException("blah", new Exception()),
                    new FileNotFoundException(),
                    new Win32Exception(),
                };

                int exceptionsTested = 0;
                foreach (Exception e in enumeratedExceptions)
                {
                    ILocation location = new OutputFileLocation(fileName, element, (startInfo) => { throw e; });
                    Assert.IsFalse(location.Open(), "Simulated Exception: " + e.ToString());
                    exceptionsTested++;
                }

                Assert.AreEqual(enumeratedExceptions.Count, exceptionsTested);
            }
        }