From 0bf1ef8af24b96d8e8da0628ed7568dd8a60ac7e Mon Sep 17 00:00:00 2001 From: William Chargin Date: Thu, 7 Jun 2018 09:20:55 -0700 Subject: [PATCH] Add unified address `toString` (#358) Test Plan: Unit tests added. Run `yarn travis`. wchargin-branch: address-tostring --- src/v3/core/address.js | 4 ++-- src/v3/core/address.test.js | 45 +++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/v3/core/address.js b/src/v3/core/address.js index 598f624..25bd7d3 100644 --- a/src/v3/core/address.js +++ b/src/v3/core/address.js @@ -191,8 +191,8 @@ export function makeAddressModule(options: Options): AddressModule { } function toString(address: Address): string { - const _ = address; - throw new Error("toString"); + const parts = toParts(address); + return `${name}${stringify(parts)}`; } function append(address: Address, ...parts: string[]): Address { diff --git a/src/v3/core/address.test.js b/src/v3/core/address.test.js index 25f3dbe..924217b 100644 --- a/src/v3/core/address.test.js +++ b/src/v3/core/address.test.js @@ -216,5 +216,50 @@ describe("core/address", () => { check("on an input with repeated components", ["jar", "jar"]); }); }); + + describe("toString", () => { + const {FooAddress, BarAddress} = makeModules(); + const partsToString = (parts) => + FooAddress.toString(FooAddress.fromParts(parts)); + + // We use this next test as a proxy for fully correct validation, + // in conjunction with tests on `assertValid`. + it("validates address kind", () => { + const bar = BarAddress.fromParts(["hello"]); + expect(() => { + FooAddress.toString(bar); + }).toThrow("expected FooAddress, got BarAddress:"); + }); + + it("includes the address kind", () => { + expect(partsToString(["hello", "world"])).toContain("FooAddress"); + }); + it("includes the address parts", () => { + expect(partsToString(["hello", "world"])).toContain("hello"); + expect(partsToString(["hello", "world"])).toContain("world"); + }); + it("does not include any NUL characters", () => { + expect(partsToString(["hello", "world"])).not.toContain("\0"); + }); + it("works on the empty address", () => { + expect(partsToString([])).toEqual(expect.anything()); + }); + it("differentiates empty components", () => { + // Each of the following should have a different `toString` form. + const inputs = [ + partsToString([]), + partsToString([""]), + partsToString(["", ""]), + partsToString(["hello", "world"]), + partsToString(["", "hello", "world"]), + partsToString(["", "hello", "", "world"]), + partsToString(["", "hello", "", "", "world"]), + partsToString(["", "hello", "", "", "world", ""]), + partsToString(["", "hello", "", "", "world", "", ""]), + partsToString(["", "hello", "", "", "world", "", "", ""]), + ]; + expect(Array.from(new Set(inputs)).sort()).toHaveLength(inputs.length); + }); + }); }); });