github.com/dubbogo/gost@v1.14.0/container/gxsync/semaphore_flaky_test.go (about) 1 /* 2 Copyright 2019 The Vitess 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 http://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 /* 18 * Licensed to the Apache Software Foundation (ASF) under one or more 19 * contributor license agreements. See the NOTICE file distributed with 20 * this work for additional information regarding copyright ownership. 21 * The ASF licenses this file to You under the Apache License, Version 2.0 22 * (the "License"); you may not use this file except in compliance with 23 * the License. You may obtain a copy of the License at 24 * 25 * http://www.apache.org/licenses/LICENSE-2.0 26 * 27 * Unless required by applicable law or agreed to in writing, software 28 * distributed under the License is distributed on an "AS IS" BASIS, 29 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 30 * See the License for the specific language governing permissions and 31 * limitations under the License. 32 */ 33 34 package gxsync 35 36 import ( 37 "testing" 38 "time" 39 ) 40 41 func TestSemaNoTimeout(t *testing.T) { 42 s := NewSemaphore(1, 0) 43 s.Acquire() 44 released := false 45 go func() { 46 time.Sleep(10 * time.Millisecond) 47 released = true 48 s.Release() 49 }() 50 s.Acquire() 51 if !released { 52 t.Errorf("release: false, want true") 53 } 54 } 55 56 func TestSemaTimeout(t *testing.T) { 57 s := NewSemaphore(1, 5*time.Millisecond) 58 s.Acquire() 59 go func() { 60 time.Sleep(10 * time.Millisecond) 61 s.Release() 62 }() 63 if s.Acquire() { 64 t.Errorf("Acquire: true, want false") 65 } 66 time.Sleep(10 * time.Millisecond) 67 if !s.Acquire() { 68 t.Errorf("Acquire: false, want true") 69 } 70 } 71 72 func TestSemaTryAcquire(t *testing.T) { 73 s := NewSemaphore(1, 0) 74 if !s.TryAcquire() { 75 t.Errorf("TryAcquire: false, want true") 76 } 77 if s.TryAcquire() { 78 t.Errorf("TryAcquire: true, want false") 79 } 80 s.Release() 81 if !s.TryAcquire() { 82 t.Errorf("TryAcquire: false, want true") 83 } 84 }