예제 #1
0
 /// <summary>
 /// Adds the given element to the collection
 /// </summary>
 /// <param name="item">The item to add</param>
 public override void Add(IModelElement item)
 {
     if ((this._parent.UsageModel_UsageScenario == null))
     {
         IUsageModel usageModel_UsageScenarioCasted = item.As <IUsageModel>();
         if ((usageModel_UsageScenarioCasted != null))
         {
             this._parent.UsageModel_UsageScenario = usageModel_UsageScenarioCasted;
             return;
         }
     }
     if ((this._parent.ScenarioBehaviour_UsageScenario == null))
     {
         IScenarioBehaviour scenarioBehaviour_UsageScenarioCasted = item.As <IScenarioBehaviour>();
         if ((scenarioBehaviour_UsageScenarioCasted != null))
         {
             this._parent.ScenarioBehaviour_UsageScenario = scenarioBehaviour_UsageScenarioCasted;
             return;
         }
     }
     if ((this._parent.Workload_UsageScenario == null))
     {
         IWorkload workload_UsageScenarioCasted = item.As <IWorkload>();
         if ((workload_UsageScenarioCasted != null))
         {
             this._parent.Workload_UsageScenario = workload_UsageScenarioCasted;
             return;
         }
     }
 }
예제 #2
0
        private void AssertThatWorkloadFileExists(IWorkload workload)
        {
            string expectedFilePath = Path.Combine(_workloadDirectory, $"Workload_{workload.Id}.json");

            Assert.That(File.Exists(expectedFilePath), Is.True,
                        $"After adding a workload with id {workload.Id}, a file '{expectedFilePath}' should exist.");
        }
        public void AddJob_ShouldCreateAndAddTheJob()
        {
            //Arrange
            string    name     = Guid.NewGuid().ToString();
            int       capacity = 10;
            IWorkload workload = CreateWorkload(name, capacity);

            string jobDescription = Guid.NewGuid().ToString();

            var originalJobCollection = workload.Jobs;

            //Act
            workload.AddJob(jobDescription);

            //Assert
            Assert.That(workload.Jobs.Count, Is.EqualTo(1), "The 'Jobs' property should contain 1 job.");
            IJob addedJob = workload.Jobs.First();

            Assert.That(addedJob, Is.Not.Null, "The added job should not be null.");
            Assert.That(addedJob.Description, Is.EqualTo(jobDescription), "The description of the added job is not correct.");
            Assert.That(addedJob.WorkloadId, Is.EqualTo(workload.Id), "The 'workloadId' of the added job is not correct.");

            Assert.That(workload.Jobs, Is.SameAs(originalJobCollection),
                        "The collection that is returned by the 'Jobs' property should be the same object in memory than the collection that is returned by the 'Jobs' property after the construction of the workload. " +
                        "Tip1: The 'Jobs' property should not have a setter. Use a backing field. " +
                        "Tip2: List<IJob> implements the IReadOnlyCollection<IJob> interface.");
        }
        public void AddJobButtonClick_WorkloadSelected_ShouldAddJobAndUpdateTheUI()
        {
            Button addJobButton = _window.FindVisualChildren <Button>().FirstOrDefault(b => (b.Content as string) == "Add job");

            Assert.That(addJobButton, Is.Not.Null, "Could not find a Button with content 'Add job'.");

            TextBox jobDescriptionTextBox = _window.FindVisualChildren <TextBox>().FirstOrDefault(tb => tb.Name == "JobDescriptionTextBox");

            Assert.That(jobDescriptionTextBox, Is.Not.Null, "Could not find a TextBox with the name 'JobDescriptionTextBox'.");

            string jobDescription = Guid.NewGuid().ToString();

            jobDescriptionTextBox.Text = jobDescription;

            var       selectedWorkloadMock = new Mock <IWorkload>();
            IWorkload selectedWorkload     = selectedWorkloadMock.Object;

            _window.SelectedWorkload = selectedWorkload;

            addJobButton.FireClickEvent();

            selectedWorkloadMock.Verify(wl => wl.AddJob(jobDescription), Times.Once,
                                        "The 'AddJob' method should be called on the selected workload. " +
                                        "The description should be the contents of the job description TextBox.");

            _workLoadRepositoryMock.Verify(repo => repo.SaveChanges(selectedWorkload), Times.Once,
                                           "After adding the job the workload should be saved in the repository.");

            Assert.That(jobDescriptionTextBox.Text, Is.Empty, "After adding the job, the TextBox should be cleared.");
        }
        private void AddAndStart(IWorkload workload)
        {
            _workloads.Enqueue(workload);
            bool startedHere = false;

            if (!_isRunning)
            {
                lock (_padlock)
                {
                    if (!_isRunning)
                    {
                        _isRunning  = true;
                        startedHere = true;
                    }
                }
            }

            if (startedHere)
            {
                Task.Run(() =>
                {
                    while (_workloads.TryDequeue(out IWorkload toRun))
                    {
                        toRun.Run();
                    }

                    _isRunning = false;
                }).RunInBackgroundSafely(false, LogWorkloadException);
            }
        }
