Skip to content

Commit

Permalink
Using objc-helpers instead of inline code for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
gershnik committed Jan 9, 2024
1 parent 83c4c06 commit 2b12536
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 108 deletions.
3 changes: 2 additions & 1 deletion Translit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
44C675C72B03515B003A5BDE /* mappings.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = mappings.xib; sourceTree = "<group>"; };
44C675CA2B03E176003A5BDE /* ru.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = ru.png; sourceTree = "<group>"; };
44C675CC2B040B87003A5BDE /* he.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = he.png; sourceTree = "<group>"; };
44E971362B4D37D50032961E /* objc-helpers-Exports.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "objc-helpers-Exports.xcconfig"; sourceTree = "<group>"; };
6D87255C09E91CF960D5DC68 /* libPods-Translit.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Translit.a"; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */

Expand Down Expand Up @@ -216,6 +217,7 @@
442D258F2B05FB9C00204800 /* Translit.xcconfig */,
442D25922B06016600204800 /* TranslitTests.xcconfig */,
442D25902B05FEFB00204800 /* sys_string-Exports.xcconfig */,
44E971362B4D37D50032961E /* objc-helpers-Exports.xcconfig */,
442D25912B0600BD00204800 /* sys_string.xcconfig */,
442D25A72B06349800204800 /* Installer.xcconfig */,
);
Expand Down Expand Up @@ -791,7 +793,6 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 442D25922B06016600204800 /* TranslitTests.xcconfig */;
buildSettings = {
ONLY_ACTIVE_ARCH = YES;
};
name = Debug;
};
Expand Down
88 changes: 1 addition & 87 deletions Translit/tests/TestCommon.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,93 +6,7 @@

#include "../src/Transliterator.hpp"

#import <XCTest/XCTest.h>

#include <sstream>
#include <cxxabi.h>

namespace TestUtil {
using std::to_string;

template<class T>
concept TestDescriptable = requires(const T & obj) {
{ testDescription(obj) } -> std::same_as<NSString *>;
};


template<class T>
concept ToStringDescriptable = requires(T obj) {
{ to_string(obj) } -> std::same_as<std::string>;
};


template<class T>
concept OStreamDescriptable = requires(T obj, std::ostream & str) {
{ str << obj };
};

inline auto demangle(const char * name) -> std::string {

int status = 0;
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, nullptr, nullptr, &status),
std::free
};
return (status==0) ? res.get() : name ;
}

template<class T>
auto describeForTest(const T & val) {
if constexpr (TestDescriptable<T>) {
return testDescription(val);
}
else if constexpr (ToStringDescriptable<T>) {
using std::to_string;
auto str = to_string(val);
return @(str.c_str());
} else if constexpr (OStreamDescriptable<T>) {
std::ostringstream str;
str << val;
return @(str.str().c_str());
} else {
return [NSString stringWithFormat:@"%s object", demangle(typeid(T).name()).c_str()];
}
}
}

#define XCTPrimitiveAssertCpp(test, op, type, expression1, expressionStr1, expression2, expressionStr2, ...) \
({ \
_XCT_TRY { \
__typeof__(expression1) expressionValue1 = (expression1); \
__typeof__(expression2) expressionValue2 = (expression2); \
if (expressionValue1 != expressionValue2) { \
_XCTRegisterFailure(test, _XCTFailureDescription(_XCTAssertion_Equal, 0, expressionStr1, expressionStr2, TestUtil::describeForTest(expressionValue1), TestUtil::describeForTest(expressionValue2)), __VA_ARGS__); \
} \
} \
_XCT_CATCH (_XCTestCaseInterruptionException *interruption) { [interruption raise]; } \
_XCT_CATCH (...) { \
NSString *_xct_reason = _XCTGetCurrentExceptionReason(); \
_XCTRegisterUnexpectedFailure(test, _XCTFailureDescription((type), 1, expressionStr1, expressionStr2, _xct_reason), __VA_ARGS__); \
} \
})

#define XCTAssertCppEqual(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, !=, _XCTAssertion_Equal, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)

#define XCTAssertCppNotEqual(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, ==, _XCTAssertion_NotEqual, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)

#define XCTAssertCppGreaterThan(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, <=, _XCTAssertion_GreaterThan, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)

#define XCTAssertCppGreaterThanOrEqual(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, <, _XCTAssertion_GreaterThanOrEqual, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)

#define XCTAssertCppLessThan(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, >=, _XCTAssertion_LessThan, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)

