简体   繁体   English

测试包含锁定的功能时,Go应用程序挂起

[英]Go app hangs when testing a function that contains a lock

This is a function I wrote that adds a request to a request queue: 这是我编写的将请求添加到请求队列的函数:

func (self *RequestQueue) addRequest(request *Request) {

    self.requestLock.Lock()
    self.queue[request.NormalizedUrl()] = request.ResponseChannel
    self.requestLock.Unlock()
}

and this is one of its tests: 这是它的测试之一:

func TestAddRequest(t *testing.T) {

    before := len(rq.queue)

    r := SampleRequests(1)[0]
    rq.addRequest(&r)

    if (len(rq.queue) - 1) != before {
        t.Errorf("Failed to add request to queue")
    }
}

When I run this test, the application hangs. 当我运行此测试时,应用程序挂起。 If I comment out this test, everything works fine. 如果我注释掉此测试,一切正常。 I think the problem is the locking inside the function. 我认为问题在于函数内部的锁定。 Is there something that I'm doing wrong? 我做错什么了吗? Thanks for your help! 谢谢你的帮助!

The problem was an infinite loop in the SampleRequests() function: 问题是SampleRequests()函数中的无限循环:

func SampleRequests(num int) []Request {

    requests := make([]Request, num, num+10)
    for i := 0; i < len(requests); i++ {
        r := NewRequest("GET", "http://api.openweathermap.org/data/2.5/weather", nil)
        r.Params.Set("lat", "35")
        r.Params.Add("lon", "139")
        r.Params.Add("units", "metric")

        requests = append(requests, r)
    }

    return requests
}

I was checking if i was less than the length of the array in the continuation condition of the for loop. 我被检查,如果i小于在for循环继续条件阵列的长度。 With each iteration, an item was added to the array, the length increased and the for loop continued executing. 每次迭代都将一个项目添加到数组中,长度增加,并且for循环继续执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM