2025-01-02 21:42:04 +09:00
|
|
|
//go:build js
|
|
|
|
|
|
|
|
package nostr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2025-01-03 01:15:12 -03:00
|
|
|
var testRelayURL = func() string {
|
2025-01-02 21:42:04 +09:00
|
|
|
url := os.Getenv("TEST_RELAY_URL")
|
2025-01-03 01:15:12 -03:00
|
|
|
if url != "" {
|
|
|
|
return url
|
2025-01-02 21:42:04 +09:00
|
|
|
}
|
2025-01-03 01:15:12 -03:00
|
|
|
return "wss://nos.lol"
|
|
|
|
}()
|
2025-01-02 21:42:04 +09:00
|
|
|
|
2025-01-03 01:15:12 -03:00
|
|
|
func TestConnectContext(t *testing.T) {
|
2025-01-02 21:42:04 +09:00
|
|
|
// relay client
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
|
|
defer cancel()
|
2025-01-03 01:15:12 -03:00
|
|
|
r, err := RelayConnect(ctx, testRelayURL)
|
2025-01-02 21:42:04 +09:00
|
|
|
assert.NoError(t, err)
|
|
|
|
|
|
|
|
defer r.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestConnectContextCanceled(t *testing.T) {
|
|
|
|
// relay client
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
cancel() // make ctx expired
|
2025-01-03 01:15:12 -03:00
|
|
|
_, err := RelayConnect(ctx, testRelayURL)
|
2025-01-02 21:42:04 +09:00
|
|
|
assert.ErrorIs(t, err, context.Canceled)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestPublish(t *testing.T) {
|
|
|
|
// test note to be sent over websocket
|
|
|
|
priv, pub := makeKeyPair(t)
|
|
|
|
textNote := Event{
|
|
|
|
Kind: KindTextNote,
|
|
|
|
Content: "hello",
|
|
|
|
CreatedAt: Timestamp(1672068534), // random fixed timestamp
|
|
|
|
Tags: Tags{[]string{"foo", "bar"}},
|
|
|
|
PubKey: pub,
|
|
|
|
}
|
|
|
|
err := textNote.Sign(priv)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
|
|
|
|
// connect a client and send the text note
|
2025-01-03 01:15:12 -03:00
|
|
|
rl := mustRelayConnect(t, testRelayURL)
|
2025-01-02 21:42:04 +09:00
|
|
|
err = rl.Publish(context.Background(), textNote)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeKeyPair(t *testing.T) (priv, pub string) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
privkey := GeneratePrivateKey()
|
|
|
|
pubkey, err := GetPublicKey(privkey)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
|
|
|
|
return privkey, pubkey
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustRelayConnect(t *testing.T, url string) *Relay {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
rl, err := RelayConnect(context.Background(), url)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
return rl
|
|
|
|
}
|