#define XCTAssertCppLessThanOrEqual(expression1, expression2, ...) \
XCTPrimitiveAssertCpp(nil, >, _XCTAssertion_LessThanOrEqual, expression1, @#expression1, expression2, @#expression2, __VA_ARGS__)
#include <objc-helpers/XCTestUtil.h>


namespace std {
Expand Down
4 changes: 3 additions & 1 deletion config/TranslitTests.xcconfig
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
// https://help.apple.com/xcode/#/dev745c5c974

#include "sys_string-Exports.xcconfig"
#include "objc-helpers-Exports.xcconfig"

PRODUCT_NAME = $(TARGET_NAME)
ONLY_ACTIVE_ARCH = YES
PRODUCT_BUNDLE_IDENTIFIER = $(ROOT_BUNDLE_IDENTIFIER).tests
GENERATE_INFOPLIST_FILE = YES
SWIFT_EMIT_LOC_STRINGS = NO
HEADER_SEARCH_PATHS = $(inherited) $(SYS_STRING_HEADER_SEARCH_PATHS)
HEADER_SEARCH_PATHS = $(inherited) $(SYS_STRING_HEADER_SEARCH_PATHS) $(OBJC_HELPERS_HEADER_SEARCH_PATHS)
GCC_PREFIX_HEADER = Translit/src/pch.hpp
GCC_PREPROCESSOR_DEFINITIONS = TRANSLIT_TESTING=1 $(inherited)
//TEST_HOST = $(BUILT_PRODUCTS_DIR)/Translit.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Translit
Expand Down
8 changes: 8 additions & 0 deletions config/objc-helpers-Exports.xcconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) 2024, Eugene Gershnik
// SPDX-License-Identifier: GPL-3.0-or-later

// Configuration settings file format documentation can be found at:
// https://help.apple.com/xcode/#/dev745c5c974

OBJC_HELPERS_HEADER_SEARCH_PATHS = $(PROJECT_DIR)/External/objc-helpers/include

92 changes: 73 additions & 19 deletions fetch
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,31 @@
# SPDX-License-Identifier: GPL-3.0-or-later

import sys
import tarfile
import shutil
import subprocess
from pathlib import Path
from urllib.request import urlretrieve

components = {
'sys_string': {
'ver': '2.13',
'url': 'https://github.com/gershnik/sys_string/releases/download/v{ver}/sys_string-{ver}.tar.gz',
'unpacker': {
'type': 'tar',
'subst': r'#sys_string/##'
},
'dir': 'sys_string',
'verFile': 'VERSION'
},
'objc-helpers': {
'ver': '2.3',
'url': 'https://github.com/gershnik/objc-helpers/releases/download/v{ver}/objc-helpers-{ver}.tar.gz',
'unpacker': {
'type': 'tar'
},
'dir': 'objc-helpers',
'verFile': 'VERSION',
'generateVerFile': True
}
}

Expand All @@ -33,8 +47,7 @@ def getVersionFromFile(path):
existingVer = verToList(path.read_text().rstrip())
return existingVer


def fetchUrl(name, component):
def checkUpToDate(name, component):
directory = externalDir / component['dir']
upToDate = False

Expand All @@ -47,26 +60,64 @@ def fetchUrl(name, component):
else:
print(f"Dont know how to detect version of {name}", file=sys.stderr)
sys.exit(1)

if not upToDate:
print(f'{name} not up to date, required {requiredVer}, existing {existingVer}')
shutil.rmtree(directory, ignore_errors=True)
if directory.exists():
print(f'Unable to remove {name} directory', file=sys.stderr);
sys.exit(1)
directory.mkdir()
url = component['url'].format(ver = component['ver'])
path, headers = urlretrieve(url)
try:
with tarfile.open(path, "r") as tar:
tar.extractall(externalDir)
print(f'Installed {name}')
finally:
Path(path).unlink()
else:
print(f'{name} is up to date')
return upToDate

def untar(name, component, archive):
directory = externalDir / component['dir']
if archive.suffix in ('.tgz', '.gz'):
comp = 'z'
elif archive.suffix in ('.tbz', '.bz'):
comp = 'j'
else:
comp = ''

command = ['/usr/bin/tar', '-C', directory, f'-x{comp}f', archive]
subst = component['unpacker'].get('subst')
if not subst is None:
command += ['-s', subst]
subprocess.run(command, check=True)

def fetchUrl(name, component, unpacker):
directory = externalDir / component['dir']

shutil.rmtree(directory, ignore_errors=True)
if directory.exists():
print(f'Unable to remove {name} directory', file=sys.stderr);
sys.exit(1)
directory.mkdir()
url = component['url'].format(ver = component['ver'])
path, headers = urlretrieve(url)
try:
unpacker(name, component, Path(path))
print(f'Installed {name}')
finally:
Path(path).unlink()
generateVerFile = component.get('generateVerFile', False)
if generateVerFile:
verFile = directory / component['verFile']
verFile.write_text(component['ver'])


def getFetcher(name, component):
if component.get('url'):
return fetchUrl
else:
print(f"Dont know how to download {name}", file=sys.stderr)
sys.exit(1)

def getUnpacker(name, component):
type = component['unpacker']['type']
if type == 'tar':
return untar
else:
print(f"Dont know how to unpack {name}", file=sys.stderr)
sys.exit(1)

localXcconfig = mydir / 'Local.xcconfig'

if not localXcconfig.exists():
Expand All @@ -84,5 +135,8 @@ if not localXcconfig.exists():
'''.lstrip())

for name, component in components.items():
if component.get('url'):
fetchUrl('sys_string', components['sys_string'])
if checkUpToDate(name, component):
continue
fetcher = getFetcher(name, component)
unpacker = getUnpacker(name, component)
fetcher(name, component, unpacker)

0 comments on commit 2b12536

Please sign in to comment.