aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/skylarkdebug/server/DebugServerTransportTest.java
blob: fedf56f6907a21db869ab63379f4bb7af2eefa9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.skylarkdebug.server;

import static com.google.common.truth.Truth.assertThat;

import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.skylarkdebugging.SkylarkDebuggingProtos.ContinueExecutionResponse;
import com.google.devtools.build.lib.skylarkdebugging.SkylarkDebuggingProtos.DebugEvent;
import com.google.devtools.build.lib.skylarkdebugging.SkylarkDebuggingProtos.DebugRequest;
import com.google.devtools.build.lib.skylarkdebugging.SkylarkDebuggingProtos.StartDebuggingRequest;
import com.google.devtools.build.lib.syntax.Environment.FailFastException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.Duration;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link DebugServerTransport}. */
@RunWith(JUnit4.class)
public class DebugServerTransportTest {

  private static final ExecutorService executor = Executors.newFixedThreadPool(1);

  private final EventCollectionApparatus events =
      new EventCollectionApparatus(EventKind.ALL_EVENTS);

  /** A simple debug client for testing purposes. */
  private static class MockDebugClient {

    Socket clientSocket;

    void connect(Duration timeout, ServerSocket serverSocket) {
      long startTimeMillis = System.currentTimeMillis();
      IOException exception = null;
      while (System.currentTimeMillis() - startTimeMillis < timeout.toMillis()) {
        try {
          clientSocket = new Socket();
          clientSocket.connect(
              new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort()),
              100);
          return;
        } catch (IOException e) {
          exception = e;
        }
      }
      throw new RuntimeException("Couldn't connect to the debug server", exception);
    }

    List<DebugEvent> readEvents() throws Exception {
      List<DebugEvent> events = new ArrayList<>();
      while (clientSocket.getInputStream().available() != 0) {
        events.add(DebugEvent.parseDelimitedFrom(clientSocket.getInputStream()));
      }
      return events;
    }

    void sendRequest(DebugRequest request) throws IOException {
      request.writeDelimitedTo(clientSocket.getOutputStream());
    }
  }

  @Before
  public void setupEventHandler() {
    // fail-fast treats 'debug' messages as errors. Replace with something that doesn't
    events.setFailFast(false);

    EnumSet<EventKind> failOnEvents = EnumSet.copyOf(EventKind.ERRORS_AND_WARNINGS);
    failOnEvents.remove(EventKind.DEBUG);

    events
        .reporter()
        .addHandler(
            event -> {
              if (failOnEvents.contains(event.getKind())) {
                throw new FailFastException(event.toString());
              }
            });
  }

  @Test
  public void testConnectAndReceiveRequest() throws Exception {
    ServerSocket serverSocket = new ServerSocket(0, 1, InetAddress.getByName(null));
    Future<DebugServerTransport> future =
        executor.submit(
            () -> DebugServerTransport.createAndWaitForClient(events.reporter(), serverSocket));
    MockDebugClient client = new MockDebugClient();
    client.connect(Duration.ofSeconds(10), serverSocket);

    DebugServerTransport serverTransport = future.get(10, TimeUnit.SECONDS);
    assertThat(serverTransport).isNotNull();
    DebugRequest request =
        DebugRequest.newBuilder()
            .setSequenceNumber(10)
            .setStartDebugging(StartDebuggingRequest.getDefaultInstance())
            .build();
    client.sendRequest(request);

    assertThat(serverTransport.readClientRequest()).isEqualTo(request);
    serverTransport.close();
  }

  @Test
  public void testConnectAndPostEvent() throws Exception {
    ServerSocket serverSocket = new ServerSocket(0, 1, InetAddress.getByName(null));
    Future<DebugServerTransport> future =
        executor.submit(
            () -> DebugServerTransport.createAndWaitForClient(events.reporter(), serverSocket));
    MockDebugClient client = new MockDebugClient();
    client.connect(Duration.ofSeconds(10), serverSocket);

    DebugServerTransport serverTransport = future.get(10, TimeUnit.SECONDS);
    assertThat(serverTransport).isNotNull();
    DebugEvent event =
        DebugEvent.newBuilder()
            .setSequenceNumber(10)
            .setContinueExecution(ContinueExecutionResponse.getDefaultInstance())
            .build();
    serverTransport.postEvent(event);

    assertThat(client.readEvents()).containsExactly(event);
    serverTransport.close();
  }
}