public Task GetLoadMetricsSingleItem() { return(this.RunDataSizeUnitsPermutationAsync(async config => { Uri collectionName = new Uri("test://dictionary"); int key = 1; string value = "Homer"; BinaryValueConverter converter = new BinaryValueConverter(collectionName, new JsonReliableStateSerializerResolver()); double size = converter.Serialize <int>(key).Buffer.Length + converter.Serialize <string>(value).Buffer.Length; double expectedMemory = size / (double)config.MemoryMetricUnits; double expectedDisk = size / (double)config.DiskMetricUnits; MockReliableDictionary <BinaryValue, BinaryValue> store = new MockReliableDictionary <BinaryValue, BinaryValue>(collectionName); MetricReliableDictionary <int, string> target = new MetricReliableDictionary <int, string>(store, converter, config); using (ITransaction tx = new MockTransaction()) { await target.SetAsync(tx, key, value); await tx.CommitAsync(); } using (ITransaction tx = new MockTransaction()) { IEnumerable <DecimalLoadMetric> result = await target.GetLoadMetricsAsync(tx, CancellationToken.None); Assert.AreEqual <int>(1, result.Count(x => x.Name == config.MemoryMetricName && x.Value == expectedMemory)); Assert.AreEqual <int>(1, result.Count(x => x.Name == config.DiskMetricName && x.Value == expectedDisk)); } })); }
public async void ShouldNotGetNonExistantKvpConfig() { var dict = await _service.StateManager.GetOrAddAsync <IReliableDictionary <ConfigKey, KvpConfig> >(CoreService.KvpDictionaryName); KvpConfig config = null; using (var tx = new MockTransaction()) { config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); await tx.CommitAsync(); } if (await dict.GetCountAsync(new MockTransaction()) != 1) { Assert.False(true, "The config key was not saved. The test will not proceed"); } var val = await _service.GetConfigSetting(new ConfigKey("NotAKey", "1.0.0")); Assert.True(val == null, "The service returned a response.... That ain't right"); }
public async void ShouldThrowInvalidOpEx_WhenConfigAlreadyExists() { var dict = await _service.StateManager.GetOrAddAsync <IReliableDictionary <ConfigKey, KvpConfig> >(CoreService.KvpDictionaryName); KvpConfig config = null; using (var tx = new MockTransaction()) { config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); await tx.CommitAsync(); } KvpConfig newconfig = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; await Assert.ThrowsAnyAsync <InvalidOperationException>(() => _service.AddConfigSetting(newconfig)); }
private static string GetCellDepData(MockTransaction mockTx, Script script) { if (script.HashType == "data") { return(GetCellDepDataByDataHash(mockTx, script.CodeHash)); } return(GetCellDepDataByTypeHash(mockTx, script.CodeHash)); }
public RecurringTransactionTester() { MockFrequency = new MockFrequency(); BaseTransaction = new MockTransaction() { Value = 500 }; }
public async Task Storing_value() { var dictionary = new MockReliableDictionary <Guid, MyDto>(new Uri("fabric://popo")); var dto = new MyDto(Guid.NewGuid(), "toto", "jean", 32, new DateTime(1985, 02, 11)); var tx = new MockTransaction(null, 1); await dictionary.AddAsync(tx, dto.Id, dto); }
public void DisposeTest() { MockTransaction trans = new MockTransaction(); trans.Dispose(); Assert.False(trans.IsCommitted); Assert.False(trans.IsRolledback); Assert.True(trans.IsDisposed); Assert.True(trans.Disposing); }
[Test] // bug #325397 public void DisposeTest () { MockTransaction trans = new MockTransaction (); trans.Dispose (); Assert.IsFalse (trans.IsCommitted, "#1"); Assert.IsFalse (trans.IsRolledback, "#2"); Assert.IsTrue (trans.IsDisposed, "#3"); Assert.IsTrue (trans.Disposing, "#4"); }
public void AddAction() { TransactionContainer container = presenter.TransactionContainer; Transaction transaction = new MockTransaction(database); container.Add(transaction); string expected = transaction.ToString() + Environment.NewLine; Assert.AreEqual(expected, view.transactionsText); }
[TestMethod] // bug #325397 public void DisposeTest() { MockTransaction trans = new MockTransaction(); trans.Dispose(); Assert.IsFalse(trans.IsCommitted, "#1"); Assert.IsFalse(trans.IsRolledback, "#2"); Assert.IsTrue(trans.IsDisposed, "#3"); Assert.IsTrue(trans.Disposing, "#4"); }
private static string GetCellDepDataByDataHash(MockTransaction mockTx, string codeHash) { foreach (MockCellDep cellDep in mockTx.MockInfo.CellDeps) { string dataHash = ComputeDataHash(cellDep.Data); if (codeHash == dataHash) { return(cellDep.Data); } } throw new Exception("CellDep not found!"); }
/// <summary> /// Any operation on a TransactedCollection that has an abort or commit action needs to be added to the MockTransaction /// so the actions can be executed in EndTransaction(). /// </summary> /// <param name="tx">MockTransaction</param> /// <returns></returns> protected MockTransaction BeginTransaction(ITransaction tx) { MockTransaction mtx = tx as MockTransaction; if (mtx != null) { mtx.TryAddTransactedCollection(this); return(mtx); } throw new ArgumentException("Must be a non-null MockTransaction", nameof(tx)); }
public void AddAction() { TransactionContainer container = presenter.TransactionContainer; Transaction transaction = new MockTransaction(); container.Add(transaction); string expected = transaction.ToString() + Environment.NewLine; Assert.AreEqual(expected, view.transactionsText); }
public void TestCommitCallsTransactionCommit() { var conn = new MockConnection(); var tran = new MockTransaction(); using (var scope = new DbScope(conn, tran)) { Assert.IsFalse(tran.IsCommited); scope.Commit(); Assert.IsTrue(tran.IsCommited); Assert.IsNull(scope.Transaction); } }
public void TestDiposeCallsTransactionDispose() { var conn = new MockConnection(); var tran = new MockTransaction(); using (var scope = new DbScope(conn, tran)) { Assert.IsFalse(tran.IsCommited); Assert.IsFalse(tran.IsDisposed); } Assert.IsTrue(tran.IsDisposed); }
public async Task DictionaryAddDuplicateKeyExceptionTypeTest() { const string key = "key"; var dictionary = new MockReliableDictionary <string, string>(new Uri("fabric://MockReliableDictionary")); var tx = new MockTransaction(null, 1); await dictionary.AddAsync(tx, key, "value"); await Assert.ThrowsExceptionAsync <ArgumentException>(async() => { await dictionary.AddAsync(tx, key, "value"); }); }
public async Task DictionaryAddAndRetrieveTest() { const string key = "key"; const string value = "value"; var dictionary = new MockReliableDictionary <string, string>(new Uri("fabric://MockReliableDictionary")); var tx = new MockTransaction(null, 1); await dictionary.AddAsync(tx, key, value); var actual = await dictionary.TryGetValueAsync(tx, key); Assert.AreEqual(actual.Value, value); }
public async Task DictionaryCountTest() { const string key = "key"; const string value = "value"; var dictionary = new MockReliableDictionary <string, string>(new Uri("fabric://MockReliableDictionary")); var tx = new MockTransaction(null, 1); await dictionary.AddAsync(tx, key, value); var actual = dictionary.Count; Assert.AreEqual(1, actual); }
private static string GetCellDepDataByTypeHash(MockTransaction mockTx, string codeHash) { foreach (MockCellDep cellDep in mockTx.MockInfo.CellDeps) { if (cellDep.Output.Type != null) { string typeHash = ComputeScriptHash(cellDep.Output.Type); if (codeHash == typeHash) { return(cellDep.Data); } } } throw new Exception("CellDep not found!"); }
public void RunTransactions() { MockTransaction transaction = new MockTransaction(); presenter.TransactionContainer.Add(transaction); Employee employee = new Employee(123, "John", "123 Baker St."); database.AddEmployee(employee); presenter.RunTransactions(); Assert.IsTrue(transaction.wasExecuted); Assert.AreEqual("", view.transactionsText); string expectedEmployeeTest = employee.ToString() + Environment.NewLine; Assert.AreEqual(expectedEmployeeTest, view.employeesText); }
public void RunTransactions() { MockTransaction transaction = new MockTransaction(database); presenter.TransactionContainer.Add(transaction); Employee employee = new Employee(123, "Kubing", "123 Baker St."); database.AddEmployee(employee); presenter.RunTransactions(); Assert.IsTrue(transaction.wasExecuted); Assert.AreEqual("", view.transactionsText); string expectedEmployeeTest = employee.ToString() + Environment.NewLine; Assert.AreEqual(expectedEmployeeTest, view.employeesText); }
private static MockTransaction DumpTransaction(Client client, Transaction tx) { MockInput[] mockInputs = tx.Inputs.Select((input) => GetMockInput(client, input)).ToArray(); MockCellDep[] mockCellDeps = tx.CellDeps.SelectMany((cellDep) => GetMockCellDep(client, cellDep)).ToArray(); Header[] mockHeaders = tx.HeaderDeps.Select((headerDep) => GetMockHeader(client, headerDep)).ToArray(); MockTransaction mockTx = new MockTransaction { MockInfo = new MockInfo { Inputs = mockInputs, CellDeps = mockCellDeps, HeaderDeps = mockHeaders, }, Tx = tx }; return(mockTx); }
public async Task DictionaryCreateKeyEnumerableAsyncTest() { const string key = "key"; const string value = "value"; var dictionary = new MockReliableDictionary <string, string>(new Uri("fabric://MockReliableDictionary")); var tx = new MockTransaction(null, 1); await dictionary.AddAsync(tx, key, value); var enumerable = await dictionary.CreateKeyEnumerableAsync(tx); var enumerator = enumerable.GetAsyncEnumerator(); await enumerator.MoveNextAsync(CancellationToken.None); var actual = enumerator.Current; Assert.AreEqual(key, actual); }
public Task GetLoadMetricsEmptyDictionary() { return(RunDataSizeUnitsPermutationAsync(async config => { int expected = 0; Uri collectionName = new Uri("test://dictionary"); MockReliableDictionary <BinaryValue, BinaryValue> store = new MockReliableDictionary <BinaryValue, BinaryValue>(collectionName); BinaryValueConverter converter = new BinaryValueConverter(collectionName, new JsonReliableStateSerializerResolver()); MetricReliableDictionary <int, string> target = new MetricReliableDictionary <int, string>(store, converter, config); using (ITransaction tx = new MockTransaction()) { IEnumerable <DecimalLoadMetric> result = await target.GetLoadMetricsAsync(tx, CancellationToken.None); Assert.AreEqual <int>(1, result.Count(x => x.Name == config.MemoryMetricName && x.Value == expected)); Assert.AreEqual <int>(1, result.Count(x => x.Name == config.DiskMetricName && x.Value == expected)); } })); }
public async void ShouldGetLatestKvpConfigByName() { var dict = await _service.StateManager.GetOrAddAsync <IReliableDictionary <ConfigKey, KvpConfig> >(CoreService.KvpDictionaryName); KvpConfig config = null; using (var tx = new MockTransaction()) { config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.1.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); var config2 = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key2 = new ConfigKey(config2); await dict.TryAddAsync(tx, key2, config2); await tx.CommitAsync(); } if (await dict.GetCountAsync(new MockTransaction()) != 2) { Assert.False(true, "The config key was not saved. The test will not proceed"); } var val = await _service.GetLatestConfigSetting("Test"); Assert.True(val != null, "The srevice returned a null response. That ain't right"); Assert.True(val.Equals(config), "The service returned a value but it did not equal the stored config"); }
public async void ShouldSaveConfig() { var dict = new MockReliableDictionary <ConfigKey, KvpConfig>(); using (var tx = new MockTransaction()) { var config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); await dict.TryAddAsync(tx, key, config); await tx.CommitAsync(); } using (var tx = new MockTransaction()) { var config = new KvpConfig() { Value = "Test", Name = "Test", Type = "String", Version = "1.0.0" }; var key = new ConfigKey(config); var val = await dict.TryGetValueAsync(tx, key); Assert.True(val.HasValue); Assert.Equal(val.Value.Name, config.Name); Assert.Equal(val.Value.Type, config.Type); Assert.Equal(val.Value.Version, config.Version); Assert.Equal(val.Value.Value, config.Value); } }
public IActionResult ProcessTransaction([FromBody] MockTransaction transaction) { var response = new BankResponse(); //We are interested in what responses the mocked bank is giving us, not how, in this case switch (transaction.TransactionAmount) { case 200: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Successful; response.SubStatus = TransactionSubStatus.Successful; break; case 05: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.DeclinedDonothonour; break; case 12: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.InvalidPayment; break; case 14: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.InvalidCardNumber; break; case 51: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.InsufficientFunds; break; case 54: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.BadTrackData; break; case 62: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.RestrictedCard; break; case 63: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.SecurityViolation; break; case 9998: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.ResponseTimeout; break; case 150: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.CardNot3DSecureEnabled; break; case 6900: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.UnableToSpecifyIfCardIsSecureEnabled; break; case 5000: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.SecureSystemMalfunction3DSecure; break; case 6510: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.SecureAuthenticationRequired3DSecure; break; case 33: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.ExpiredCard; break; case 4001: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.PaymentBlockedDueToRisk; break; case 4008: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.CardNumberBlacklisted; break; case 2011: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.StopPaymenttThisAuth; break; case 2013: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Failed; response.SubStatus = TransactionSubStatus.StopPaymentAll; break; default: response.BankResponseID = Guid.NewGuid(); response.Status = TransactionStatus.Successful; response.SubStatus = TransactionSubStatus.Successful; break; } return(Ok(response)); }
public async Task <IActionResult> OnGet(string?txHash, string?ioType, int?ioIndex, int?scriptType, string?filePath, int?txId = null) { if (ioType != "input" && ioType != "output") { throw new Exception("ioType must be `input` or `output`!"); } if (ioIndex == null) { throw new Exception("ioIndex cannot be null!"); } if (scriptType == null) { throw new Exception("scriptType cannot be null!"); } if (txId == null && (txHash == null || txHash == "")) { throw new Exception("txId and txHash cannot be all null!"); } Client client = Rpc(); Transaction transaction; if (txId != null) { RecordedTransaction?failedTransaction = await DbContext.RecordedTransactions.FirstOrDefaultAsync(t => t.Id == txId); if (failedTransaction == null) { throw new Exception($"Failed transaction not found, check your txID: {txId}"); } try { transaction = Transaction.FromJson(failedTransaction.RawTransaction); } catch { throw new Exception("Failed Transaction cannot parsed to Transaction!"); } } else { TransactionWithStatus?txWithStatus = client.GetTransaction(txHash !); if (txWithStatus == null) { throw new Exception($"Transaction not found: {txHash}"); } transaction = txWithStatus.Transaction; } Output output = transaction.Outputs[(int)ioIndex]; if (ioType == "input") { Input input = transaction.Inputs[(int)ioIndex]; TransactionWithStatus originTx = client.GetTransaction(input.PreviousOutput.TxHash) !; output = originTx.Transaction.Outputs[TypesConvert.HexToUInt32(input.PreviousOutput.Index)]; } if (scriptType == 1 && output.Type == null) { throw new Exception($"Type script not found in {{tx_hash: {txHash}, index: {ioIndex}, ioType: {ioType}}}"); } Script script = scriptType == 0 ? output.Lock : output.Type; string scriptHash = ComputeScriptHash(script); MockTransaction mockTx = DumpTransaction(client, transaction); mockTx.Tx.Hash = null; string targetContractData = GetCellDepData(mockTx, script); string binaryFilePath = WriteToFile(scriptHash, targetContractData); string?binaryForDebugger = null; if (filePath != null) { binaryFilePath = filePath; binaryForDebugger = filePath; } string mockTxFilePath = WriteMockTx(scriptHash, mockTx.ToJson()); string scriptGroupType = scriptType == 0 ? "lock" : "type"; try { DebuggerProcessManager.Start(ActiveProject !, scriptGroupType, scriptHash, mockTxFilePath, binaryFilePath, ioType, (int)ioIndex, binaryForDebugger); } catch (System.InvalidOperationException e) { TempData["ErrorMessage"] = e.Message; } return(Page()); }
public void PubSubNeverPicksUpOwnTransactions() { _testName = System.Reflection.MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString(); using (var fLock = new ManagedFileLock(_testName)) { Cleanup(); using (var pdb1 = new Database<Guid, MockClassA>(_testName + ".subscriber" + ".database", "ReplicationID", new FileCore<Guid, long>()) .WithPublishing("Test", new FilePublisher<Guid, MockClassA>(Path.Combine(Environment.CurrentDirectory, _testName))) .WithSubscription("Test", new FileSubscriber<Guid, MockClassA>(Path.Combine(Environment.CurrentDirectory, _testName), new TimeSpan(0, 0, 0, 0, 500)))) { pdb1.Load(); pdb1.Clear(); using (var t = pdb1.BeginTransaction()) { pdb1.Delete(o => o != null); t.Commit(); } Assert.IsTrue(Directory.Exists(Path.Combine(Environment.CurrentDirectory, _testName))); var objects = TestResourceFactory.GetMockClassAObjects(25).OfType<MockClassC>().ToList(); var negativeObjects = TestResourceFactory.GetMockClassAObjects(25).OfType<MockClassC>().ToList(); using (var t = pdb1.BeginTransaction()) { objects.ForEach(o => pdb1.Add(o)); t.Commit(); } var testTran = new MockTransaction<Guid, MockClassA>( new TransactionManager<Guid, MockClassA>( new MockTransactionFactory<Guid, MockClassA>() , new TransactionSynchronizer<Guid, MockClassA>())); testTran.Source = pdb1.TransactionSource; foreach (var no in negativeObjects) testTran.Enlist(Action.Create, no.ReplicationID, (MockClassA)no); testTran.Commit(); var formatter = new BSONFormatter(); using (var fs = new FileStream( Path.Combine(Environment.CurrentDirectory, _testName, testTran.Id.ToString() + ".trans") , FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, false)) { var s = formatter.FormatObjStream(testTran); s.WriteAllTo(fs); fs.Flush(); fs.Close(); } Thread.Sleep(750); var sw = new Stopwatch(); sw.Start(); while (pdb1.FileFlushQueueActive && sw.ElapsedMilliseconds < 3000) Thread.Sleep(100); Assert.AreEqual(25, pdb1.Length); } } }