예제 #6
0
 private void AssertWorkloadEquality(IWorkload workload1, IWorkload workload2, string errorMessage)
 {
     Assert.That(workload1.Id, Is.EqualTo(workload2.Id), $"{errorMessage} - The id's don't match.");
     Assert.That(workload1.Capacity, Is.EqualTo(workload2.Capacity), $"{errorMessage} - The capacities don't match.");
     Assert.That(workload1.Name, Is.EqualTo(workload2.Name), $"{errorMessage} - The names don't match.");
     Assert.That(workload1.Jobs, Is.Not.Null, $"{errorMessage} - The jobs of one of the workload is null.");
     Assert.That(workload2.Jobs, Is.Not.Null, $"{errorMessage} - The jobs of one of the workload is null.");
     Assert.That(workload1.Jobs.Count, Is.EqualTo(workload2.Jobs.Count), $"{errorMessage} - The jobs don't match.");
 }
        private string ConvertWorkloadToJson(IWorkload workload)
        {
            string json = JsonConvert.SerializeObject(workload, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            });

            return(json);
        }
        public void ToString_ShouldReturnAStringContainingNameAndCapacity()
        {
            string name     = Guid.NewGuid().ToString();
            int    capacity = Random.Next(1, int.MaxValue);

            IWorkload workload = CreateWorkload(name, capacity);

            string workLoadAsText = workload.ToString();

            Assert.That(workLoadAsText, Does.StartWith(name), "The first part should be the name of the workload.");
            Assert.That(workLoadAsText, Does.Contain(capacity.ToString()), "The capacity is not found in the returned string.");
        }
        public void Constructor_ShouldInitializeProperly()
        {
            string name     = Guid.NewGuid().ToString();
            int    capacity = Random.Next(1, int.MaxValue);

            IWorkload workload = CreateWorkload(name, capacity);

            Assert.That(workload.Name, Is.EqualTo(name), "The 'Name' is not initialized correctly.");
            Assert.That(workload.Capacity, Is.EqualTo(capacity), "The 'Capacity' is not initialized correctly.");
            Assert.That(workload.Id, Is.Not.EqualTo(Guid.Empty), "The constructor should generate and assign a Guid to the 'Id' property.");
            Assert.That(workload.Jobs, Is.Not.Null, "The 'Jobs' list should be an empty list.");
            Assert.That(workload.Jobs.Count, Is.Zero, "The 'Jobs' list should be an empty list.");
        }
        public void AddJob_MaximumCapacityReached_ShouldThrowAnInvalidOperationException()
        {
            //Arrange
            string    name     = Guid.NewGuid().ToString();
            int       capacity = 1;
            IWorkload workload = CreateWorkload(name, capacity);

            workload.AddJob(Guid.NewGuid().ToString());

            //Act + Assert
            Assert.That(() => workload.AddJob(Guid.NewGuid().ToString()), Throws.InvalidOperationException,
                        "When a second job is added to a workload of capacity '1', an InvalidOperationException should be thrown.");
        }
        public void ShouldHaveAPrivateParameterLessConstructorAndPrivateSettersForJsonConversionToWork()
        {
            var constructor = _workloadType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
                              .FirstOrDefault(c => c.IsPrivate);

            Assert.That(constructor, Is.Not.Null, "Cannot find a private constructor.");
            Assert.That(constructor.GetParameters().Length, Is.Zero, "The private constructor should not have parameters.");

            IWorkload workload = constructor.Invoke(new object[] { }) as IWorkload;

            Assert.That(workload, Is.Not.Null, "Could not cast the 'Workload' to an 'IWorkload'.");
            Assert.That(workload.Jobs, Is.Not.Null, "The 'Jobs' list should be an empty list after the private constructor is used.");
            Assert.That(workload.Jobs.Count, Is.Zero, "The 'Jobs' list should be an empty list after the private constructor is used.");

            AssertHasPrivateSetter(_workloadType, nameof(IWorkload.Id));
            AssertHasPrivateSetter(_workloadType, nameof(IWorkload.Name));
            AssertHasPrivateSetter(_workloadType, nameof(IWorkload.Capacity));
        }
