Example #1
0
        async Task TestApiFunction(ApiTestSetup setup, bool withContent = true)
        {
            var                  expectedContent    = new { message = "hello" };
            const string         handlerName        = "handler_name";
            const HttpStatusCode expectedStatusCode = HttpStatusCode.OK;
            const string         expectedId         = "23421";

            var server = new MockHttpServer();
            WithServiceClause withServiceClause = server.WithService("http://www.base.com/sub");

            setup(withServiceClause, "user?id={id}", new [] { "PUT" }, expectedContent, expectedStatusCode, handlerName);

            HttpClient client = CreateClient(server);

            HttpResponseMessage response = await client.PutAsJsonAsync($"http://www.base.com/sub/user?id={expectedId}", new object());

            Assert.Equal(expectedStatusCode, response.StatusCode);

            if (withContent)
            {
                string actualMessage = JsonConvert.DeserializeAnonymousType(
                    await response.Content.ReadAsStringAsync(),
                    expectedContent).message;
                Assert.Equal(expectedContent.message, actualMessage);
            }

            server[handlerName].VerifyHasBeenCalled();
            server[handlerName].VerifyHasBeenCalled(1);
            server[handlerName].VerifyBindedParameter("id", expectedId);
        }
        public void TestTxSigner()
        {
            List <String> mnemonic = new List <String>(singleVector.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            // Create the network info
            NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: localbech32Hrp, lcdUrl: localTestUrl);

            // Build a transaction
            MsgSend msg = new MsgSend(
                fromAddress: "cosmos1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2",
                toAddress: "cosmos12lla7fg3hjd2zj6uvf4pqj7atx273klc487c5k",
                amount: new List <StdCoin> {
                new StdCoin(denom: "uatom", amount: "100")
            }
                );
            // Fee
            StdFee fee = new StdFee(
                gas: "200000",
                amount: new List <StdCoin> {
                new StdCoin(denom: "uatom", amount: "250")
            }
                );
            StdTx tx = TxBuilder.buildStdTx(stdMsgs: new List <StdMsg> {
                msg
            }, fee: fee);
            // Create a wallet
            Wallet wallet = Wallet.derive(mnemonic, networkInfo);

            // Verify Wallet
            Assert.AreEqual(wallet.networkInfo.bech32Hrp, networkInfo.bech32Hrp);
            Assert.AreEqual(wallet.networkInfo.lcdUrl, networkInfo.lcdUrl);

            // Build the mockup server
            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <String, Object> accResponse  = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.AccountDataResponse);
            Dictionary <String, Object> NodeResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.NodeInfoResponse);

            // Initialize Server Response
            _server
            .WithService(localTestUrl)
            .Api("auth/accounts/{wallettAddress}", accResponse)
            .Api("node_info", NodeResponse);

            // Link the client to the retrieval classes
            HttpClient client = new HttpClient(_server);

            AccountDataRetrieval.client = client;
            NodeInfoRetrieval.client    = client;

            // Call without await to avoid marking test class as async
            StdTx signedTx = TxSigner.signStdTx(wallet: wallet, stdTx: tx).Result;

            Assert.AreEqual(signedTx.signatures.Count, 1);

            StdSignature signature = (signedTx.signatures.ToArray())[0];

            Assert.AreEqual(signature.publicKey.type, "tendermint/PubKeySecp256k1");
            Assert.AreEqual(signature.publicKey.value, "ArMO2T5FNKkeF2aAZY012p/cpa9+PqKqw2GcQRPhAn3w");
            Assert.AreEqual(signature.value, "m2op4CCBa39fRZD91WiqtBLKbUQI+1OWsc1tJkpDg+8FYB4y51KahGn26MskVMpTJl5gToIC1pX26hLbW1Kxrg==");
        }
