dart - HttpClientRequest在添加数据时失败

时间:2013-09-13 01:18:35

标签: dart

我正在尝试创建一些简单的单元测试,这是代码:

import 'dart:io';

import 'package:unittest/unittest.dart';

void main() {
  test('check if sent data equals expected data', () {

    HttpServer.bind('127.0.0.1', 8080)
      .then(expectAsync1((HttpServer server) {
        server.listen((HttpRequest request) {
          expect(request.runtimeType.toString(), equals('_HttpRequest'));
          request.fold(new BytesBuilder(), (prev, next) {
            prev.addAll(next);
            return prev;
          })
          .then(expectAsync1((BytesBuilder bb) {
            var bytes = bb.takeBytes(),
                helloString = new String.fromCharCodes(bytes);
            expect(helloString, equals('hello'));
            request.response.write(helloString);
            request.response.close();
            server.close();
          }));
        });
      }));

    HttpClient client = new HttpClient();
    client.get('127.0.0.1', 8080, '/')
      .then((HttpClientRequest request) {
        request.add('hello'.codeUnits);
        return request.close();
      });

  });
}

给我一​​个错误:打破异常:'dart:async / stream_impl.dart':断言失败:第149行pos 12:'! _isClosed'不是真的。

经过一些解决方法后,我发现负责的是request.add('hello'.codeUnits)

所以现在我无法将数据添加到HttpClientRequest。任何解决方法?

1 个答案:

答案 0 :(得分:2)

您使用的是什么版本的Dart?我无法重现你得到的错误。有关此问题的进展,请参阅http://dartbug.com/13293

但是代码存在许多问题:

  1. BytesBuilder没有addAll方法
  2. 使用client.get时,请求的内容长度设置为0
  3. 似乎客户端可能在服务器绑定之前连接。
  4. 如下所示重写测试使其运行:

    import 'dart:io';
    import 'package:unittest/unittest.dart';
    
    void main() {
      test('check if sent data equals expected data', () {
        expect(HttpServer.bind('127.0.0.1', 8081).then((HttpServer server) {
          HttpClient client = new HttpClient();
          server.listen((HttpRequest request) {
            expect(request.runtimeType.toString(), equals('_HttpRequest'));
            request.fold(new BytesBuilder(), (prev, next) {
              prev.add(next);
              return prev;
            }).then((BytesBuilder bb) {
              var bytes = bb.takeBytes();
              var helloString = new String.fromCharCodes(bytes);
              expect(helloString, equals('hello'));
              request.response.write(helloString);
              request.response.close();
              server.close();
            });
          });
    
          return client.post('127.0.0.1', 8081, '/').then((HttpClientRequest request) {
            request.add('hello'.codeUnits);
            return request.close().then((HttpClientRequest response) {
              return response.statusCode;
            });
          }).whenComplete(client.close());
        }), completion(equals(HttpStatus.OK)));
      });
    }