2024-02-04 16:29:09 +03:00
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2024-02-24 00:51:46 +03:00
package optional_test
2024-02-04 16:29:09 +03:00
import (
"testing"
2024-02-24 00:51:46 +03:00
"code.gitea.io/gitea/modules/optional"
2024-02-04 16:29:09 +03:00
"github.com/stretchr/testify/assert"
)
func TestOption ( t * testing . T ) {
2024-02-24 00:51:46 +03:00
var uninitialized optional . Option [ int ]
2024-02-04 16:29:09 +03:00
assert . False ( t , uninitialized . Has ( ) )
assert . Equal ( t , int ( 0 ) , uninitialized . Value ( ) )
assert . Equal ( t , int ( 1 ) , uninitialized . ValueOrDefault ( 1 ) )
2024-02-24 00:51:46 +03:00
none := optional . None [ int ] ( )
2024-02-04 16:29:09 +03:00
assert . False ( t , none . Has ( ) )
assert . Equal ( t , int ( 0 ) , none . Value ( ) )
assert . Equal ( t , int ( 1 ) , none . ValueOrDefault ( 1 ) )
2024-04-29 11:47:56 +03:00
some := optional . Some ( 1 )
2024-02-04 16:29:09 +03:00
assert . True ( t , some . Has ( ) )
assert . Equal ( t , int ( 1 ) , some . Value ( ) )
assert . Equal ( t , int ( 1 ) , some . ValueOrDefault ( 2 ) )
2024-02-29 21:52:49 +03:00
noneBool := optional . None [ bool ] ( )
assert . False ( t , noneBool . Has ( ) )
assert . False ( t , noneBool . Value ( ) )
assert . True ( t , noneBool . ValueOrDefault ( true ) )
someBool := optional . Some ( true )
assert . True ( t , someBool . Has ( ) )
assert . True ( t , someBool . Value ( ) )
assert . True ( t , someBool . ValueOrDefault ( false ) )
2024-02-04 16:29:09 +03:00
var ptr * int
2024-02-24 00:51:46 +03:00
assert . False ( t , optional . FromPtr ( ptr ) . Has ( ) )
2024-02-04 16:29:09 +03:00
2024-02-23 05:18:33 +03:00
int1 := 1
2024-02-24 00:51:46 +03:00
opt1 := optional . FromPtr ( & int1 )
2024-02-04 16:29:09 +03:00
assert . True ( t , opt1 . Has ( ) )
assert . Equal ( t , int ( 1 ) , opt1 . Value ( ) )
2024-02-24 00:51:46 +03:00
assert . False ( t , optional . FromNonDefault ( "" ) . Has ( ) )
2024-02-04 16:29:09 +03:00
2024-02-24 00:51:46 +03:00
opt2 := optional . FromNonDefault ( "test" )
2024-02-04 16:29:09 +03:00
assert . True ( t , opt2 . Has ( ) )
assert . Equal ( t , "test" , opt2 . Value ( ) )
2024-02-24 00:51:46 +03:00
assert . False ( t , optional . FromNonDefault ( 0 ) . Has ( ) )
2024-02-04 16:29:09 +03:00
2024-02-24 00:51:46 +03:00
opt3 := optional . FromNonDefault ( 1 )
2024-02-04 16:29:09 +03:00
assert . True ( t , opt3 . Has ( ) )
assert . Equal ( t , int ( 1 ) , opt3 . Value ( ) )
}