Example #3
0
        public async Task should_get_optional_query_parameters_of_uri()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Api(
                "user/{userId}/session/{sessionId}?p1={value1}&p2={value2}",
                "GET",
                _ => new { Parameter = _ }.AsResponse());

            HttpClient client = CreateClient(server);

            HttpResponseMessage response = await client.GetAsync(
                "http://www.base.com/user/12/session/28000?p2=v2");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            string jsonString = await response.Content.ReadAsStringAsync();

            var content = JsonConvert.DeserializeAnonymousType(
                jsonString,
                new { Parameter = default(Dictionary <string, object>) });

            Assert.Equal(string.Empty, content.Parameter["value1"]);
            Assert.Equal("v2", content.Parameter["value2"]);
        }
        public void NetworkQueryReturnsCorrectData()
        {
            const String localTestUrl = "http://example.com";

            // Build the mockup server
            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <String, Object> nodeResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.SentDocumentResponseJson);

            // Initialize Server Response
            _server
            .WithService(localTestUrl)
            .Api("", "GET", nodeResponse);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;

            // Test response
            JArray resultList = Network.queryChain(localTestUrl).Result as JArray;

            List <NetworkTestData> testDataList = resultList.Select(json => new NetworkTestData((JObject)json)).ToList();

            Assert.IsTrue(testDataList.Count == 4);
            Assert.IsTrue("did:com:1zfhgwfgex8rc9t00pk6jm6xj6vx5cjr4ngy32v" == testDataList[0].sender);
            Assert.IsTrue("6a881ef0-04da-4524-b7ca-6e5e3b7e61dc" == testDataList[1].uuid);
        }
Example #5
0
        public async Task should_not_confuse_between_different_systems()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://service1.com")
            .Api("user", new { message = "from service 1" })
            .Done()
            .WithService("http://service2.com")
            .Api("user", new { message = "from service 2" })
            .Done();

            HttpClient client = CreateClient(server);

            HttpResponseMessage responseSvc1 = await client.GetAsync("http://service1.com/user");

            HttpResponseMessage responseSvc2 = await client.GetAsync("http://service2.com/user");

            HttpResponseMessage responseSvc3 = await client.GetAsync("http://service-not-exist.com/user");

            var template = new { message = default(string) };

            Assert.Equal("from service 1", (await responseSvc1.ReadAs(template)).message);
            Assert.Equal("from service 2", (await responseSvc2.ReadAs(template)).message);
            Assert.Equal(HttpStatusCode.NotFound, responseSvc3.StatusCode);
        }
