登录
首页 >  Golang >  Go问答

当使用“count”标志多次运行测试时,net/rpc 服务器保持注册状态

来源:stackoverflow

时间:2024-04-28 09:09:35 444浏览 收藏

大家好,我们又见面了啊~本文《当使用“count”标志多次运行测试时,net/rpc 服务器保持注册状态》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

该程序创建一个 rpc 服务器和一个客户端,并通过 rpc 接口公开多个方法。

多个测试函数分别测试其中一种方法。

第一个测试函数注册rpc服务器:

    rpcserver := new(rpcserver)
    rpc.register(rpcserver)
    rpc.handlehttp()

使用通道,每个函数都会等待服务器发出它正在运行的信号,当客户端完成时,发出信号让服务器关闭。

在测试函数中:

    // start the server
    ch := make(chan bool, 1)
    go runrpcserver(ch)

    // wait for the server to start
    <-ch

    ...do some work...

    // close the server
    ch <- true
    close(ch)

在服务器函数中:

    listener, err := net.listen("tcp4", "")
    if err != nil {
        log.fatal("could not open a listener port: ", err.error())
    }
    wg := sync.waitgroup{}
        wg.add(1)
        // start the server
        rpcserver := http.server{}
        go func() {
            go rpcserver.serve(listener)
            // signal that the server is running
            ch <- true
            // wait for the command to close the server
            <-ch
            <-ch
            // shutdown server and exit
            if err := rpcserver.shutdown(context.background()); err != nil {
                log.printf("http server shutdown: %v\n", err)
            }
            listener.close()
            wg.done()
    }()
    wg.wait()

当运行测试一次甚至多次时,一切都工作得很好:

去测试 -count 1 ./src/rpcserver/ 去测试 -count 1 ./src/rpcserver/

但是,在运行时

去测试-计数2 ./src/rpcserver/

第二次运行开始时返回错误:

--- 失败:testrpcserver(0.00s) 恐慌:http:/gorpc 的多个注册 [已恢复] 恐慌:http:/gorpc 的多个注册

我想知道为什么

去测试-计数2 ./src/rpcserver/

行为并不完全如下:

去测试 -count 1 ./src/rpcserver/ 去测试 -count 1 ./src/rpcserver/

为了在连续运行的测试之间取消注册服务器,可以做什么?

编辑: 这是说明该问题的完整最小示例:

server.go:

package rpcserver

import (
    "context"
    "log"
    "net"
    "net/http"
    "net/rpc"
)

type rpcserver int

// rpc: only methods that comply with the following scheme are exported:
// func (t *t) methodname(argtype t1, replytype *t2) error

// since rpc-exposed methods must takes an argument.
type emptyarg struct{}

// expose several methods via the rpc interface:
func (rpcserver *rpcserver) method_1(emptyarg emptyarg, reply *string) error {

    *reply = "this is method_1"
    return nil
}

func (rpcserver *rpcserver) method_2(emptyarg emptyarg, reply *string) error {

    *reply = "this is method_2"
    return nil
}

func (rpcserver *rpcserver) method_3(emptyarg emptyarg, reply *string) error {

    *reply = "this is method_3"
    return nil
}

// should be called only once per process
func registerrpcmethods() {

    // register the rpc methods
    rpcserver := new(rpcserver)
    rpc.register(rpcserver)
    rpc.handlehttp()
}

func runrpcserver(ch chan struct{}) {

    // open a listener port
    listener, err := net.listen("tcp4", "127.0.0.1:38659")
    if err != nil {
        log.fatal("listen error:", err)
    }

    // print some data
    log.println("server running")
    log.println("network:", listener.addr().network())

    // start the server
    rpcserver := http.server{}
    go func() {
        go rpcserver.serve(listener)
        // signal that the server is running
        ch <- struct{}{}
        // wait for the command to close the server
        <-ch
        // shutdown server and exit
        if err := rpcserver.shutdown(context.background()); err != nil {
            log.printf("http server shutdown: %v\n", err)
        }
        listener.close()
        // signal that the server is closed
        ch <- struct{}{}
    }()
}

server_test.go:

package rpcserver

import (
    "net/rpc"
    "testing"
)

func TestMethod_1(t *testing.T) {

    // call once.
    // (test functions are executed in-order)
    RegisterRPCMethods()

    // start the server
    ch := make(chan struct{})
    go RunRPCServer(ch)

    // wait for the server to start
    <-ch

    // Dial to the rpc server
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:38659")
    if err != nil {
        t.Errorf("Could not dial %s: %s", "127.0.0.1:38659", err.Error())
    }
    // the called function allready asserting type.
    reply := ""
    err = client.Call("RPCServer.Method_1", EmptyArg{}, &reply)
    if err != nil {
        t.Error(err)
    }

    // close the server
    ch <- struct{}{}
    // wait for the server to close
    <-ch
    close(ch)
}