예제 #12
0
        public void SaveChanges_ShouldOverwriteTheMatchingWorkloadFile()
        {
            //Arrange
            TestWorkload workload = new WorkloadBuilder().Build() as TestWorkload;

            try
            {
                _repository.Add(workload);
            }
            catch (Exception)
            {
                Assert.Fail(
                    $"Make sure that the test '{nameof(Add_ShouldSaveAJsonVersionOfTheWorkloadInAFile)}' is green, before attempting to make this test green.");
            }

            string newName     = "EditedName";
            int    newCapacity = workload.Capacity + 1;

            //Act
            workload.Name     = newName;
            workload.Capacity = newCapacity;
            _repository.SaveChanges(workload);

            //Assert
            IReadOnlyList <IWorkload> allWorkloads = null;

            try
            {
                allWorkloads = _repository.GetAll();
            }
            catch (Exception)
            {
                Assert.Fail(
                    $"Make sure that the test '{nameof(GetAll_ShouldRetrieveAllAddedWorkloads)}' is green, before attempting to make this test green.");
            }

            Assert.That(allWorkloads.Count, Is.EqualTo(1), "Only one workload should be returned by 'GetAll' after adding 1 workload and updating it.");

            IWorkload updatedWorkload = allWorkloads.First();

            Assert.That(updatedWorkload.Name, Is.EqualTo(newName), "A change in the name is not saved correctly.");
            Assert.That(updatedWorkload.Capacity, Is.EqualTo(newCapacity), "A change in the capacity is not saved correctly.");
        }
        public void AddWorkloadButtonClick_ShouldUseTheRepositoryAndUpdateTheUI()
        {
            Button addWorkloadButton = _window.FindVisualChildren <Button>().FirstOrDefault(b => (b.Content as string) == "Add workload");

            Assert.That(addWorkloadButton, Is.Not.Null, "Could not find a Button with content 'Add workload'.");

            TextBox workloadNameTextBox = _window.FindVisualChildren <TextBox>().FirstOrDefault(tb => tb.Name == "WorkloadNameTextBox");

            Assert.That(workloadNameTextBox, Is.Not.Null, "Could not find a TextBox with the name 'WorkloadNameTextBox'.");

            string workloadName = Guid.NewGuid().ToString();

            workloadNameTextBox.Text = workloadName;

            IWorkload addedWorkload = null;

            _workLoadRepositoryMock.Setup(repo => repo.Add(It.IsAny <IWorkload>()))
            .Callback((IWorkload workload) =>
            {
                addedWorkload = workload;
            });

            addWorkloadButton.FireClickEvent();

            Assert.That(addedWorkload, Is.Not.Null, "The 'Add' method of the repository should be called.");
            Assert.That(addedWorkload.Name, Is.EqualTo(workloadName), "The workload that is passed in should contain the name filled in in the TextBox.");
            Assert.That(addedWorkload.Capacity, Is.EqualTo(10), "The workload that is passed in should have a capacity of 10.");

            Assert.That(_window.AllWorkloads, Contains.Item(addedWorkload),
                        "The workload that is added in the repository should also be added to the 'AllWorkloads' collection.");

            Assert.That(_window.SelectedWorkload, Is.SameAs(addedWorkload),
                        "The workload that is added in the repository should  also be the 'SelectedWorkload'.");

            Assert.That(workloadNameTextBox.Text, Is.Empty, "After adding the workload, the TextBox should be cleared.");
        }
        public Task Run(IWorkload workload, IBucket bucket, Action <WorkloadResult> onWorkloadCompleted)
        {
            Ensure.That(workload, "workload").IsNotNull();
            Ensure.That(onWorkloadCompleted, "onWorkloadCompleted").IsNotNull();

            try
            {
                return(Task.WhenAll(
                           Enumerable.Range(1, _numOfClients)
                           .Select(index =>
                {
                    return workload.Execute(bucket, index)
                    .ContinueWith(task =>
                    {
                        onWorkloadCompleted(task.Result);
                    });
                })
                           ));
            }
            catch (Exception ex)
            {
                throw new Exception($"Exception while running workload tasks for \"{workload.GetType().Name}\".", ex);
            }
        }
 public void Add(IWorkload workload)
 {
     SaveWorkload(workload);
 }
 private void SaveWorkload(IWorkload workload)
 {
     //TODO: save the workload in a json format in a file
     //Tip: use helper methods that are given (GetWorkloadFilePath, ConvertWorkloadToJson)
 }
        public void Start(string[] args)
        {
            Logger.Debug("OnStart");

            items            = new WorkloadCollection();
            ServiceStopping += items.StopEventHandler;
            Logger.Debug("Reading configuration data");
            WorkloadConfigurationSection config = null;

            try
            {
                config =
                    (WorkloadConfigurationSection)ConfigurationManager.GetSection(
                        "WorkloadConfiguration");

                if (config.Workloads.Count == 0)
                {
                    Logger.Error("No workloads configured.");
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }

            foreach (WorkloadConfiguration wcfg in config.Workloads)
            {
                Logger.Debug($"Creating workload {wcfg.WorkloadName}.");
                try
                {
                    Logger.Debug($"Creating instance of {wcfg.WorkloadType}");
                    IWorkload w = null;
                    if (wcfg.WorkloadAssembly == "")
                    {
                        Logger.Debug("Loading from main assembly");
                        w = (IWorkload)Assembly.GetExecutingAssembly().CreateInstance(wcfg.WorkloadType);
                    }
                    else
                    {
                        Logger.Debug($"Loading from assembly '{wcfg.WorkloadAssembly}");
                        Assembly a = Assembly.Load(wcfg.WorkloadAssembly);
                        w = (IWorkload)a.CreateInstance(wcfg.WorkloadType);
                    }

                    if (w == null)
                    {
                        Logger.Error($"Unable to create instance of {wcfg.WorkloadType}");
                        continue;
                    }
                    foreach (WorkloadProperty wProp in wcfg.WorkloadProperties)
                    {
                        Logger.Debug($"Setting property [{wProp.PropertyName}] to '{wProp.PropertyValue}'.");
                        PropertyInfo p = w.GetType().GetProperty(wProp.PropertyName);
                        if (p != null)
                        {
                            if (p.PropertyType == typeof(string))
                            {
                                p.SetValue(w, wProp.PropertyValue);
                            }
                            else if (p.PropertyType == typeof(int?))
                            {
                                p.SetValue(w, int.Parse(wProp.PropertyValue));
                            }
                            else if (p.PropertyType == typeof(int))
                            {
                                p.SetValue(w, int.Parse(wProp.PropertyValue));
                            }
                            else if (p.PropertyType == typeof(bool))
                            {
                                p.SetValue(w, bool.Parse(wProp.PropertyValue));
                            }
                            else
                            {
                                Logger.Error($"Unsupported configuration property type {p.PropertyType}");
                            }
                        }
                    }
                    items.Add(w);
                }
                catch (Exception e)
                {
                    Logger.Error(e.Message, e);
                }
            }


            Logger.Info($"{ServiceName} started.");
            items.Start();
        }
 public void SaveChanges(IWorkload workload)
 {
     SaveWorkload(workload);
 }