Example #6
0
        public async void should_get_request_conent_from_calling_history_even_if_original_request_has_been_disposed()
        {
            var server = new MockHttpServer();

            server.WithService("http://www.base.com")
            .Api("login", "POST", HttpStatusCode.OK, "login");

            var client = new HttpClient(server);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://www.base.com/login")
            {
                Content = new StringContent(
                    JsonConvert.SerializeObject(new { username = "******", password = "******" }), Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(request);

            response.Dispose();
            request.Dispose();

            var actualRequestContent = await server["login"].SingleOrDefaultRequestContentAsync(
                new { username = string.Empty, password = string.Empty });

            Assert.Equal("n", actualRequestContent.username);
            Assert.Equal("p", actualRequestContent.password);
        }
Example #7
0
        public async Task should_distinguish_sub_applications()
        {
            var server = new MockHttpServer();

            server.WithService("http://domain.com/apps/app1")
            .Api("user", HttpStatusCode.OK);

            server.WithService("http://domain.com/apps/app2")
            .Api("user", HttpStatusCode.Accepted);

            HttpClient client = CreateClient(server);

            HttpResponseMessage responseApp1 = await client.GetAsync("http://domain.com/apps/app1/user");

            HttpResponseMessage responseApp2 = await client.GetAsync("http://domain.com/apps/app2/user");

            Assert.Equal(HttpStatusCode.OK, responseApp1.StatusCode);
            Assert.Equal(HttpStatusCode.Accepted, responseApp2.StatusCode);
        }
Example #8
0
        public async Task should_get_lastest_matched_defintion_even_at_different_level()
        {
            var server = new MockHttpServer();

            server.WithService("http://domain.com/apps/app1")
            .Api("/", HttpStatusCode.BadRequest)
            .Api("user", HttpStatusCode.OK);

            HttpClient          client = CreateClient(server);
            HttpResponseMessage responseWithoutOverride = await client.GetAsync("http://domain.com/apps/app1");

            Assert.Equal(HttpStatusCode.BadRequest, responseWithoutOverride.StatusCode);

            server.WithService("http://domain.com/apps")
            .Api("{appName}", HttpStatusCode.Accepted);

            HttpResponseMessage response = await client.GetAsync("http://domain.com/apps/app1");

            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
        }
Example #9
0
        public async Task should_return_404_if_no_handler_matches_for_uri(
            string serviceUri, string template, string requestUri)
        {
            var server = new MockHttpServer();

            server.WithService(serviceUri).Api(template, "GET", HttpStatusCode.OK);

            HttpClient          client   = CreateClient(server);
            HttpResponseMessage response = await client.GetAsync(requestUri);

            Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
        }
        // '"fromWallet()" returns a well-formed "BuyMembership" object.'
        public async Task WellFormedBuyMembershipFromWalletAsync()
        {
            //This is the comparison class
            CompareLogic  compareLogic   = new CompareLogic();
            String        lcdUrl         = "http://localhost:1317";
            string        didcom         = "1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:" + didcom, lcdUrl: "");
            String        mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            MembershipType membershipType = MembershipType.GREEN;

            BuyMembership expectedBuyMembership = new BuyMembership(membershipType: MyEnumExtensions.ToEnumMemberAttrValue(membershipType), buyerDid: wallet.bech32Address, tsp: "");

            BuyMembership buyMembership = BuyMembershipHelper.fromWallet(wallet, MembershipType.GREEN, tsp: "");

            MsgBuyMembership MsgMember     = new MsgBuyMembership(buyMembership);
            String           localTestUrl1 = $"{lcdUrl}/commercio/MsgBuyMembership";

            var _server = new MockHttpServer();

            //////  I need this in order to get the correct data out of the mock server
            ////Dictionary<string, object> nodeResponse1 = JsonConvert.DeserializeObject<Dictionary<String, Object>>(TestResources.TestResources.accountResponse);
            ////// Dictionary<String, Object> nodeResponse2 = JsonConvert.DeserializeObject<Dictionary<String, Object>>(TestResources.TestResources.tumblerIdentityJson);
            ////// Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", MsgMember);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient();

            Network.client = client;
            // Get the server response
            HttpResponseMessage response = await client.GetAsync(localTestUrl1);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                System.ArgumentException argEx = new System.ArgumentException($"Expected status code OK (200) but got ${response.StatusCode} - ${response.ReasonPhrase}");
                throw argEx;
            }

            // Parse the data
            String jsonResponse = await response.Content.ReadAsStringAsync();



            Assert.AreEqual(compareLogic.Compare(buyMembership.toJson(), expectedBuyMembership.toJson()).AreEqual, true);
        }
        public async Task should_change_default_behavior_if_default_exists()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Default(req => HttpStatusCode.Found.AsResponse());

            HttpClient client = CreateClient(server);

            HttpResponseMessage response = await client.GetAsync("http://www.base.com/any-uri");

            Assert.Equal(HttpStatusCode.Found, response.StatusCode);
        }
        public async Task should_override_by_another_default_definition()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Default(req => HttpStatusCode.Found.AsResponse())
            .Default(req => HttpStatusCode.Accepted.AsResponse());

            HttpClient          client   = CreateClient(server);
            HttpResponseMessage response = await client.GetAsync("http://www.base.com/any-uri");

            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
        }
