example_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package lapitest
  4. import (
  5. "context"
  6. "testing"
  7. "tailscale.com/ipn"
  8. )
  9. func TestClientServer(t *testing.T) {
  10. t.Parallel()
  11. ctx := context.Background()
  12. // Create a server and two clients.
  13. // Both clients represent the same user to make this work across platforms.
  14. // On Windows we've been restricting the API usage to a single user at a time.
  15. // While we're planning on changing this once a better permission model is in place,
  16. // this test is currently limited to a single user (but more than one client is fine).
  17. // Alternatively, we could override GOOS via envknobs to test as if we're
  18. // on a different platform, but that would make the test depend on global state, etc.
  19. s := NewServer(t, WithLogging(false))
  20. c1 := s.ClientWithName("User-A")
  21. c2 := s.ClientWithName("User-A")
  22. // Start watching the IPN bus as the second client.
  23. w2, _ := c2.WatchIPNBus(context.Background(), ipn.NotifyInitialPrefs)
  24. // We're supposed to get a notification about the initial prefs,
  25. // and WantRunning should be false.
  26. n, err := w2.Next()
  27. for ; err == nil; n, err = w2.Next() {
  28. if n.Prefs == nil {
  29. // Ignore non-prefs notifications.
  30. continue
  31. }
  32. if n.Prefs.WantRunning() {
  33. t.Errorf("WantRunning(initial): got %v, want false", n.Prefs.WantRunning())
  34. }
  35. break
  36. }
  37. if err != nil {
  38. t.Fatalf("IPNBusWatcher.Next failed: %v", err)
  39. }
  40. // Now send an EditPrefs request from the first client to set WantRunning to true.
  41. change := &ipn.MaskedPrefs{Prefs: ipn.Prefs{WantRunning: true}, WantRunningSet: true}
  42. gotPrefs, err := c1.EditPrefs(ctx, change)
  43. if err != nil {
  44. t.Fatalf("EditPrefs failed: %v", err)
  45. }
  46. if !gotPrefs.WantRunning {
  47. t.Fatalf("EditPrefs.WantRunning: got %v, want true", gotPrefs.WantRunning)
  48. }
  49. // We can check the backend directly to see if the prefs were set correctly.
  50. if gotWantRunning := s.Backend().Prefs().WantRunning(); !gotWantRunning {
  51. t.Fatalf("Backend.Prefs.WantRunning: got %v, want true", gotWantRunning)
  52. }
  53. // And can also wait for the second client with an IPN bus watcher to receive the notification
  54. // about the prefs change.
  55. n, err = w2.Next()
  56. for ; err == nil; n, err = w2.Next() {
  57. if n.Prefs == nil {
  58. // Ignore non-prefs notifications.
  59. continue
  60. }
  61. if !n.Prefs.WantRunning() {
  62. t.Fatalf("WantRunning(changed): got %v, want true", n.Prefs.WantRunning())
  63. }
  64. break
  65. }
  66. if err != nil {
  67. t.Fatalf("IPNBusWatcher.Next failed: %v", err)
  68. }
  69. }