...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/ocsp/ocsp_test.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/ocsp

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  //go:build go1.13
     8  // +build go1.13
     9  
    10  package ocsp
    11  
    12  import (
    13  	"context"
    14  	"crypto/x509"
    15  	"net"
    16  	"testing"
    17  	"time"
    18  
    19  	"go.mongodb.org/mongo-driver/internal/assert"
    20  	"go.mongodb.org/mongo-driver/internal/httputil"
    21  )
    22  
    23  func TestContactResponders(t *testing.T) {
    24  	t.Run("context cancellation is honored", func(t *testing.T) {
    25  		t.Parallel()
    26  
    27  		ctx, cancel := context.WithCancel(context.Background())
    28  		cancel()
    29  
    30  		serverCert := &x509.Certificate{
    31  			OCSPServer: []string{"https://localhost:5000"},
    32  		}
    33  		cfg := config{
    34  			serverCert: serverCert,
    35  			issuer:     &x509.Certificate{},
    36  			cache:      NewCache(),
    37  			httpClient: httputil.DefaultHTTPClient,
    38  		}
    39  
    40  		res := contactResponders(ctx, cfg)
    41  		assert.Nil(t, res, "expected nil response details, but got %v", res)
    42  	})
    43  	t.Run("context timeout is honored", func(t *testing.T) {
    44  		t.Parallel()
    45  
    46  		ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    47  		defer cancel()
    48  
    49  		// Create a TCP listener on a random port that doesn't accept any connections, causing
    50  		// connection attempts to hang indefinitely from the client's perspective.
    51  		l, err := net.Listen("tcp", "localhost:0")
    52  		assert.Nil(t, err, "tls.Listen() error: %v", err)
    53  		defer l.Close()
    54  
    55  		serverCert := &x509.Certificate{
    56  			OCSPServer: []string{"https://" + l.Addr().String()},
    57  		}
    58  		cfg := config{
    59  			serverCert: serverCert,
    60  			issuer:     &x509.Certificate{},
    61  			cache:      NewCache(),
    62  			httpClient: httputil.DefaultHTTPClient,
    63  		}
    64  
    65  		// Expect that contactResponders() returns a nil response but does not cause any errors when
    66  		// the passed-in context times out.
    67  		start := time.Now()
    68  		res := contactResponders(ctx, cfg)
    69  		duration := time.Since(start)
    70  		assert.Nil(t, res, "expected nil response, but got: %v", res)
    71  		assert.True(t, duration <= 5*time.Second, "expected duration to be <= 5s, but was %v", duration)
    72  	})
    73  }
    74  

View as plain text