Example #13
0
        public async Task should_handle_by_latest_matched_uri()
        {
            var server = new MockHttpServer();

            server.WithService("http://www.base.com/user")
            .Api("account", HttpStatusCode.OK, "route 1")
            .Api("account", "GET", HttpStatusCode.OK, "route 2");

            HttpClient          client   = CreateClient(server);
            HttpResponseMessage response = await client.GetAsync("http://www.base.com/user/account");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            server["route 2"].VerifyHasBeenCalled();
            server["route 1"].VerifyNotCalled();
        }
        public async Task should_be_traced()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Api("api", HttpStatusCode.OK)
            .Default(req => HttpStatusCode.Found.AsResponse(), "default");

            HttpClient client = CreateClient(server);

            await client.PostAsJsonAsync("http://www.base.com/not-exist", new {});

            server["default"].VerifyHasBeenCalled();
        }
        public async Task DidDocumentFromWalletJsonTest()
        {
            String lcdUrl = "http://localhost:1317";
            // string didcom = "1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: lcdUrl);
            String        mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            // Here the mock server part...
            // Build the mockup server

            String localTestUrl1 = $"{lcdUrl}/auth/accounts/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";
            // String localTestUrl2 = $"{lcdUrl}/identities/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";

            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <string, object> nodeResponse1 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.accountResponse);

            // Dictionary<String, Object> nodeResponse2 = JsonConvert.DeserializeObject<Dictionary<String, Object>>(TestResources.TestResources.tumblerIdentityJson);
            // Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", nodeResponse1);
            //_server
            //    .WithService(localTestUrl2)
            //    .Api("", "GET", nodeResponse2);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;

            KeyPair rsaKeyPair = KeysHelper.generateRsaKeyPair();
            KeyPair ecKeyPair  = KeysHelper.generateEcKeyPair();

            List <PublicKey> pubKeys = new List <PublicKey>();

            pubKeys.Add(rsaKeyPair.publicKey);
            pubKeys.Add(ecKeyPair.publicKey);

            DidDocument       didDocument = DidDocumentHelper.fromWallet(wallet, pubKeys);
            TransactionResult results     = await IdHelper.setDidDocument(didDocument, wallet);

            // Just to test no exception in the code
            Assert.AreEqual(true, true);
        }
Example #16
0
        public async Task should_return_desired_message_if_handler_matches_for_uri(
            string serviceUri, string route, string requestUri)
        {
            var server  = new MockHttpServer();
            var content = new { name = "hello" };

            server.WithService(serviceUri).Api(route, "GET", content);

            HttpClient          client   = CreateClient(server);
            HttpResponseMessage response = await client.GetAsync(requestUri);

            Assert.Equal(response.StatusCode, HttpStatusCode.OK);
            var actualContent = JsonConvert.DeserializeAnonymousType(
                await response.Content.ReadAsStringAsync(),
                content);

            Assert.Equal("hello", actualContent.name);
        }
        public async Task should_be_override_by_more_specific_api()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Api("api", HttpStatusCode.OK)
            .Default(req => HttpStatusCode.Found.AsResponse());

            HttpClient client = CreateClient(server);

            HttpResponseMessage responseDefault = await client.GetAsync("http://www.base.com/any-uri");

            HttpResponseMessage responseApi = await client.GetAsync("http://www.base.com/api");

            Assert.Equal(HttpStatusCode.Found, responseDefault.StatusCode);
            Assert.Equal(HttpStatusCode.OK, responseApi.StatusCode);
        }
Example #18
0
        public async Task should_verify_api_called_times()
        {
            var httpServer = new MockHttpServer();

            httpServer
            .WithService("http://www.base.com")
            .Api("api1", "GET", HttpStatusCode.OK, "api1")
            .Api("api2", "GET", HttpStatusCode.OK, "api2");

            HttpClient client = CreateClient(httpServer);

            await client.GetAsync("http://www.base.com/api1");

            await client.GetAsync("http://www.base.com/api1");

            IRequestHandlerTracer tracer = httpServer["api1"];

            tracer.VerifyHasBeenCalled(2);
            Assert.Throws <VerifyException>(() => tracer.VerifyHasBeenCalled(3));
        }
Example #19
0
        public async void should_get_request_content_from_calling_history()
        {
            var server = new MockHttpServer();

            server.WithService("http://www.base.com")
            .Api("login", "POST", HttpStatusCode.OK, "login");

            var client = new HttpClient(server);

            HttpResponseMessage response = await client.PostAsJsonAsync(
                "http://www.base.com/login",
                new { username = "******", password = "******" });

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var actualRequestContent = await server["login"].SingleOrDefaultRequestContentAsync(
                new { username = string.Empty, password = string.Empty });

            Assert.Equal("n", actualRequestContent.username);
            Assert.Equal("p", actualRequestContent.password);
        }
