unit UTestRegions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DOM, XMLRead, XMLWrite, fpcunit, testregistry, URegions; type TTestRegions = class(TTestCase) private function RegionsToXML(AList: TRegionList): string; function ListFromXML(const AXML: string): TRegionList; published procedure CreateAndFind; procedure SerializeDeserializeRoundtrip; procedure FindMissingReturnsNil; end; implementation function TTestRegions.RegionsToXML(AList: TRegionList): string; var doc: TXMLDocument; root: TDOMElement; stream: TStringStream; begin doc := TXMLDocument.Create; try root := doc.CreateElement('regions'); doc.AppendChild(root); AList.Serialize(root); stream := TStringStream.Create(''); try WriteXMLFile(doc, stream); Result := stream.DataString; finally stream.Free; end; finally doc.Free; end; end; function TTestRegions.ListFromXML(const AXML: string): TRegionList; var doc: TXMLDocument; stream: TStringStream; begin stream := TStringStream.Create(AXML); try ReadXMLFile(doc, stream); try Result := TRegionList.Deserialize(nil, doc.DocumentElement); finally doc.Free; end; finally stream.Free; end; end; procedure TTestRegions.CreateAndFind; var list: TRegionList; region: TRegion; begin list := TRegionList.Create(nil); try region := TRegion.Create(list, 'britain'); list.Add(region); region.Areas.Add(1, 2, 3, 4); AssertEquals('count', 1, list.Count); AssertSame('find by name', region, list.Find('britain')); AssertEquals('index by name', 0, list.IndexOf('britain')); finally list.Free; end; end; procedure TTestRegions.SerializeDeserializeRoundtrip; var list: TRegionList; region: TRegion; xml: string; loaded: TRegionList; found: TRegion; begin list := TRegionList.Create(nil); try region := TRegion.Create(list, 'yew'); list.Add(region); region.Areas.Add(10, 20, 30, 40); region.Areas.Add(50, 60, 70, 80); xml := RegionsToXML(list); loaded := ListFromXML(xml); try AssertEquals('region count survives', 1, loaded.Count); found := loaded.Find('yew'); AssertTrue('region found', found <> nil); AssertEquals('area count survives', 2, found.Areas.Count); AssertEquals('area 0 left', 10, found.Areas.Rects[0].Left); AssertEquals('area 0 top', 20, found.Areas.Rects[0].Top); AssertEquals('area 0 right', 30, found.Areas.Rects[0].Right); AssertEquals('area 0 bottom', 40, found.Areas.Rects[0].Bottom); AssertEquals('area 1 left', 50, found.Areas.Rects[1].Left); finally loaded.Free; end; finally list.Free; end; end; procedure TTestRegions.FindMissingReturnsNil; var list: TRegionList; begin list := TRegionList.Create(nil); try AssertTrue('missing region is nil', list.Find('nowhere') = nil); finally list.Free; end; end; initialization RegisterTests([TTestRegions]); end.