public void TestLocalFileStore_Yaml() { InitializeLocalStorage(); var rootPath = Path.Combine( Directory.GetCurrentDirectory(), "test-file-store"); var testKey = new TestKey(accountId: Guid.NewGuid()); var testValueA = "Hello, world!"; var testValueB = "Kthx, world!"; var dataStore = new FileStoreDataStore <TestKey, string>( fileStore: new LocalFileStore(rootPath: rootPath), serializer: new ByteSerializer(), keyMap: "test-values/{AccountId}", fileExtension: ".txt"); TestDataStore( dataStore, testKey, testValueA, testValueB); }
public IList <TestResultDescriptionModel> GetResults(TestKey key) { var testResult = _uow.Repository <UserModel>() .GetQueryable() .Include(c => c.TestResults) .FirstOrDefault(CurrentUser.FindUser) .TestResults .LastOrDefault(c => c == key); // TODO: Refactor me var test = _userService.FindTeacher().UserTestModels.LastOrDefault(c => c == key); var list = new List <TestResultDescriptionModel>(); var index = 0; foreach (var testQuestion in test.QuestionModels) { foreach (var testResultQuestion in testResult.QuestionResultModels) { if (testResultQuestion.Text == testQuestion.Text) { var correctAnswers = testQuestion.Options .Where(c => c.IsCorrect) .Select(c => c.Name) .ToArray(); var firstNotSecond = correctAnswers.Except(testResultQuestion.OptionsName.Select(c => c.Name)).ToList(); var result = !firstNotSecond.Any(); ++index; double points = test.NumberOfPoints / test.NumberOfQuestions; string pointResult = (result ? points : default).ToString();
public IFixedLengthKey FactoryMethod(BinaryReader reader) { TestKey testKey = new TestKey(); testKey.Read(reader); return(testKey); }
public void ProcessTakeAvailableItem() { MessageBus bus = new MessageBus(); List <string> messages = new List <string>(); bus.Subscribe <OutputMessage>(m => messages.Add(m.Text)); Item actualItem = null; bus.Subscribe <TakeItemMessage>(m => { messages.Add($"You {m.Verb} the {m.Noun}!"); actualItem = m.Item; }); TestRoom room = new TestRoom(bus); Item expectedItem = new TestKey(bus); room.Add("key", expectedItem); room.Add("coin", new TestCoin(bus)); room.Enter(); bus.Send(new SentenceMessage(new Word("take", "TAKE"), new Word("key", "KEY"))); bus.Send(new SentenceMessage(new Word("look", "LOOK"), new Word(string.Empty, string.Empty))); messages.Should().Equal( "You are in a test room.", "There is a key here.", "There is a coin here.", "You TAKE the KEY!", "You are in a test room.", "There is a coin here."); actualItem.Should().BeSameAs(expectedItem); }
private void button1_Click(object sender, EventArgs e) //проверка ключа { List <FixedKey> fix = new List <FixedKey>(); try { SaveBmp(bm2, $@"{dir}\test"); //сохраняем рисунок ключа bool[,] arrFilled = BmpToMatrix(bm2); //переводим в вид матрицы TestKey newKey = new TestKey(DateTime.Now, arrFilled); //чтение списка эталонных ключей System.IO.FileStream fs = new System.IO.FileStream($@"{dir}\collection.ini", System.IO.FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); fix.Clear();//очищаем коллекцию перед записью из файла do { fix.Add((FixedKey)bf.Deserialize(fs)); } while (fs.Position < fs.Length); fs.Close(); int i = 1; foreach (FixedKey f in fix) { int ck = newKey.CheckTestKey(newKey.matrix, f.matrix); textBox1.Text += $"{i}) {ck}%" + Environment.NewLine; i++; } // NewPic(); //очистка поля после проверки } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public UserTestModel GetTestByTaskDescriptionWithPermution(TestKey key) { var userTestModel = GetTestByTaskDescription(key); if (!userTestModel.Permuted) { return(userTestModel); } var questions = userTestModel.QuestionModels.ToList(); var random = new Random(); for (int i = 0; i < questions.Count; i++) { var pivot = random.Next(0, questions.Count); var temp = questions[pivot]; questions[pivot] = questions[i]; questions[i] = temp; } userTestModel.QuestionModels = questions; return(userTestModel); }
public void ShowConcreteLesson(TestKey key) { var test = _testService.GetTestByTaskDescription(key); RedirectDecorator.ToViewModel(ChangePage.CreateAndPassData(typeof(TestResultViewModel), typeof(UserTestModel), test) ); }
public int Compare(object x, object y) { TestKey xKey = (TestKey)x; TestKey yKey = (TestKey)y; return((int)(xKey._key - yKey._key)); }
public void ShouldNotBeEqual(string keyValue, string otherValue) { var key = new TestKey(keyValue); var otherKey = new TestKey(otherValue); Assert.That(key, Is.Not.EqualTo(otherKey)); }
// TODO: Refactor me public void AddResultToUser(TestKey key, Dictionary <string, ICollection <string> > answers) { var newEntity = TestResultModel.CreateNew(key, answers.Select(c => QuestionResultModel.CreateNew(c.Key, c.Value)).ToList()); try { var existed = _uow.Repository <TestResultModel>().GetQueryable() .Where(c => c.UserModel.Id == CurrentUser.Instance.Id && c.UnitName == key.UnitName && c.LessonName == key.LessonName); if (existed.Any()) { _uow.Repository <TestResultModel>().Delete(existed.ToList()); } newEntity.UserModel = _uow.Repository <UserModel>().GetQueryable().FirstOrDefault(CurrentUser.FindUser); _uow.Repository <TestResultModel>().Add(newEntity); _uow.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); throw; } }
public void RangeSearching3() { TestKey keyFactory = new TestKey(); IBTree bTree = new /*BTree*/ OmniaMeaBTree(_indexFileName, keyFactory); bTree.SetCacheSize(2); bTree.Open(); for (int i = 0; i < 100000; i++) { bTree.InsertKey(new TestKey(2), i); } IntArrayList offsets = new IntArrayList(); bTree.SearchForRange(new TestKey(2), new TestKey(2), offsets); Assert.AreEqual(true, FindOffset(offsets, 9000)); bTree.DeleteKey(new TestKey(2), 9000); offsets.Clear(); bTree.SearchForRange(new TestKey(2), new TestKey(2), offsets); Assert.AreEqual(false, FindOffset(offsets, 9000)); Assert.AreEqual(true, FindOffset(offsets, 1)); bTree.DeleteKey(new TestKey(2), 1); offsets.Clear(); bTree.SearchForRange(new TestKey(2), new TestKey(2), offsets); Assert.AreEqual(false, FindOffset(offsets, 1)); bTree.Close(); }
public void BatchSearching() { TestKey keyFactory = new TestKey(); IBTree bTree = new /*BTree*/ OmniaMeaBTree(_indexFileName, keyFactory); bTree.SetCacheSize(2); bTree.Open(); for (int i = 0; i < 10000; i++) { bTree.InsertKey(new TestKey(i), i); } Assert.AreEqual(10000, bTree.Count); IntArrayList offsets = new IntArrayList(); for (int i = 0; i < 10000; i++) { bTree.DeleteKey(new TestKey(i), i); offsets.Clear(); bTree.SearchForRange(new TestKey(i), new TestKey(Int32.MaxValue), offsets); Assert.AreEqual(10000 - i - 1, offsets.Count); Assert.AreEqual(false, FindOffset(offsets, i)); } Assert.AreEqual(0, bTree.Count); bTree.Close(); bTree.Open(); Assert.AreEqual(0, bTree.Count); bTree.Close(); }
public IFixedLengthKey FactoryMethod( ) { TestKey testKey = new TestKey(); testKey._key = _key; return(testKey); }
/// <summary> /// Marks test as failed with given error message. /// </summary> /// <param name="category">Category of the test</param> /// <param name="testKey">Key of the test</param> /// <param name="errorMessage">Message describing why test failed.</param> public void MarkTestFailure(TestCategory category, TestKey testKey, string errorMessage) { lock (TestStates) { TestStates[category][testKey].Result = false; TestStates[category][testKey].ErrorMessage = errorMessage; } }
/// <summary> /// Marks test as successfull. /// </summary> /// <param name="category">Category of the test</param> /// <param name="testKey">Key of the test</param> public void MarkTestSuccess(TestCategory category, TestKey testKey) { lock (TestStates) { TestStates[category][testKey].Result = true; TestStates[category][testKey].ErrorMessage = ""; } }
public TestKey Create(int value) { var keyValue = value % 2; var key = new TestKey(keyValue); KeysCreated.Add(key); return(key); }
/// <summary> /// Initializes state of test to report. /// </summary> /// <param name="category">Category where the test belongs to.</param> /// <param name="key">Key of the test.</param> private void InitializeTestState(TestCategory category, TestKey key) { lock (TestStates) { TestState testState = new TestState(); testState.Category = category; testState.Key = key; TestStates[testState.Category].Add(testState.Key, testState); } }
protected override void AssertExpectedKeyFactory() { var expected = new KeyValuePair <TestKey, TestValue>(new TestKey(), new TestValue()); Expression <Predicate <FuzzyElement <KeyValuePair <TestKey, TestValue> > > > fuzzyElement = arg => ReferenceEquals(elements, arg.Field <IEnumerable <KeyValuePair <TestKey, TestValue> > >().Value); ConfiguredCall arrange = fuzzy.Build(Arg.Is(fuzzyElement)).Returns(expected); TestKey actual = spec !.Field <Func <TestKey> >().Value !(); Assert.Equal(expected.Key, actual); }
public UserTestModel GetTestByTaskDescription(TestKey key) { var test = _userService.FindTeacher()?.UserTestModels.FirstOrDefault(c => c == key); if (test is null) { throw new InvalidOperationException(); } return(test); }
public void ShouldDeserializeTextKeyValue(string keyValue) { var key = new TestKey(keyValue); var jsonOptions = new JsonSerializerOptions(); jsonOptions.Converters.Add(new TextValueJsonConverter <TestKey>()); var serialized = JsonSerializer.Serialize(key, jsonOptions); Console.WriteLine(serialized); var deserialized = JsonSerializer.Deserialize <TestKey>(serialized); Assert.That(deserialized, Is.EqualTo(key)); }
public async Task TryGet_returnsNone_FromStorageOfAnotherValue() { var provider = new ServiceCollection() .AddStorage(b => b.AddLocal <TestKey, object>().AddLocal <TestKey, string>()) .BuildServiceProvider(); var storage1 = provider.GetRequiredService <IStorage <TestKey, object> >(); var storage2 = provider.GetRequiredService <IStorage <TestKey, string> >(); var key = new TestKey("key"); await storage1.AddOrGet(key, "value"); var value = await storage2.TryGet(key); value.Should().Be((Option <string>)Option.None); }
public async Task TryGet_returnsSome_FromStorageProviderOfTheSameValue() { var provider = new ServiceCollection() .AddStorage(b => b.AddLocal <TestKey, TestValue>()) .BuildServiceProvider(); var storage1 = provider.GetRequiredService <IStorage <TestKey, TestValue> >(); var storage2 = provider.GetRequiredService <IStorage <TestKey, TestValue> >(); var key = new TestKey("key"); await storage1.AddOrGet(key, new TestValue("value")); var value = await storage2.TryGet(key); value.Should().Be(Option.Some(new TestValue("value"))); }
private void btnChkKey_Click(object sender, RoutedEventArgs e) //проверка ключа { if (dir == null) //если не прочитаны настройки (некуда сохранять ключи) - выходим { System.Windows.MessageBox.Show($"Невозможно сохранить ключи.\nЛибо не читаются настройки, либо указана некорректная дирректория сохранения."); return; } bool opened = false; textBox1.Text = null;//##окно для вывода % совпадения ключей, потом убрать Bitmap bmp = MakeBmpFromInkCanvas(); bool[,] arrFilled = BmpToMatrix(bmp);//переводим в вид матрицы тестовый ключ TestKey newKey = new TestKey(DateTime.Now, arrFilled); fix = TakeFixKey(); if (fix == null) { return; //проверяем на наличие ключей } int i = 1; foreach (FixedKey f in fix) { int ck = newKey.CheckTestKey(newKey.matrix, f.matrix); textBox1.Text += $"{i}) {ck}%" + Environment.NewLine; if (ck >= 98 && !opened) { OpenLock(); //##Подумать над механизмом разрешения!!! opened = true; failsCount = 0; //обнуляем счётчик неудачных вводов } i++; } LogWrite($"Произведено сравнение ключа c эталонным."); if (!opened) { failsCount++; } if (failsCount >= 3) //если неудачных попыток ввода >=3 { AlertMail(failsCount); } inkcanvas.Strokes.Clear(); //очищаем поле ввода ключа }
public void SetGetAndRemoveWorksWithObjectKeysWhenDifferentReferences() { var cache = CreateCache(); var obj = new object(); var result = cache.Set(new TestKey(), obj); Assert.Same(obj, result); result = cache.Get(new TestKey()); Assert.Same(obj, result); var key = new TestKey(); cache.Remove(key); result = cache.Get(key); Assert.Null(result); }
public StartedTestViewModel(ITestService testService, ITestResultService testResultService) { _answers = new Dictionary <string, ICollection <string> >(); _testKey = TinyTempCache.Get <Type, TestKey>(typeof(TestKey)); _testService = testService; _testResultService = testResultService; _userTestModel = _testService.GetTestByTaskDescriptionWithPermution(_testKey); _timer = _userTestModel.Duration; NextQuestion = new RelayCommand(ShowNextQuestion); TestResult = new RelayCommand(ShowTestResult); Back = new RelayCommand(ShowBack); Reset(); StartTimer(); }
/** <inheritdoc /> */ public IDictionary AddOneToEachDictionary(IDictionary dict) { var res = new Hashtable(); foreach (DictionaryEntry pair in dict) { var k = new TestKey(((TestKey)pair.Key).Id + 1); var v = new TestValue() { Id = ((TestValue)pair.Value).Id + 1, Name = ((TestValue)pair.Value).Name }; res.Add(k, v); } return(res); }
public void RemoveOneItem() { MessageBus bus = new MessageBus(); List <string> output = new List <string>(); Action <OutputMessage> subscriber = m => output.Add(m.Text); bus.Subscribe(subscriber); TestRoom room = new TestRoom(bus); Item expected = new TestKey(bus); room.Add("key", expected); Item removed = room.Remove("key"); room.Enter(); output.Should().Equal( "You are in a test room."); removed.Should().BeSameAs(expected); }
public void Test_WeakKeyDictionary() { var normalKeyDiction = new Dictionary <TestKey, int>(); var key = new TestKey("Yohan"); var keyReference = new WeakReference(key); normalKeyDiction.Add(key, 1); Assert.AreEqual(1, normalKeyDiction.Count); Assert.AreEqual(1, normalKeyDiction[key]); Assert.IsTrue(keyReference.IsAlive); key = null; GC.Collect(); //Normal Dictionary hold the strong reference to the key. Assert.IsTrue(keyReference.IsAlive); var weakKeyDictionary = new WeakKeyDictionary <TestKey, int>(); key = new TestKey("Yohan"); keyReference = new WeakReference(key); weakKeyDictionary.Add(key, 1); Assert.AreEqual(1, weakKeyDictionary.Count); Assert.AreEqual(1, weakKeyDictionary[key]); IList keys = weakKeyDictionary.Keys; Assert.AreEqual(1, keys.Count); Assert.IsTrue(keyReference.IsAlive); key = null; GC.Collect(); //WeakKeyDictionary hold the WeakReference of the key. Assert.IsFalse(keyReference.IsAlive); GC.KeepAlive(normalKeyDiction); }
public void DropOneItem() { MessageBus bus = new MessageBus(); Dictionary <string, Item> items = new Dictionary <string, Item>(); items["DROP/KEY"] = new TestKey(bus); bus.Subscribe <DropItemMessage>(m => m.Items.Add(m.Noun.Primary, items[$"{m.Verb}/{m.Noun}"])); List <string> output = new List <string>(); bus.Subscribe <OutputMessage>(m => output.Add(m.Text)); TestRoom room = new TestRoom(bus); room.Enter(); bus.Send(new SentenceMessage(new Word("drop", "DROP"), new Word("key", "KEY"))); bus.Send(new SentenceMessage(new Word("look", "LOOK"), new Word(string.Empty, string.Empty))); output.Should().Equal( "You are in a test room.", "You are in a test room.", "There is a key here."); }
public void Test_WeakKeyDictionary() { var normalKeyDiction = new Dictionary<TestKey, int>(); var key = new TestKey("Yohan"); var keyReference = new WeakReference(key); normalKeyDiction.Add(key, 1); Assert.AreEqual(1, normalKeyDiction.Count); Assert.AreEqual(1, normalKeyDiction[key]); Assert.IsTrue(keyReference.IsAlive); key = null; GC.Collect(); //Normal Dictionary hold the strong reference to the key. Assert.IsTrue(keyReference.IsAlive); var weakKeyDictionary = new WeakKeyDictionary<TestKey, int>(); key = new TestKey("Yohan"); keyReference = new WeakReference(key); weakKeyDictionary.Add(key, 1); Assert.AreEqual(1, weakKeyDictionary.Count); Assert.AreEqual(1, weakKeyDictionary[key]); IList keys = weakKeyDictionary.Keys; Assert.AreEqual(1, keys.Count); Assert.IsTrue(keyReference.IsAlive); key = null; GC.Collect(); //WeakKeyDictionary hold the WeakReference of the key. Assert.IsFalse(keyReference.IsAlive); GC.KeepAlive(normalKeyDiction); }
public void SuccessiveClosingOpeningTest() { TestKey keyFactory = new TestKey(); IBTree bTree = new /*BTree*/ OmniaMeaBTree(_indexFileName, keyFactory); bTree.SetCacheSize(16); bTree.Open(); const int bTreeSize = 200003; // !!!!! PRIME NUMBER !!!!! for (int i = 0; i < bTreeSize; ++i) { bTree.InsertKey(new TestKey(i), i); } Random rnd = new Random(); int insert = rnd.Next(bTreeSize) + bTreeSize; int delete = rnd.Next(bTreeSize); for (int i = 0; i < 1000; ++i) { bTree.Close(); bTree.Open(); if (bTreeSize != bTree.Count) { throw new Exception("After Open() bTreeSize != bTree.Count, i = " + i); } for (int j = 0; j < 50; ++j) { bTree.InsertKey(new TestKey(insert), insert); bTree.DeleteKey(new TestKey(delete), delete); insert = (insert + 50000) % bTreeSize + bTreeSize; delete = (delete + 50000) % bTreeSize; } if (bTreeSize != bTree.Count) { throw new Exception("After inserting/deleting bTreeSize != bTree.Count, i = " + i); } } bTree.Close(); }
public void Test_WeakKeyDictionary_CRUD() { var weakKeyDictionary = new WeakKeyDictionary<TestKey, int>(); var key = new TestKey("Yohan"); weakKeyDictionary.Add(key, 1); Assert.AreEqual(1, weakKeyDictionary.Count); Assert.AreEqual(1, weakKeyDictionary[key]); weakKeyDictionary.Remove(key); Assert.AreEqual(0, weakKeyDictionary.Count); Exception exception = null; try { weakKeyDictionary.Remove(null); } catch (ArgumentNullException e) { exception = e; } Assert.IsNotNull(exception); exception = null; try { var i = weakKeyDictionary[new TestKey("1")]; } catch (KeyNotFoundException e) { exception = e; } Assert.IsNotNull(exception); key = new TestKey("Yohan2"); weakKeyDictionary.Add(key, 1); Assert.AreEqual(1, weakKeyDictionary[key]); weakKeyDictionary.Clear(); Assert.AreEqual(0, weakKeyDictionary.Count); weakKeyDictionary.Add(key, 1); Assert.IsTrue(weakKeyDictionary.ContainsKey(key)); Assert.IsTrue(weakKeyDictionary.ContainsValue(1)); weakKeyDictionary[key] = 2; Assert.AreEqual(2, weakKeyDictionary[key]); bool contains = weakKeyDictionary.ContainsValue(2); Assert.IsTrue(contains); exception = null; try { weakKeyDictionary[null] = 3; } catch (ArgumentNullException e) { exception = e; } Assert.IsNotNull(exception); exception = null; try { weakKeyDictionary.Add(key, 1); } catch (ArgumentException e) { exception = e; } Assert.IsNotNull(exception); int value; weakKeyDictionary.TryGetValue(key, out value); Assert.AreEqual(2, value); var count = weakKeyDictionary.Count; key = null; GC.Collect(); weakKeyDictionary.Add(new TestKey("yohan9"), 2); Assert.AreEqual(count, weakKeyDictionary.Keys.Count); }