集成测试(端到端):如何使用NodeJS检查Azure事件网格上的消息?

huangapple go评论133阅读模式
英文:

Integration Test (E2E): How to check message on Azure Event Grid with NodeJS?

问题

我有一个.NET HttpTrigger Azure函数,它接收请求主体并将其发送到Azure事件网格主题。

我需要为此编写一个NodeJS/TS的E2E或集成测试。我的想法是模仿向Azure函数发送HTTP Post请求,然后检查/观察消息是否存在于EventGrid主题中作为检查条件,但这比说起来容易得多。

我找到了一个非常酷的.NET项目,但不幸的是,我无法使用它,因为我的测试项目使用了PlayWright和NodeJS。

这篇Microsoft 文章 讨论了如何创建一个使用Azure Relay连接的Node客户端/服务器。但是,我不确定如何将它整合到我的测试中,甚至不确定是否是正确的做法?

import { test as base, APIResponse } from '@playwright/test';

let _respStatus: number;
let _response: APIResponse;

// 触发 Azure 函数
base.step('Send POST to "admin/functions/FunctionName"', async () => {
  _response = await request.post('admin/functions/FunctionName', { data: null });
  _respStatus = _response.status();
});

// 通过 Azure Relay 监听 Event Grid 主题上的消息
base.step("Listen for Event Grid message", async () => {
  const https = require("hyco-https");
  const ns = "{RelayNamespace}";
  const path = "{HybridConnectionName}";
  const keyrule = "{SASKeyName}";
  const key = "{SASKeyValue}";

  var uri = https.createRelayListenUri(ns, path);
  var server = https.createRelayedServer(
    {
      server: uri,
      token: () => https.createRelayToken(uri, keyrule, key),
    },
    (req, res) => {
      res.setHeader("Content-Type", "text/html");
      res.end("<html><head><title>Hey!</title></head><body>Relayed Node.js Server!</body></html>");
    }).listen(() => {});
});

<details>
<summary>英文:</summary>

I have a .NET HttpTrigger Azure Function which takes the request body and emit it to an Azure Event Grid topic.

I need to write an E2E or integration test for this in NodeJS/TS.  My thought is to mimic a HTTP Post request to the Azure function and then check/observe the message exists within the EventGrid topic as a check condition but that is easier said than done.  


I found a [very cool project in .NET][2] but unfortunately I cannot use it because my test project is using PlayWright and NodeJS.

This Microsoft [article][1] talks about create a Node client/server using Azure Relay Connection.  But, I am not sure how to incorporate it into my test, or even if it is the right thing to do?


      import  { test as base, APIResponse } from &#39;@playwright/test&#39;;

      let _respStatus: number;
      let _response: APIResponse;

      //Trigger the Azure Function
      base.step(&#39;Send POST to \&quot;admin/functions/FunctionName\&quot;&#39;, async () =&gt; {
        _response = await request.post(&#39;admin/functions/FunctionName&#39;,{ data: null });
        _respStatus = _response.status();
      });

      //Check for the message on Event Grid Topic via Azure Relay
      base.step(&quot;Listen for Event Grid message&quot;, async () =&gt; {
        const https = require(&quot;hyco-https&quot;);
        const ns = &quot;{RelayNamespace}&quot;;
        const path = &quot;{HybridConnectionName}&quot;;
        const keyrule = &quot;{SASKeyName}&quot;;
        const key = &quot;{SASKeyValue}&quot;;

        var uri = https.createRelayListenUri(ns, path);
        var server = https.createRelayedServer(
          {
            server: uri,
            token: () =&gt; https.createRelayToken(uri, keyrule, key),
          },
          (req, res) =&gt; {
            res.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
            res.end(&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Hey!&lt;/title&gt;&lt;/head&gt;&lt;body&gt;Relayed Node.js Server!&lt;/body&gt;&lt;/html&gt;&quot;);
          }).listen(() =&gt; {});

  [1]: https://learn.microsoft.com/en-us/azure/azure-relay/relay-hybrid-connections-http-requests-node-get-started
  [2]: https://eventgrid.arcus-azure.net/Features/running-integration-tests

</details>


# 答案1
**得分**: 0

I managed to get it working. Here is the general idea behind my solution.

- 在Azure云上创建一个Azure Relay,创建一个混合连接并让它订阅Event Grid以接收我的测试消息。
- 使用Node.js编写一个'服务器'以连接到Azure Relay以接收数据。在这种情况下,Azure Relay充当客户端,向服务器代码发送请求消息。
- 将此服务器代码包装在我的Playwright测试用例的test.beforeAll()中,以便每次运行测试时,此HTTP服务器都会开始侦听。
- 当此'服务器'从Azure Relay接收到消息时,它会解析消息并设置任何变量,例如消息ID,以供稍后在我的测试验证中使用。

我已经为您翻译了所需的部分,不包括代码部分。有关更多详细信息,请访问https://learn.microsoft.com/en-us/azure/azure-relay/relay-hybrid-connections-http-requests-node-get-started。

<details>
<summary>英文:</summary>

I managed to get it working.  Here is the general idea behind my solution.

 - Create an Azure Relay on Azure cloud, create a hybrid connection and have it subscribed to the
   Event Grid to receive my test messages. 
 - Write a &#39;server&#39; using nodeJs
   to hook into the Azure Relay in order to receive data.  In this case
   the Azure Relay acts as a client which sends request message to the
   server code. 
 - Wrap this server code inside the test.beforeAll() in my
   Playwrite test case so that each time the test run, this http server
   will start listening. 
 - When this &#39;server&#39; receives message from Azure Relay, it parses
   the message and set any variable such as the message Id
   which I can use later in my test validation.


       test.beforeAll(async ({ getFunctionAppApiContext, a0UserCredentials }) =&gt; 
       {
           let _response: APIResponse;
           let _respBody: any;
           let respId: string;
           let server: any;
           var qs = require(&#39;querystring&#39;);
           let eventGridMessage: string;

         const https = require(&quot;hyco-https&quot;);

         const ns = &#39;&lt;relay_name&gt;.servicebus.windows.net&#39;;
         const path = &#39;&lt;hybrid_connection_name&gt;&#39;;
         const keyrule = &#39;&lt;hybrid_connection_policy_name&gt;&#39;;
         const key = &#39;&lt;hybrid_connection_key&gt;&#39;;
  
         //setup the listener to listen events from Azure Relay
         var uri = https.createRelayListenUri(ns, path);
         server = https.createRelayedServer(
         {
             server: uri,
             token: () =&gt; https.createRelayToken(uri, keyrule, key),
         },
         //process request from Azure relay originated from event grid 
         (req, res) =&gt; {
            var bodyStream = &#39;&#39;;
            req.on(&#39;data&#39;, function(incomingData) {
                bodyStream += incomingData;
            });
            
            req.on(&#39;end&#39;, () =&gt; {
           eventGridMessage = qs.parse(bodyStream);
          });
         }).listen();
       });


The details that I based my solution on can be found at https://learn.microsoft.com/en-us/azure/azure-relay/relay-hybrid-connections-http-requests-node-get-started 


</details>



huangapple
  • 本文由 发表于 2023年6月9日 04:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定