Example #20
0
        public async Task should_verify_api_called_or_not_called()
        {
            var httpServer = new MockHttpServer();

            httpServer
            .WithService("http://www.base.com")
            .Api("api1", "GET", HttpStatusCode.OK, "api1")
            .Api("api2", "GET", HttpStatusCode.OK, "api2");

            HttpClient client = CreateClient(httpServer);

            await client.GetAsync("http://www.base.com/api1");

            httpServer["api1"].VerifyHasBeenCalled();
            Assert.Throws <VerifyException>(
                () => httpServer["api1"].VerifyNotCalled());
            httpServer["api2"].VerifyNotCalled();
            Assert.Throws <VerifyException>(
                () => httpServer["api2"].VerifyHasBeenCalled());
        }
Example #21
0
        public async Task should_return_desired_message_if_http_method_is_matched(
            string httpMethodConfig, string actualMethod)
        {
            string[] httpMethods = httpMethodConfig.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (httpMethods.Length == 0)
            {
                httpMethods = null;
            }

            var server = new MockHttpServer();

            server.WithService("http://www.base.com").Api("user", httpMethods, HttpStatusCode.OK);

            HttpRequestMessage request = new HttpRequestMessage(
                new HttpMethod(actualMethod), "http://www.base.com/user");
            HttpClient          client   = CreateClient(server);
            HttpResponseMessage response = await client.SendAsync(request);

            Assert.Equal(response.StatusCode, HttpStatusCode.OK);
        }
        public async Task should_not_confuse_with_default_behavior_of_different_services()
        {
            var server = new MockHttpServer();

            server
            .WithService("http://www.base.com")
            .Default(req => HttpStatusCode.Found.AsResponse())
            .Done()
            .WithService("http://www.another.com")
            .Default(req => HttpStatusCode.NotAcceptable.AsResponse())
            .Done();

            HttpClient          client       = CreateClient(server);
            HttpResponseMessage responseBase = await client.GetAsync("http://www.base.com");

            HttpResponseMessage responseAnother = await client.GetAsync("http://www.another.com");

            HttpResponseMessage responseNotExist = await client.GetAsync("http://www.not-exist.com");

            Assert.Equal(HttpStatusCode.Found, responseBase.StatusCode);
            Assert.Equal(HttpStatusCode.NotAcceptable, responseAnother.StatusCode);
            Assert.Equal(HttpStatusCode.NotFound, responseNotExist.StatusCode);
        }