func TestMethod_2(t *testing.T) {

    // start the server
    ch := make(chan struct{})
    go RunRPCServer(ch)

    // wait for the server to start
    <-ch

    // Dial to the rpc server
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:38659")
    if err != nil {
        t.Errorf("Could not dial %s: %s", "127.0.0.1:38659", err.Error())
    }
    // the called function allready asserting type.
    reply := ""
    err = client.Call("RPCServer.Method_2", EmptyArg{}, &reply)
    if err != nil {
        t.Error(err)
    }

    // close the server
    ch <- struct{}{}
    // wait for the server to close
    <-ch
    close(ch)
}

func TestMethod_3(t *testing.T) {

    // start the server
    ch := make(chan struct{})
    go RunRPCServer(ch)

    // wait for the server to start
    <-ch

    // Dial to the rpc server
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:38659")
    if err != nil {
        t.Errorf("Could not dial %s: %s", "127.0.0.1:38659", err.Error())
    }
    // the called function allready asserting type.
    reply := ""
    err = client.Call("RPCServer.Method_3", EmptyArg{}, &reply)
    if err != nil {
        t.Error(err)
    }

    // close the server
    ch <- struct{}{}
    // wait for the server to close
    <-ch
    close(ch)
}

运行时:

去测试-v-count 1 ./src/server/...

输出符合预期:

=== 运行测试方法_1 2022/05/11 10:59:49 服务器运行中 2022/05/11 10:59:49 网络:tcp --- 通过:testmethod_1(0.00s) === 运行测试方法_2 2022/05/11 10:59:49 服务器运行中 2022/05/11 10:59:49 网络:tcp --- 通过:testmethod_2(0.00s) === 运行测试方法_3 2022/05/11 10:59:49 服务器运行中 2022/05/11 10:59:49 网络:tcp --- 通过:testmethod_3(0.00s) 经过 好的 lsfrpc/src/server 0.008s

运行时

去测试-v-count 1 ./src/server/... 去测试-v-count 1 ./src/server/...

一切正常(上面的输出,两次)

但是,运行时:

去测试-v-count 2 ./src/server/...

第二次运行开始时出现错误:

=== 运行测试方法_1 2022/05/11 10:59:52 服务器运行 2022/05/11 10:59:52 网络:tcp --- 通过:testmethod_1(0.00s) === 运行测试方法_2 2022/05/11 10:59:52 服务器运行 2022/05/11 10:59:52 网络:tcp --- 通过:testmethod_2(0.00s) === 运行测试方法_3 2022/05/11 10:59:52 服务器运行 2022/05/11 10:59:52 网络:tcp --- 通过:testmethod_3(0.00s) === 运行测试方法_1 --- 失败:testmethod_1(0.00s) 恐慌:http:/gorpc 的多个注册 [已恢复] 恐慌:http:/gorpc 的多个注册 goroutine 63 [运行]: 测试.trunner.func1.2({0x7b9f20, 0xc0002927f0}) /home/sivsha01/go/src/testing/testing.go:1389 +0x24e 测试.trunner.func1() /home/sivsha01/go/src/testing/testing.go:1392 +0x39f 恐慌({0x7b9f20,0xc0002927f0}) /home/sivsha01/go/src/runtime/panic.go:838 +0x207 net/http.(*servemux).handle(0xb2e160, {0x83449c, 0x8}, {0x8dc3c0?, 0xc000198000})

与我上面描述的相同。对我来说,这似乎是一种错误的行为。


正确答案


重现该问题的简化版本:

package rpcserver

import (
    "net/http"
    "os"
    "testing"
)

func testregister(t *testing.t) {
    t.logf("pid: %d", os.getpid())

    register()
}

func register() {
    http.handlefunc("/", func(w http.responsewriter, r *http.request) {})
}

当您使用 go test -count 2 -v 运行测试时,您会发现这 2 个测试在同一进程中运行。正如您的评论中所述:registerrpcmethods() 每个进程应该只调用一次

您可以使用 sync.once 来确保它只被调用一次:

package rpcserver

import (
    "net/http"
    "os"
    "sync"
    "testing"
)

func TestRegister(t *testing.T) {
    t.Logf("pid: %d", os.Getpid())

    register()
}

var registerOnce sync.Once

func register() {
    registerOnce.Do(func() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})
    })
}

此外,您的测试将不再依赖于测试的执行顺序。并且所有测试都可以单独运行。

到这里,我们也就讲完了《当使用“count”标志多次运行测试时,net/rpc 服务器保持注册状态》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>