iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Go语言context test源码分析详情
  • 561
分享到

Go语言context test源码分析详情

2024-04-02 19:04:59 561人浏览 泡泡鱼
摘要

目录1.测试例子分析2.单元测试1.测试例子分析 example_test.go,展示了With-系列的4个例子 func ExampleWithCancel() {   gen :

1.测试例子分析

example_test.go,展示了With-系列的4个例子

func ExampleWithCancel() {
  gen := func(ctx context.Context) <-chan int {
    dst := make(chan int)
    n := 1
    Go func() {
      for {
        select {
        case <-ctx.Done():
          return // returning not to leak the goroutine
        case dst <- n:
          n++
        }
      }
    }()
    return dst
  }

  ctx, cancel := context.WithCancel(context.Background())
  defer cancel() // cancel when we are finished consuming integers

  for n := range gen(ctx) {
    fmt.Println(n)
    if n == 5 {
      break
    }
  }
  // Output:
  // 1
  // 2
  // 3
  // 4
  // 5
}

结构分析,gen是一个函数,返回值是一个信道, for range channel是有特殊意义的, for会循环从channel读数据,直到channel被close(),不然就是无限循环.

gen内部的协程就是典型的闭包,for range会不断触发读,gen内部的for select 会不断触发写,主协程读5次之后,会结束main函数,会触发defer函数, 也就是取消操作对应的回调,此时done信道会被close,gen内部的协程会正常退出.

这个例子是测试支持取消信号的上下文,取消函数的调用放在了maindefer函数中.

const shortDuration = 1 * time.Millisecond
func ExampleWithDeadline() {
  d := time.Now().Add(shortDuration)
  ctx, cancel := context.WithDeadline(context.Background(), d)

  // Even though ctx will be expired, it is good practice to call its
  // cancellation function in any case. Failure to do so may keep the
  // context and its parent alive longer than necessary.
  defer cancel()

  select {
  case <-time.After(1 * time.Second):
    fmt.Println("overslept")
  case <-ctx.Done():
    fmt.Println(ctx.Err())
  }

  // Output:
  // context deadline exceeded
}

deadline的这个例子,在maindefer中也有主动调用取消函数的. 实际上通过打印可以显示deadline是否按预期工作.

func ExampleWithTimeout() {
  ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
  defer cancel()

  select {
  case <-time.After(1 * time.Second):
    fmt.Println("overslept")
  case <-ctx.Done():
    fmt.Println(ctx.Err()) // prints "context deadline exceeded"
  }

  // Output:
  // context deadline exceeded
}

timeout只是deadline的一种简写.

func ExampleWithValue() {
  type favContexTKEy string

  f := func(ctx context.Context, k favContextKey) {
    if v := ctx.Value(k); v != nil {
      fmt.Println("found value:", v)
      return
    }
    fmt.Println("key not found:", k)
  }

  k := favContextKey("language")
  ctx := context.WithValue(context.Background(), k, "Go")

  f(ctx, k)
  f(ctx, favContextKey("color"))

  // Output:
  // found value: Go
  // key not found: color
}

context.WithValueContext.Value()是存取操作, 取的时候,如果key没找到,会返回nil.

2.单元测试

context_text.go,x_test.go是单元测试, example_test.go是示例,benchmark_test.go是基准测试, net_test.go展示了deadline对net包的支持.

先看单元测试的context_text.go.

type testingT interface {}

type otherContext struct {}
func quiescent(t testingT) time.Duration {}
func XTestBackground(t testingT) {}
func XTestTODO(t testingT) {}
func XTestWithCancel(t testingT) {}
func contains(m map[canceler]struct{}, key canceler) bool {}
func XTestParentFinishesChild(t testingT) {}
func XTestChildFinishesFirst(t testingT) {}
func testDeadline(c Context, name string, t testingT) {}
func XTestDeadline(t testingT) {}
func XTestTimeout(t testingT) {}
func XTestCanceledTimeout(t testingT) {}
func XTestValues(t testingT) {}
func XTestAllocs(t testingT, testingShort func() bool, testingAllocsPerRun func(int, func()) float64) {}
func XTestSimultaneousCancels(t testingT) {}
func XTestInterlockedCancels(t testingT) {}
func XTestLayersCancel(t testingT) {}
func XTestLayersTimeout(t testingT) {}
func XTestCancelRemoves(t testingT) {}
func XTestWithCancelCanceledParent(t testingT) {}
func XTestWithValueChecksKey(t testingT) {}
func XTestInvalidDerivedFail(t testingT) {}
func recoveredValue(fn func()) (v interface{}) {}
func XTestDeadlineExceededSupportsTimeout(t testingT) {}
type myCtx struct {}
type myDoneCtx struct {}
func (d *myDoneCtx) Done() <-chan struct{} {}
func XTestCustomContextGoroutines(t testingT) {}

这暴露的大多测试函数的参数类型是testingT接口类型,但这个源文件中没有实现testingT接口的,

func TestBackground(t *testing.T)                      { XTestBackground(t) }
func TestTODO(t *testing.T)                            { XTestTODO(t) }
func TestWithCancel(t *testing.T)                      { XTestWithCancel(t) }
func TestParentFinishesChild(t *testing.T)             { XTestParentFinishesChild(t) }
func TestChildFinishesFirst(t *testing.T)              { XTestChildFinishesFirst(t) }
func TestDeadline(t *testing.T)                        { XTestDeadline(t) }
func TestTimeout(t *testing.T)                         { XTestTimeout(t) }
func TestCanceledTimeout(t *testing.T)                 { XTestCanceledTimeout(t) }
func TestValues(t *testing.T)                          { XTestValues(t) }
func TestAllocs(t *testing.T)                          { XTestAllocs(t, testing.Short, testing.AllocsPerRun) }
func TestSimultaneousCancels(t *testing.T)             { XTestSimultaneousCancels(t) }
func TestInterlockedCancels(t *testing.T)              { XTestInterlockedCancels(t) }
func TestLayersCancel(t *testing.T)                    { XTestLayersCancel(t) }
func TestLayersTimeout(t *testing.T)                   { XTestLayersTimeout(t) }
func TestCancelRemoves(t *testing.T)                   { XTestCancelRemoves(t) }
func TestWithCancelCanceledParent(t *testing.T)        { XTestWithCancelCanceledParent(t) }
func TestWithValueChecksKey(t *testing.T)              { XTestWithValueChecksKey(t) }
func TestInvalidDerivedFail(t *testing.T)              { XTestInvalidDerivedFail(t) }
func TestDeadlineExceededSupportsTimeout(t *testing.T) { XTestDeadlineExceededSupportsTimeout(t) }
func TestCustomContextGoroutines(t *testing.T)         { XTestCustomContextGoroutines(t) }

这是x_test.go的内容,直接是用testing.T类型来实现testingT接口.

那先分析一下testing.T对testingT接口的实现.

type T struct {
  common
  isParallel bool
  context    *testContext
}
func (t *T) Deadline() (deadline time.Time, ok bool) {
  deadline = t.context.deadline
  return deadline, !deadline.IsZero()
}

注意:testing.T.context不是context.Context的实现类型, Deadline()返回了t.context中存储的deadline信息.

testing.T内嵌了testing.common,大部分方法集都来至common:

Error(args ...interface{})
Errorf(fORMat string, args ...interface{})
Fail()
FailNow()
Failed() bool
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
Helper()
Log(args ...interface{})
Logf(format string, args ...interface{})
Name() string
Skip(args ...interface{})
SkipNow()
Skipf(format string, args ...interface{})
Skipped() bool

Parallel()是由testing.T实现,某个测试用例多次重复执行时, 可启用并发参数.

到此这篇关于Go语言context test源码分析详情的文章就介绍到这了,更多相关Go语言context test源码分析内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: Go语言context test源码分析详情

本文链接: https://www.lsjlt.com/news/138491.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Go语言context test源码分析详情
    目录1.测试例子分析2.单元测试1.测试例子分析 example_test.go,展示了With-系列的4个例子 func ExampleWithCancel() {   gen :...
    99+
    2024-04-02
  • Go语言io pipe源码分析详情
    目录1.结构分析2.pipe sruct分析3.PipeReader对外暴露的是读/关闭4.写法5.总结pipe.go分析: 这个文件使用到了errors包,也是用到了sync库.文...
    99+
    2024-04-02
  • 对Go语言中的context包源码分析
    目录一、包说明分析二、包结构分析三、Context接口类型分析四、后续分析规划五、基于实现类型到常用函数六、With-系列函数七、扩展功能以及如何扩展八、补充一、包说明分析 cont...
    99+
    2024-04-02
  • Go语言进阶freecache源码分析
    这篇文章主要介绍“Go语言进阶freecache源码分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Go语言进阶freecache源码分析”文章能帮助大家解决问题。00. 什么是 freecach...
    99+
    2023-07-06
  • go语言构建顺序源码分析
    这篇文章主要介绍“go语言构建顺序源码分析”,在日常操作中,相信很多人在go语言构建顺序源码分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”go语言构建顺序源码分析”的疑惑有所帮助!接下来,请跟着小编一起来...
    99+
    2023-07-05
  • Go中Context使用源码解析
    目录前言1、Context定义2、Context的派生2.1、创建Context对象2.2、parent Context3、context 接口四种实现4、 emptyCtx 源码分...
    99+
    2023-05-16
    Go Context源码解析 Go Context
  • Go语言读写锁RWMutex的源码分析
    目录前言RWMutex 总览深入源码数据结构RLock()RUnlock()Lock()Unlock()常见问题实战一下前言 在前面两篇文章中 初见 Go Mutex&nb...
    99+
    2024-04-02
  • Go语言网络编程与Http源码分析
    这篇文章主要介绍“Go语言网络编程与Http源码分析”,在日常操作中,相信很多人在Go语言网络编程与Http源码分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Go语言网络编程与Http源码分析”的疑惑有所...
    99+
    2023-07-05
  • 如何分析Go语言的库源码文件
    这期内容当中小编将会给大家带来有关如何分析Go语言的库源码文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。go适合做什么go是golang...
    99+
    2024-04-02
  • 怎么进行Go语言HTTP Server源码分析
    这期内容当中小编将会给大家带来有关怎么进行Go语言HTTP Server源码分析,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Go语言中HTTP Server:HTTP  server,顾名思义...
    99+
    2023-06-17
  • go语言字符类型byte与rune源码分析
    这篇文章主要介绍“go语言字符类型byte与rune源码分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“go语言字符类型byte与rune源码分析”文章能帮助大家解决问题。一、byte类型介绍by...
    99+
    2023-07-05
  • go语言分布式id生成器及分布式锁源码分析
    本文小编为大家详细介绍“go语言分布式id生成器及分布式锁源码分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“go语言分布式id生成器及分布式锁源码分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。分布式 i...
    99+
    2023-07-05
  • Go语言流程控制详情
    目录1、流程控制2、if 语句3、goto4、for语句5、switch1、流程控制 流程控制在编程语言中是最伟大的发明了,因为有了它,你可以通过很简单的流程描述来表达很复杂的逻辑。...
    99+
    2024-04-02
  • C语言函数调用堆栈详情分析
    目录 一、C函数栈帧开辟以及回退过程二、C函数调用约定和返回值 一、C函数栈帧开辟以及回退过程 __cdecl(C语言默认调用方式,函数参数8字节以内,使用pus...
    99+
    2024-04-02
  • Go语言学习之context包的用法详解
    目录前言需求一需求二Context 接口emptyCtxvalueCtx类型定义WithValuecancelCtx类型定义cancelCtxWithCanceltimerCtx类型...
    99+
    2024-04-02
  • Go语言的变量定义详情
    目录一、变量声明变量二、短声明指针三、new函数四、变量的生命期五、变量的作用域一、变量 声明变量 go定义变量的方式和c,c++,java语法不一样,如下: var 变量名 类型,...
    99+
    2024-04-02
  • Go语言中的通道channel详情
    目录一、Go语言通道基础概念1.channel产生背景2.channel工作方式二、通道使用语法1.通道的声明与初始化2.将数据放入通道内3.从通道内取出数据4.关闭通道close三...
    99+
    2024-04-02
  • react中context传值和生命周期源码分析
    本篇内容主要讲解“react中context传值和生命周期源码分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“react中context传值和生命周期源码分析”吧!假设:项目中存在复杂组件树:...
    99+
    2023-07-05
  • go语言源码是啥写的
    Go语言早期源码是使用C语言和汇编语言写成的,从Go 1.5版本后,完全使用Go语言自身进行编写。Google早在2014年初的时候,就已经开始在筹备从Go语言的源码中彻底移除C语言,也就是说让Go语言真正完成自举,用早期版本重写了Go语言...
    99+
    2023-05-14
    go语言 Golang
  • go语言context包功能及操作使用详解
    目录Context包到底是干嘛用的?context原理什么时候应该使用 Context?如何创建 Context?主协程通知有子协程,子协程又有多个子协程context核心接口emp...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作