github.com/go-spring/spring-base@v1.1.3/log/plugin_writer_test.go (about)

     1  /*
     2   * Copyright 2012-2019 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package log_test
    18  
    19  import (
    20  	"context"
    21  	"io/ioutil"
    22  	"sync"
    23  	"testing"
    24  
    25  	"github.com/go-spring/spring-base/assert"
    26  	"github.com/go-spring/spring-base/log"
    27  	"github.com/go-spring/spring-base/util"
    28  )
    29  
    30  func TestWriters(t *testing.T) {
    31  
    32  	var fileName string
    33  	{
    34  		file, err := ioutil.TempFile("", "")
    35  		if err != nil {
    36  			t.Fatal(err)
    37  		}
    38  		if err = file.Close(); err != nil {
    39  			t.Fatal(err)
    40  		}
    41  		fileName = file.Name()
    42  	}
    43  
    44  	var wg sync.WaitGroup
    45  	wg.Add(2)
    46  	for i := 0; i < 2; i++ {
    47  		go func() {
    48  			defer wg.Done()
    49  			_, err := log.Writers.Get(fileName, func() (log.Writer, error) {
    50  				return log.NewFileWriter(fileName)
    51  			})
    52  			util.Panic(err).When(err != nil)
    53  		}()
    54  	}
    55  	wg.Wait()
    56  
    57  	w, err := log.Writers.Get(fileName, nil)
    58  	assert.Nil(t, err)
    59  	assert.NotNil(t, w)
    60  
    61  	ctx := context.Background()
    62  	log.Writers.Release(ctx, w)
    63  	assert.True(t, log.Writers.Has(fileName))
    64  	log.Writers.Release(ctx, w)
    65  	assert.True(t, log.Writers.Has(fileName))
    66  	log.Writers.Release(ctx, w)
    67  	assert.False(t, log.Writers.Has(fileName))
    68  }