Example #23
0
        // '"fromWallet()" returns a well-formed "RequestDidPowerUp" object.'
        public async Task WellFormedRequestDidPowerUpFromWallet()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            String        lcdUrl         = "http://localhost:1317";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: lcdUrl);
            String        mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            Wallet pairwaisedWallet = Wallet.derive(mnemonic, networkInfo, lastDerivationPathSegment: "1");

            List <StdCoin> amount = new List <StdCoin> {
                new StdCoin(denom: "denom", amount: "10")
            };

            // Here the mock server part...
            // Build the mockup server
            String localTestUrl1 = $"{lcdUrl}/government/tumbler";
            String localTestUrl2 = $"{lcdUrl}/identities/did:com:1fvwfjx2yealxyw5hktqnvm5ynljlc8jqkkd8kl";

            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <string, object> nodeResponse1 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerAddressJson);
            Dictionary <String, Object> nodeResponse2 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerIdentityJson);

            // Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", nodeResponse1);
            _server
            .WithService(localTestUrl2)
            .Api("", "GET", nodeResponse2);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;


            KeyPair keyPair = KeysHelper.generateRsaKeyPair();

            String powerUpProof  = "powerUpProof";
            String uuid          = Guid.NewGuid().ToString();
            String encryptionKey = "encryptionKey";

            RequestDidPowerUp expectedRequestDidPowerUp = new RequestDidPowerUp(
                claimantDid: wallet.bech32Address,
                amount: amount,
                powerUpProof: Convert.ToBase64String(Encoding.UTF8.GetBytes(powerUpProof)),
                uuid: uuid,
                encryptionKey: Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptionKey))
                );

            RequestDidPowerUp requestDidPowerUp = await RequestDidPowerUpHelper.fromWallet(
                wallet,
                pairwaisedWallet.bech32Address,
                amount,
                (RSAPrivateKey)keyPair.privateKey
                );

            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.claimantDid, expectedRequestDidPowerUp.claimantDid).AreEqual, true);
            Assert.AreEqual(requestDidPowerUp.amount.Count, expectedRequestDidPowerUp.amount.Count);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.amount[0].toJson(), expectedRequestDidPowerUp.amount[0].toJson()).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.uuid, expectedRequestDidPowerUp.uuid).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.powerUpProof, expectedRequestDidPowerUp.powerUpProof).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.encryptionKey, expectedRequestDidPowerUp.encryptionKey).AreEqual, false);
        }
        // '"fromWallet()" returns a well-formed "RequestDidPowerUp" object.'
        public async Task WellFormedRequestDidPowerUpFromWallet()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            String        lcdUrl         = "http://url";
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: lcdUrl);
            String        mnemonicString = "dash ordinary anxiety zone slot rail flavor tortoise guilt divert pet sound ostrich increase resist short ship lift town ice split payment round apology";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            Wallet pairwaisedWallet = Wallet.derive(mnemonic, networkInfo, lastDerivationPathSegment: "1");

            List <StdCoin> amount = new List <StdCoin> {
                new StdCoin(denom: "denom", amount: "10")
            };

            // Here the mock server part...
            // Build the mockup server
            String localTestUrl1 = $"{lcdUrl}/government/tumbler";
            String localTestUrl2 = $"{lcdUrl}/identities/did:com:14ttg3eyu88jda8udvxpwjl2pwxemh72w0grsau";

            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <string, object> nodeResponse1 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerAddressJson);
            Dictionary <String, Object> nodeResponse2 = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.TestResources.tumblerIdentityJson);

            // Initialize Server Response
            _server
            .WithService(localTestUrl1)
            .Api("", "GET", nodeResponse1);
            _server
            .WithService(localTestUrl2)
            .Api("", "GET", nodeResponse2);

            // Link the client to the retrieval class Network
            HttpClient client = new HttpClient(_server);

            Network.client = client;


            KeyPair keyPair = KeysHelper.generateRsaKeyPair();

            String powerUpProof  = "powerUpProof";
            String uuid          = Guid.NewGuid().ToString();
            String encryptionKey = "encryptionKey";

            RequestDidPowerUp expectedRequestDidPowerUp = new RequestDidPowerUp(
                claimantDid: wallet.bech32Address,
                amount: amount,
                powerUpProof: Convert.ToBase64String(Encoding.UTF8.GetBytes(powerUpProof)),
                uuid: uuid,
                encryptionKey: Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptionKey))
                );

            RequestDidPowerUp requestDidPowerUp = await RequestDidPowerUpHelper.fromWallet(
                wallet,
                pairwaisedWallet.bech32Address,
                amount,
                (RSAPrivateKey)keyPair.privateKey
                );

            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.claimantDid, expectedRequestDidPowerUp.claimantDid).AreEqual, true);
            Assert.AreEqual(requestDidPowerUp.amount.Count, expectedRequestDidPowerUp.amount.Count);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.amount[0].toJson(), expectedRequestDidPowerUp.amount[0].toJson()).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.uuid, expectedRequestDidPowerUp.uuid).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.powerUpProof, expectedRequestDidPowerUp.powerUpProof).AreEqual, false);
            Assert.AreEqual(compareLogic.Compare(requestDidPowerUp.encryptionKey, expectedRequestDidPowerUp.encryptionKey).AreEqual, false);
        }
Example #25
0
        public void should_throw_if_service_address_is_not_an_absolute_uri()
        {
            var server = new MockHttpServer();

            Assert.Throws <UriFormatException>(() => server.WithService("/uri"));
        }