code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
//
// GTMDelegatingTableColumn.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMDelegatingTableColumn.h"
@implementation GTMDelegatingTableColumn
- (id)dataCellForRow:(NSInteger)row {
id dataCell = nil;
id delegate = [[self tableView] delegate];
BOOL sendSuper = YES;
if (delegate) {
if ([delegate respondsToSelector:@selector(gtm_tableView:dataCellForTableColumn:row:)]) {
dataCell = [delegate gtm_tableView:[self tableView]
dataCellForTableColumn:self
row:row];
sendSuper = NO;
} else {
_GTMDevLog(@"tableView delegate didn't implement gtm_tableView:dataCellForTableColumn:row:");
}
}
if (sendSuper) {
dataCell = [super dataCellForRow:row];
}
return dataCell;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMDelegatingTableColumn.m | Objective-C | bsd | 1,357 |
//
// GTMNSWorkspace+ScreenSaver.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Carbon/Carbon.h>
#import <ScreenSaver/ScreenSaver.h>
#import "GTMNSWorkspace+ScreenSaver.h"
#import "GTMDefines.h"
#import "GTMGarbageCollection.h"
// Interesting class descriptions extracted from ScreenSaver.framework using
// class-dump. Note that these are "not documented".
@protocol ScreenSaverControl
- (BOOL)screenSaverIsRunning;
- (BOOL)screenSaverCanRun;
- (void)setScreenSaverCanRun:(BOOL)fp8;
- (void)screenSaverStartNow;
- (void)screenSaverStopNow;
- (void)restartForUser:(id)fp8;
- (double)screenSaverTimeRemaining;
- (void)screenSaverDidFade;
- (BOOL)screenSaverIsRunningInBackground;
- (void)screenSaverDidFadeInBackground:(BOOL)fp8
psnHi:(unsigned int)fp12
psnLow:(unsigned int)fp16;
@end
@interface ScreenSaverController : NSObject <ScreenSaverControl> {
NSConnection *_connection;
id _daemonProxy;
void *_reserved;
}
+ (id)controller;
+ (id)monitor;
+ (id)daemonConnectionName;
+ (id)enginePath;
- (void)_connectionClosed:(id)fp8;
- (id)init;
- (void)dealloc;
- (BOOL)screenSaverIsRunning;
- (BOOL)screenSaverCanRun;
- (void)setScreenSaverCanRun:(BOOL)fp8;
- (void)screenSaverStartNow;
- (void)screenSaverStopNow;
- (void)restartForUser:(id)fp8;
- (double)screenSaverTimeRemaining;
- (void)screenSaverDidFade;
- (BOOL)screenSaverIsRunningInBackground;
- (void)screenSaverDidFadeInBackground:(BOOL)fp8
psnHi:(unsigned int)fp12
psnLow:(unsigned int)fp16;
@end
// end of extraction
@implementation NSWorkspace (GTMScreenSaverAddition)
// Check if the screen saver is running.
+ (BOOL)gtm_isScreenSaverActive {
BOOL answer = NO;
ScreenSaverController *controller = nil;
// We're calling into an "undocumented" framework here, so we are going to
// step rather carefully (and in 10.5.2 it's only 32bit).
#if !__LP64__
Class screenSaverControllerClass = NSClassFromString(@"ScreenSaverController");
_GTMDevAssert(screenSaverControllerClass,
@"Are you linked with ScreenSaver.framework?"
" Can't find ScreenSaverController class.");
if ([screenSaverControllerClass respondsToSelector:@selector(controller)]) {
controller = [ScreenSaverController controller];
if (controller) {
if ([controller respondsToSelector:@selector(screenSaverIsRunning)]) {
answer = [controller screenSaverIsRunning];
} else {
// COV_NF_START
_GTMDevLog(@"ScreenSaverController no longer supports -screenSaverIsRunning?");
controller = nil;
// COV_NF_END
}
}
}
#endif // !__LP64__
if (!controller) {
// COV_NF_START
// If we can't get the controller, chances are we are being run from the
// command line and don't have access to the window server. As such we are
// going to fallback to the older method of figuring out if a screen saver
// is running.
ProcessSerialNumber psn;
// Check if the saver is already running
require_noerr(GetFrontProcess(&psn), CantGetFrontProcess);
CFDictionaryRef cfProcessInfo
= ProcessInformationCopyDictionary(&psn,
kProcessDictionaryIncludeAllInformationMask);
require(cfProcessInfo, CantGetFrontProcess);
NSDictionary *processInfo = [GTMNSMakeCollectable(cfProcessInfo) autorelease];
NSString *bundlePath = [processInfo objectForKey:@"BundlePath"];
// ScreenSaverEngine is the frontmost app if the screen saver is actually
// running Security Agent is the frontmost app if the "enter password"
// dialog is showing
answer = [bundlePath hasSuffix:@"ScreenSaverEngine.app"] ||
[bundlePath hasSuffix:@"SecurityAgent.app"];
// COV_NF_END
}
CantGetFrontProcess:
return answer;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMNSWorkspace+ScreenSaver.m | Objective-C | bsd | 4,480 |
//
// GTMShading.h
//
// A protocol for an object that can be used as a shader.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
/// \cond Protocols
@protocol GTMShading
// Returns the shadefunction for using in a shader.
// This shadefunction shoud never be released. It is owned by the implementor
// of the GTMShading protocol.
//
// Returns:
// a shading function.
- (CGFunctionRef)shadeFunction;
// Returns the colorSpace for using in a shader.
// This colorSpace shoud never be released. It is owned by the implementor
// of the GTMShading protocol.
//
// Returns:
// a color space.
- (CGColorSpaceRef)colorSpace;
@end
/// \endcond
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMShading.h | Objective-C | bsd | 1,218 |
//
// GTMNSBezierPath+CGPath.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Cocoa/Cocoa.h>
/// Category for extracting a CGPathRef from a NSBezierPath
@interface NSBezierPath (GTMBezierPathCGPathAdditions)
/// Extract a CGPathRef from a NSBezierPath.
//
// Args:
//
// Returns:
// Converted CGPathRef. Must be released by client (CGPathRelease).
// nil if failure.
- (CGPathRef)gtm_createCGPath;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+CGPath.h | Objective-C | bsd | 991 |
//
// GTMNSWorkspace+ScreenSaverTest.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMNSWorkspace+ScreenSaver.h"
@interface GTMNSWorkspace_ScreenSaverTest : GTMTestCase
@end
@implementation GTMNSWorkspace_ScreenSaverTest
- (void)testIsScreenSaverActive {
// Not much of a test, just executes the code. Couldn't think of a
// good way of verifying this one.
[NSWorkspace gtm_isScreenSaverActive];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMNSWorkspace+ScreenSaverTest.m | Objective-C | bsd | 1,017 |
//
// GTMNSBezierPath+CGPath.m
//
// Category for extracting a CGPathRef from a NSBezierPath
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSBezierPath+CGPath.h"
#import "GTMDefines.h"
@implementation NSBezierPath (GTMBezierPathCGPathAdditions)
// Extract a CGPathRef from a NSBezierPath.
//
// Args:
//
// Returns:
// Converted CGPathRef. Must be released by client (CGPathRelease).
// nil if failure.
- (CGPathRef)gtm_createCGPath {
CGMutablePathRef thePath = CGPathCreateMutable();
if (!thePath) return nil;
NSInteger elementCount = [self elementCount];
// The maximum number of points is 3 for a NSCurveToBezierPathElement.
// (controlPoint1, controlPoint2, and endPoint)
NSPoint controlPoints[3];
for (NSInteger i = 0; i < elementCount; i++) {
switch ([self elementAtIndex:i associatedPoints:controlPoints]) {
case NSMoveToBezierPathElement:
CGPathMoveToPoint(thePath, &CGAffineTransformIdentity,
controlPoints[0].x, controlPoints[0].y);
break;
case NSLineToBezierPathElement:
CGPathAddLineToPoint(thePath, &CGAffineTransformIdentity,
controlPoints[0].x, controlPoints[0].y);
break;
case NSCurveToBezierPathElement:
CGPathAddCurveToPoint(thePath, &CGAffineTransformIdentity,
controlPoints[0].x, controlPoints[0].y,
controlPoints[1].x, controlPoints[1].y,
controlPoints[2].x, controlPoints[2].y);
break;
case NSClosePathBezierPathElement:
CGPathCloseSubpath(thePath);
break;
default:
_GTMDevLog(@"Unknown element at [NSBezierPath (GTMBezierPathCGPathAdditions) cgPath]");
break;
};
}
return thePath;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+CGPath.m | Objective-C | bsd | 2,399 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>libgcov_readme.html</title>
<meta http-equiv="REFRESH" content="0;url=http://code.google.com/p/google-toolbox-for-mac/wiki/TigerGcov"></HEAD>
</head>
<body>
</body>
</html>
| 08iteng-ipad | systemtests/google-toolbox-for-mac/TigerGcov/libgcov_readme.html | HTML | bsd | 352 |
//
// GTMIPhoneUnitTestDelegate.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMIPhoneUnitTestDelegate.h"
#import "GTMDefines.h"
#if !GTM_IPHONE_SDK
#error GTMIPhoneUnitTestDelegate for iPhone only
#endif
#import <objc/runtime.h>
#import <stdio.h>
#import <UIKit/UIKit.h>
#import "GTMSenTestCase.h"
// Used for sorting methods below
static int MethodSort(const void *a, const void *b) {
const char *nameA = sel_getName(method_getName(*(Method*)a));
const char *nameB = sel_getName(method_getName(*(Method*)b));
return strcmp(nameA, nameB);
}
// Return YES if class is subclass (1 or more generations) of SenTestCase
static BOOL IsTestFixture(Class aClass) {
BOOL iscase = NO;
Class testCaseClass = [SenTestCase class];
Class superclass;
for (superclass = aClass;
!iscase && superclass;
superclass = class_getSuperclass(superclass)) {
iscase = superclass == testCaseClass ? YES : NO;
}
return iscase;
}
@implementation GTMIPhoneUnitTestDelegate
// Run through all the registered classes and run test methods on any
// that are subclasses of SenTestCase. Terminate the application upon
// test completion.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[self runTests];
if (!getenv("GTM_DISABLE_TERMINATION")) {
// To help using xcodebuild, make the exit status 0/1 to signal the tests
// success/failure.
int exitStatus = (([self totalFailures] == 0U) ? 0 : 1);
exit(exitStatus);
}
}
// Run through all the registered classes and run test methods on any
// that are subclasses of SenTestCase. Print results and run time to
// the default output.
- (void)runTests {
int count = objc_getClassList(NULL, 0);
NSMutableData *classData
= [NSMutableData dataWithLength:sizeof(Class) * count];
Class *classes = (Class*)[classData mutableBytes];
_GTMDevAssert(classes, @"Couldn't allocate class list");
objc_getClassList(classes, count);
totalFailures_ = 0;
totalSuccesses_ = 0;
NSString *suiteName = [[NSBundle mainBundle] bundlePath];
NSDate *suiteStartDate = [NSDate date];
NSString *suiteStartString
= [NSString stringWithFormat:@"Test Suite '%@' started at %@\n",
suiteName, suiteStartDate];
fputs([suiteStartString UTF8String], stderr);
fflush(stderr);
for (int i = 0; i < count; ++i) {
Class currClass = classes[i];
if (IsTestFixture(currClass)) {
NSDate *fixtureStartDate = [NSDate date];
NSString *fixtureName = NSStringFromClass(currClass);
NSString *fixtureStartString
= [NSString stringWithFormat:@"Test Suite '%@' started at %@\n",
fixtureName, fixtureStartDate];
int fixtureSuccesses = 0;
int fixtureFailures = 0;
fputs([fixtureStartString UTF8String], stderr);
fflush(stderr);
id testcase = [[currClass alloc] init];
_GTMDevAssert(testcase, @"Unable to instantiate Test Suite: '%@'\n",
fixtureName);
unsigned int methodCount;
Method *methods = class_copyMethodList(currClass, &methodCount);
if (!methods) {
// If the class contains no methods, head on to the next class
NSString *output = [NSString stringWithFormat:@"Test Suite '%@' "
@"finished at %@.\nExecuted 0 tests, with 0 "
@"failures (0 unexpected) in 0 (0) seconds\n",
fixtureName, fixtureStartDate];
fputs([output UTF8String], stderr);
continue;
}
// This handles disposing of methods for us even if an
// exception should fly.
[NSData dataWithBytesNoCopy:methods
length:sizeof(Method) * methodCount];
// Sort our methods so they are called in Alphabetical order just
// because we can.
qsort(methods, methodCount, sizeof(Method), MethodSort);
for (size_t j = 0; j < methodCount; ++j) {
Method currMethod = methods[j];
SEL sel = method_getName(currMethod);
char *returnType = NULL;
const char *name = sel_getName(sel);
// If it starts with test, takes 2 args (target and sel) and returns
// void run it.
if (strstr(name, "test") == name) {
returnType = method_copyReturnType(currMethod);
if (returnType) {
// This handles disposing of returnType for us even if an
// exception should fly. Length +1 for the terminator, not that
// the length really matters here, as we never reference inside
// the data block.
[NSData dataWithBytesNoCopy:returnType
length:strlen(returnType) + 1];
}
}
if (returnType // True if name starts with "test"
&& strcmp(returnType, @encode(void)) == 0
&& method_getNumberOfArguments(currMethod) == 2) {
BOOL failed = NO;
NSDate *caseStartDate = [NSDate date];
@try {
[testcase performTest:sel];
} @catch (NSException *exception) {
failed = YES;
}
if (failed) {
fixtureFailures += 1;
} else {
fixtureSuccesses += 1;
}
NSTimeInterval caseEndTime
= [[NSDate date] timeIntervalSinceDate:caseStartDate];
NSString *caseEndString
= [NSString stringWithFormat:@"Test Case '-[%@ %s]' %@ (%0.3f "
@"seconds).\n",
fixtureName, name,
failed ? @"failed" : @"passed",
caseEndTime];
fputs([caseEndString UTF8String], stderr);
fflush(stderr);
}
}
[testcase release];
NSDate *fixtureEndDate = [NSDate date];
NSTimeInterval fixtureEndTime
= [fixtureEndDate timeIntervalSinceDate:fixtureStartDate];
NSString *fixtureEndString
= [NSString stringWithFormat:@"Test Suite '%@' finished at %@.\n"
@"Executed %d tests, with %d failures (%d "
@"unexpected) in %0.3f (%0.3f) seconds\n\n",
fixtureName, fixtureEndDate,
fixtureSuccesses + fixtureFailures,
fixtureFailures, fixtureFailures,
fixtureEndTime, fixtureEndTime];
fputs([fixtureEndString UTF8String], stderr);
fflush(stderr);
totalSuccesses_ += fixtureSuccesses;
totalFailures_ += fixtureFailures;
}
}
NSDate *suiteEndDate = [NSDate date];
NSTimeInterval suiteEndTime
= [suiteEndDate timeIntervalSinceDate:suiteStartDate];
NSString *suiteEndString
= [NSString stringWithFormat:@"Test Suite '%@' finished at %@.\n"
@"Executed %d tests, with %d failures (%d "
@"unexpected) in %0.3f (%0.3f) seconds\n\n",
suiteName, suiteEndDate,
totalSuccesses_ + totalFailures_,
totalFailures_, totalFailures_,
suiteEndTime, suiteEndTime];
fputs([suiteEndString UTF8String], stderr);
fflush(stderr);
}
- (NSUInteger)totalSuccesses {
return totalSuccesses_;
}
- (NSUInteger)totalFailures {
return totalFailures_;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestDelegate.m | Objective-C | bsd | 8,120 |
//
// GTMNSObject+BindingUnitTesting.m
//
// An informal protocol for doing advanced binding unittesting with objects.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import "GTMNSObject+BindingUnitTesting.h"
#import "GTMSystemVersion.h"
BOOL GTMDoExposedBindingsFunctionCorrectly(NSObject *object,
NSArray **errors) {
NSMutableArray *errorArray = [NSMutableArray array];
if (errors) {
*errors = nil;
}
NSArray *bindings = [object exposedBindings];
if ([bindings count]) {
NSArray *bindingsToIgnore = [object gtm_unitTestExposedBindingsToIgnore];
NSString *bindingKey;
GTM_FOREACH_OBJECT(bindingKey, bindings) {
if (![bindingsToIgnore containsObject:bindingKey]) {
Class theClass = [object valueClassForBinding:bindingKey];
if (!theClass) {
NSString *error
= [NSString stringWithFormat:@"%@ should have valueClassForBinding '%@'",
object, bindingKey];
[errorArray addObject:error];
continue;
}
@try {
@try {
[object valueForKey:bindingKey];
}
@catch (NSException *e) {
_GTMDevLog(@"%@ is not key value coding compliant for key %@",
object, bindingKey);
continue;
} // COV_NF_LINE - compiler bug
NSArray *testValues
= [object gtm_unitTestExposedBindingsTestValues:bindingKey];
GTMBindingUnitTestData *testData;
GTM_FOREACH_OBJECT(testData, testValues) {
id valueToSet = [testData valueToSet];
[object setValue:valueToSet forKey:bindingKey];
id valueReceived = [object valueForKey:bindingKey];
id desiredValue = [testData expectedValue];
if (![desiredValue gtm_unitTestIsEqualTo:valueReceived]) {
NSString *error
= [NSString stringWithFormat:@"%@ unequal to expected %@ for binding '%@'",
valueReceived, desiredValue, bindingKey];
[errorArray addObject:error];
continue;
}
}
}
@catch(NSException *e) {
NSString *error
= [NSString stringWithFormat:@"%@:%@-> Binding %@",
[e name], [e reason], bindingKey];
[errorArray addObject:error];
} // COV_NF_LINE - compiler bug
}
}
} else {
NSString *error =
[NSString stringWithFormat:@"%@ does not have any exposed bindings",
object];
[errorArray addObject:error];
}
if (errors) {
*errors = errorArray;
}
return [errorArray count] == 0;
}
@implementation GTMBindingUnitTestData
+ (id)testWithIdentityValue:(id)value {
return [self testWithValue:value expecting:value];
}
+ (id)testWithValue:(id)value expecting:(id)expecting {
return [[[self alloc] initWithValue:value expecting:expecting] autorelease];
}
- (id)initWithValue:(id)value expecting:(id)expecting {
if ((self = [super init])) {
valueToSet_ = [value retain];
expectedValue_ = [expecting retain];
}
return self;
}
- (BOOL)isEqual:(id)object {
BOOL isEqual = [object isMemberOfClass:[self class]];
if (isEqual) {
id objValue = [object valueToSet];
id objExpect = [object expectedValue];
isEqual = (((valueToSet_ == objValue) || ([valueToSet_ isEqual:objValue]))
&& ((expectedValue_ == objExpect) || ([expectedValue_ isEqual:objExpect])));
}
return isEqual;
}
- (NSUInteger)hash {
return [valueToSet_ hash] + [expectedValue_ hash];
}
- (void)dealloc {
[valueToSet_ release];
[expectedValue_ release];
[super dealloc];
}
- (id)valueToSet {
return valueToSet_;
}
- (id)expectedValue {
return expectedValue_;
}
@end
@implementation NSObject (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [NSMutableArray arrayWithObject:NSValueBinding];
if ([[self exposedBindings] containsObject:NSFontBinding]) {
NSString *fontBindings[] = { NSFontBoldBinding, NSFontFamilyNameBinding,
NSFontItalicBinding, NSFontNameBinding, NSFontSizeBinding };
for (size_t i = 0; i < sizeof(fontBindings) / sizeof(NSString*); ++i) {
[array addObject:fontBindings[i]];
}
}
return array;
}
- (NSMutableArray*)gtm_unitTestExposedBindingsTestValues:(NSString*)binding {
NSMutableArray *array = [NSMutableArray array];
id value = [self valueForKey:binding];
// Always test identity if possible
if (value) {
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
}
// Now some default test values for a variety of bindings to make
// sure that we cover all the bases and save other people writing lots of
// duplicate test code.
// If anybody can think of more to add, please go nuts.
if ([binding isEqualToString:NSAlignmentBinding]) {
value = [NSNumber numberWithInt:NSLeftTextAlignment];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:NSRightTextAlignment];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:NSCenterTextAlignment];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:NSJustifiedTextAlignment];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:NSNaturalTextAlignment];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
NSNumber *valueToSet = [NSNumber numberWithInt:500];
[array addObject:[GTMBindingUnitTestData testWithValue:valueToSet
expecting:value]];
valueToSet = [NSNumber numberWithInt:-1];
[array addObject:[GTMBindingUnitTestData testWithValue:valueToSet
expecting:value]];
} else if ([binding isEqualToString:NSAlternateImageBinding] ||
[binding isEqualToString:NSImageBinding] ||
[binding isEqualToString:NSMixedStateImageBinding] ||
[binding isEqualToString:NSOffStateImageBinding] ||
[binding isEqualToString:NSOnStateImageBinding]) {
// This handles all image bindings
value = [NSImage imageNamed:@"NSApplicationIcon"];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSAnimateBinding] ||
[binding isEqualToString:NSDocumentEditedBinding] ||
[binding isEqualToString:NSEditableBinding] ||
[binding isEqualToString:NSEnabledBinding] ||
[binding isEqualToString:NSHiddenBinding] ||
[binding isEqualToString:NSVisibleBinding] ||
[binding isEqualToString:NSIsIndeterminateBinding] ||
// NSTranparentBinding 10.5 only
[binding isEqualToString:@"transparent"]) {
// This handles all bool value bindings
value = [NSNumber numberWithBool:YES];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithBool:NO];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSAlternateTitleBinding] ||
[binding isEqualToString:NSHeaderTitleBinding] ||
[binding isEqualToString:NSLabelBinding] ||
[binding isEqualToString:NSTitleBinding] ||
[binding isEqualToString:NSToolTipBinding]) {
// This handles all string value bindings
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:@"happy"]];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:@""]];
// Test some non-ascii roman text
char a_not_alpha[] = { 'A', 0xE2, 0x89, 0xA2, 0xCE, 0x91, '.', 0x00 };
value = [NSString stringWithUTF8String:a_not_alpha];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some korean
char hangugo[] = { 0xED, 0x95, 0x9C, 0xEA, 0xB5,
0xAD, 0xEC, 0x96, 0xB4, 0x00 };
value = [NSString stringWithUTF8String:hangugo];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some japanese
char nihongo[] = { 0xE6, 0x97, 0xA5, 0xE6, 0x9C,
0xAC, 0xE8, 0xAA, 0x9E, 0x00 };
value = [NSString stringWithUTF8String:nihongo];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some arabic
char arabic[] = { 0xd9, 0x83, 0xd8, 0xa7, 0xd9, 0x83, 0xd8, 0xa7, 0x00 };
value = [NSString stringWithUTF8String:arabic];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSRepresentedFilenameBinding]) {
// This handles all path bindings
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:@"/happy"]];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:@"/"]];
// Test some non-ascii roman text
char a_not_alpha[] = { '/', 'A', 0xE2, 0x89, 0xA2, 0xCE, 0x91, '.', 0x00 };
value = [NSString stringWithUTF8String:a_not_alpha];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some korean
char hangugo[] = { '/', 0xED, 0x95, 0x9C, 0xEA, 0xB5,
0xAD, 0xEC, 0x96, 0xB4, 0x00 };
value = [NSString stringWithUTF8String:hangugo];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some japanese
char nihongo[] = { '/', 0xE6, 0x97, 0xA5, 0xE6, 0x9C,
0xAC, 0xE8, 0xAA, 0x9E, 0x00 };
value = [NSString stringWithUTF8String:nihongo];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// Test some arabic
char arabic[] = { '/', 0xd9, 0x83, 0xd8, 0xa7, 0xd9, 0x83, 0xd8, 0xa7, 0x00 };
value = [NSString stringWithUTF8String:arabic];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSMaximumRecentsBinding]) {
value = [NSNumber numberWithInt:0];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:-1];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:INT16_MAX];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithInt:INT16_MIN];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSRowHeightBinding]) {
NSNumber *valueOne = [NSNumber numberWithInt:1];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:valueOne]];
value = [NSNumber numberWithInt:0];
id value2 = [NSNumber numberWithInt:INT16_MIN];
// Row height no longer accepts <= 0 values on SnowLeopard
// which is a good thing.
if ([GTMSystemVersion isSnowLeopardOrGreater]) {
[array addObject:[GTMBindingUnitTestData testWithValue:value
expecting:valueOne]];
[array addObject:[GTMBindingUnitTestData testWithValue:value2
expecting:valueOne]];
} else {
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value2]];
}
value = [NSNumber numberWithInt:INT16_MAX];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSMaxValueBinding] ||
[binding isEqualToString:NSMaxWidthBinding] ||
[binding isEqualToString:NSMinValueBinding] ||
[binding isEqualToString:NSMinWidthBinding] ||
[binding isEqualToString:NSContentWidthBinding] ||
[binding isEqualToString:NSContentHeightBinding] ||
[binding isEqualToString:NSWidthBinding] ||
[binding isEqualToString:NSAnimationDelayBinding]) {
// NSAnimationDelay is deprecated on SnowLeopard. We continue to test it
// to make sure it doesn't get broken.
// This handles all float value bindings
value = [NSNumber numberWithFloat:0];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:FLT_MAX];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:-FLT_MAX];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:FLT_MIN];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:-FLT_MIN];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:FLT_EPSILON];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSNumber numberWithFloat:-FLT_EPSILON];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSTextColorBinding]) {
// This handles all color value bindings
value = [NSColor colorWithCalibratedWhite:1.0 alpha:1.0];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSColor colorWithCalibratedWhite:1.0 alpha:0.0];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSColor colorWithCalibratedWhite:1.0 alpha:0.5];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSColor colorWithCalibratedRed:0.5 green:0.5 blue:0.5 alpha:0.5];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSColor colorWithDeviceCyan:0.25 magenta:0.25 yellow:0.25
black:0.25 alpha:0.25];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSFontBinding]) {
// This handles all font value bindings
value = [NSFont boldSystemFontOfSize:[NSFont systemFontSize]];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSFont toolTipsFontOfSize:[NSFont smallSystemFontSize]];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
value = [NSFont labelFontOfSize:144.0];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSRecentSearchesBinding] ||
[binding isEqualToString:NSSortDescriptorsBinding]) {
// This handles all array value bindings
value = [NSArray array];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else if ([binding isEqualToString:NSTargetBinding]) {
value = [NSNull null];
[array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
} else {
_GTMDevLog(@"Skipped Binding: %@ for %@", binding, self); // COV_NF_LINE
}
return array;
}
- (BOOL)gtm_unitTestIsEqualTo:(id)value {
return [self isEqualTo:value];
}
@end
#pragma mark -
#pragma mark All the special AppKit Bindings issues below
@interface NSImage (GTMBindingUnitTestingAdditions)
@end
@implementation NSImage (GTMBindingUnitTestingAdditions)
- (BOOL)gtm_unitTestIsEqualTo:(id)value {
// NSImage just does pointer equality in the default isEqualTo implementation
// we need something a little more heavy duty that actually compares the
// images internally.
return [[self TIFFRepresentation] isEqualTo:[value TIFFRepresentation]];
}
@end
@interface NSScroller (GTMBindingUnitTestingAdditions)
@end
@implementation NSScroller (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
SInt32 major, minor, bugFix;
[GTMSystemVersion getMajor:&major minor:&minor bugFix:&bugFix];
if (major <= 10 && minor <= 5 && bugFix <= 5) {
// rdar://5849154 - NSScroller exposes binding with no value
// class for NSValueBinding
[array addObject:NSValueBinding];
}
if ([GTMSystemVersion isBuildLessThanOrEqualTo:kGTMSystemBuild10_6_0_WWDC]) {
// Broken on SnowLeopard WWDC and below
// rdar://5849236 - NSScroller exposes binding for NSFontBinding
[array addObject:NSFontBinding];
}
return array;
}
@end
@interface NSTextField (GTMBindingUnitTestingAdditions)
@end
@implementation NSTextField (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
// Not KVC Compliant
for (int i = 0; i < 10; i++) {
[array addObject:[NSString stringWithFormat:@"displayPatternValue%d", i]];
}
return array;
}
- (NSMutableArray *)gtm_unitTestExposedBindingsTestValues:(NSString*)binding {
NSMutableArray *array = [super gtm_unitTestExposedBindingsTestValues:binding];
if ([binding isEqualToString:NSAlignmentBinding]) {
if ([GTMSystemVersion isBuildLessThanOrEqualTo:kGTMSystemBuild10_6_0_WWDC]) {
// rdar://5851487 - If NSAlignmentBinding for a NSTextField is set to -1
// and then got it returns 7
NSNumber *textAlignment = [NSNumber numberWithInt:NSNaturalTextAlignment];
GTMBindingUnitTestData *dataToRemove =
[GTMBindingUnitTestData testWithValue:[NSNumber numberWithInt:-1]
expecting:textAlignment];
[array removeObject:dataToRemove];
GTMBindingUnitTestData *dataToAdd =
[GTMBindingUnitTestData testWithValue:[NSNumber numberWithInt:-1]
expecting:[NSNumber numberWithInt:7]];
[array addObject:dataToAdd];
}
}
return array;
}
@end
@interface NSSearchField (GTMBindingUnitTestingAdditions)
@end
@implementation NSSearchField (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
SInt32 major, minor, bugFix;
[GTMSystemVersion getMajor:&major minor:&minor bugFix:&bugFix];
if (major <= 10 && minor <= 5 && bugFix <= 6) {
// rdar://5851491 - Setting NSAlignmentBinding of search field to
// NSCenterTextAlignment broken
// Broken on 10.5.6 and below.
[array addObject:NSAlignmentBinding];
}
// Not KVC Compliant
[array addObject:NSPredicateBinding];
return array;
}
@end
@interface NSWindow (GTMBindingUnitTestingAdditions)
@end
@implementation NSWindow (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
// Not KVC Compliant
[array addObject:NSContentWidthBinding];
[array addObject:NSContentHeightBinding];
for (int i = 0; i < 10; i++) {
[array addObject:[NSString stringWithFormat:@"displayPatternTitle%d", i]];
}
return array;
}
@end
@interface NSBox (GTMBindingUnitTestingAdditions)
@end
@implementation NSBox (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
// Not KVC Compliant
for (int i = 0; i < 10; i++) {
[array addObject:[NSString stringWithFormat:@"displayPatternTitle%d", i]];
}
return array;
}
@end
@interface NSTableView (GTMBindingUnitTestingAdditions)
@end
@implementation NSTableView (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
if ([GTMSystemVersion isBuildLessThanOrEqualTo:kGTMSystemBuild10_6_0_WWDC]) {
// rdar://6288332 - NSTableView does not respond to NSFontBinding
// Broken on 10.5, and SnowLeopard WWDC
[array addObject:NSFontBinding];
}
// Not KVC Compliant
[array addObject:NSContentBinding];
[array addObject:NSDoubleClickTargetBinding];
[array addObject:NSDoubleClickArgumentBinding];
[array addObject:NSSelectionIndexesBinding];
return array;
}
@end
@interface NSTextView (GTMBindingUnitTestingAdditions)
@end
@implementation NSTextView (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
if ([GTMSystemVersion isBuildLessThanOrEqualTo:kGTMSystemBuild10_6_0_WWDC]) {
//rdar://5849335 - NSTextView only partially KVC compliant for key
// NSAttributedStringBinding
[array addObject:NSAttributedStringBinding];
}
// Not KVC Compliant
[array addObject:NSDataBinding];
[array addObject:NSValueURLBinding];
[array addObject:NSValuePathBinding];
return array;
}
@end
@interface NSTabView (GTMBindingUnitTestingAdditions)
@end
@implementation NSTabView (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
if ([GTMSystemVersion isBuildLessThanOrEqualTo:kGTMSystemBuild10_6_0_WWDC]) {
// rdar://5849248 - NSTabView exposes binding with no value class
// for NSSelectedIdentifierBinding
[array addObject:NSSelectedIdentifierBinding];
}
// Not KVC Compliant
[array addObject:NSSelectedIndexBinding];
[array addObject:NSSelectedLabelBinding];
return array;
}
@end
@interface NSButton (GTMBindingUnitTestingAdditions)
@end
@implementation NSButton (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
// Not KVC Compliant
[array addObject:NSArgumentBinding];
return array;
}
@end
@interface NSProgressIndicator (GTMBindingUnitTestingAdditions)
@end
@implementation NSProgressIndicator (GTMBindingUnitTestingAdditions)
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore {
NSMutableArray *array = [super gtm_unitTestExposedBindingsToIgnore];
// Not KVC Compliant
[array addObject:NSAnimateBinding];
return array;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMNSObject+BindingUnitTesting.m | Objective-C | bsd | 22,808 |
//
// GTMTestTimer.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
#import <mach/mach_time.h>
// GTMTestTimer is done in straight inline C to avoid obj-c calling overhead.
// It is for doing test timings at very high precision.
// Test Timers have standard CoreFoundation Retain/Release rules.
// Test Timers are not thread safe. Test Timers do NOT check their arguments
// for NULL. You will crash if you pass a NULL argument in.
typedef struct {
mach_timebase_info_data_t time_base_info_;
bool running_;
uint64_t start_;
uint64_t split_;
uint64_t elapsed_;
NSUInteger iterations_;
NSUInteger retainCount_;
} GTMTestTimer;
// Create a test timer
GTM_INLINE GTMTestTimer *GTMTestTimerCreate(void) {
GTMTestTimer *t = (GTMTestTimer *)calloc(sizeof(GTMTestTimer), 1);
if (t) {
if (mach_timebase_info(&t->time_base_info_) == KERN_SUCCESS) {
t->retainCount_ = 1;
} else {
// COV_NF_START
free(t);
t = NULL;
// COV_NF_END
}
}
return t;
}
// Retain a timer
GTM_INLINE void GTMTestTimerRetain(GTMTestTimer *t) {
t->retainCount_ += 1;
}
// Release a timer. When release count hits zero, we free it.
GTM_INLINE void GTMTestTimerRelease(GTMTestTimer *t) {
t->retainCount_ -= 1;
if (t->retainCount_ == 0) {
free(t);
}
}
// Starts a timer timing. Specifically starts a new split. If the timer is
// currently running, it resets the start time of the current split.
GTM_INLINE void GTMTestTimerStart(GTMTestTimer *t) {
t->start_ = mach_absolute_time();
t->running_ = true;
}
// Stops a timer and returns split time (time from last start) in nanoseconds.
GTM_INLINE uint64_t GTMTestTimerStop(GTMTestTimer *t) {
uint64_t now = mach_absolute_time();
t->running_ = false;
++t->iterations_;
t->split_ = now - t->start_;
t->elapsed_ += t->split_;
t->start_ = 0;
return t->split_;
}
// returns the current timer elapsed time (combined value of all splits, plus
// current split if the timer is running) in nanoseconds.
GTM_INLINE double GTMTestTimerGetNanoseconds(GTMTestTimer *t) {
uint64_t total = t->elapsed_;
if (t->running_) {
total += mach_absolute_time() - t->start_;
}
return (double)(total * t->time_base_info_.numer
/ t->time_base_info_.denom);
}
// Returns the current timer elapsed time (combined value of all splits, plus
// current split if the timer is running) in seconds.
GTM_INLINE double GTMTestTimerGetSeconds(GTMTestTimer *t) {
return GTMTestTimerGetNanoseconds(t) * 0.000000001;
}
// Returns the current timer elapsed time (combined value of all splits, plus
// current split if the timer is running) in milliseconds.
GTM_INLINE double GTMTestTimerGetMilliseconds(GTMTestTimer *t) {
return GTMTestTimerGetNanoseconds(t) * 0.000001;
}
// Returns the current timer elapsed time (combined value of all splits, plus
// current split if the timer is running) in microseconds.
GTM_INLINE double GTMTestTimerGetMicroseconds(GTMTestTimer *t) {
return GTMTestTimerGetNanoseconds(t) * 0.001;
}
// Returns the number of splits (start-stop) cycles recorded.
// GTMTestTimerGetSeconds()/GTMTestTimerGetIterations() gives you an average
// of all your splits.
GTM_INLINE NSUInteger GTMTestTimerGetIterations(GTMTestTimer *t) {
return t->iterations_;
}
// Returns true if the timer is running.
GTM_INLINE bool GTMTestTimerIsRunning(GTMTestTimer *t) {
return t->running_;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMTestTimer.h | Objective-C | bsd | 4,032 |
#!/bin/bash
#
# RunMacOSUnitTests.sh
# Copyright 2008 Google Inc.
#
# 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.
#
# Run the unit tests in this test bundle.
# Set up some env variables to make things as likely to crash as possible.
# See http://developer.apple.com/technotes/tn2004/tn2124.html for details.
#
set -o errexit
set -o nounset
set -o verbose
# Controlling environment variables:
#
# GTM_DISABLE_ZOMBIES -
# Set to a non-zero value to turn on zombie checks. You will probably
# want to turn this off if you enable leaks.
GTM_DISABLE_ZOMBIES=${GTM_DISABLE_ZOMBIES:=0}
# GTM_ENABLE_LEAKS -
# Set to a non-zero value to turn on the leaks check. You will probably want
# to disable zombies, otherwise you will get a lot of false positives.
GTM_ENABLE_LEAKS=${GTM_ENABLE_LEAKS:=0}
# GTM_LEAKS_SYMBOLS_TO_IGNORE
# List of comma separated symbols that leaks should ignore. Mainly to control
# leaks in frameworks you don't have control over.
# Search this file for GTM_LEAKS_SYMBOLS_TO_IGNORE to see examples.
# Please feel free to add other symbols as you find them but make sure to
# reference Radars or other bug systems so we can track them.
GTM_LEAKS_SYMBOLS_TO_IGNORE=${GTM_LEAKS_SYMBOLS_TO_IGNORE:=""}
# GTM_DO_NOT_REMOVE_GCOV_DATA
# By default before starting the test, we remove any *.gcda files for the
# current project build configuration so you won't get errors when a source
# file has changed and the gcov data can't be merged.
# We remove all the gcda files for the current configuration for the entire
# project so that if you are building a test bundle to test another separate
# bundle we make sure to clean up the files for the test bundle and the bundle
# that you are testing.
# If you DO NOT want this to occur, set GTM_DO_NOT_REMOVE_GCOV_DATA to a
# non-zero value.
GTM_DO_NOT_REMOVE_GCOV_DATA=${GTM_DO_NOT_REMOVE_GCOV_DATA:=0}
ScriptDir=$(dirname "$(echo $0 | sed -e "s,^\([^/]\),$(pwd)/\1,")")
ScriptName=$(basename "$0")
ThisScript="${ScriptDir}/${ScriptName}"
GTMXcodeNote() {
echo ${ThisScript}:${1}: note: GTM ${2}
}
# The workaround below is due to
# Radar 6248062 otest won't run with MallocHistory enabled under rosetta
# Basically we go through and check what architecture we are running on
# and which architectures we can support
AppendToSymbolsLeaksShouldIgnore() {
if [ "${GTM_LEAKS_SYMBOLS_TO_IGNORE}" = "" ]; then
GTM_LEAKS_SYMBOLS_TO_IGNORE="${1}"
else
GTM_LEAKS_SYMBOLS_TO_IGNORE="${GTM_LEAKS_SYMBOLS_TO_IGNORE}, ${1}"
fi
}
AppendToLeakTestArchs() {
if [ "${LEAK_TEST_ARCHS}" = "" ]; then
LEAK_TEST_ARCHS="${1}"
else
LEAK_TEST_ARCHS="${LEAK_TEST_ARCHS} ${1}"
fi
}
AppendToNoLeakTestArchs() {
if [ "${NO_LEAK_TEST_ARCHS}" = "" ]; then
NO_LEAK_TEST_ARCHS="${1}"
else
NO_LEAK_TEST_ARCHS="${NO_LEAK_TEST_ARCHS} ${1}"
fi
}
UpdateArchitecturesToTest() {
case "${NATIVE_ARCH_ACTUAL}" in
ppc)
if [ "${1}" = "ppc" ]; then
AppendToLeakTestArchs "${1}"
fi
;;
ppc64)
if [ "${1}" = "ppc" -o "${1}" = "ppc64" ]; then
AppendToLeakTestArchs "${1}"
fi
;;
i386)
if [ "${1}" = "i386" ]; then
AppendToLeakTestArchs "${1}"
elif [ "${1}" = "ppc" ]; then
AppendToNoLeakTestArchs "${1}"
fi
;;
x86_64)
if [ "${1}" = "i386" -o "${1}" = "x86_64" ]; then
AppendToLeakTestArchs "${1}"
elif [ "${1}" = "ppc" -o "${1}" = "ppc64" ]; then
AppendToNoLeakTestArchs "${1}"
fi
;;
*)
echo "RunMacOSUnitTests.sh Unknown native architecture: ${NATIVE_ARCH_ACTUAL}"
exit 1
;;
esac
}
RunTests() {
if [ "${CURRENT_ARCH}" = "" ]; then
CURRENT_ARCH=`arch`
fi
if [ "${ONLY_ACTIVE_ARCH}" = "YES" ]; then
ARCHS="${CURRENT_ARCH}"
fi
if [ "${ARCHS}" = "" ]; then
ARCHS=`arch`
fi
if [ "${VALID_ARCHS}" = "" ]; then
VALID_ARCHS=`arch`
fi
if [ "${NATIVE_ARCH_ACTUAL}" = "" ]; then
NATIVE_ARCH_ACTUAL=`arch`
fi
LEAK_TEST_ARCHS=""
NO_LEAK_TEST_ARCHS=""
for TEST_ARCH in ${ARCHS}; do
for TEST_VALID_ARCH in ${VALID_ARCHS}; do
if [ "${TEST_VALID_ARCH}" = "${TEST_ARCH}" ]; then
UpdateArchitecturesToTest "${TEST_ARCH}"
fi
done
done
# These are symbols that leak on OS 10.5.5
# radar 6247293 NSCollatorElement leaks in +initialize.
AppendToSymbolsLeaksShouldIgnore "+[NSCollatorElement initialize]"
# radar 6247911 The first call to udat_open leaks only on x86_64
AppendToSymbolsLeaksShouldIgnore "icu::TimeZone::initDefault()"
# radar 6263983 +[IMService allServices] leaks
AppendToSymbolsLeaksShouldIgnore "-[IMServiceAgentImpl allServices]"
# radar 6264034 +[IKSFEffectDescription initialize] Leaks
AppendToSymbolsLeaksShouldIgnore "+[IKSFEffectDescription initialize]"
# Running leaks on architectures that support leaks.
export MallocStackLogging=YES
export GTM_LEAKS_SYMBOLS_TO_IGNORE="${GTM_LEAKS_SYMBOLS_TO_IGNORE}"
ARCHS="${LEAK_TEST_ARCHS}"
VALID_ARCHS="${LEAK_TEST_ARCHS}"
GTMXcodeNote ${LINENO} "Leak checking enabled for $ARCHS. Ignoring leaks from $GTM_LEAKS_SYMBOLS_TO_IGNORE."
"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests"
# Running leaks on architectures that don't support leaks.
unset MallocStackLogging
GTM_ENABLE_LEAKS=0
ARCHS="${NO_LEAK_TEST_ARCHS}"
VALID_ARCHS="${NO_LEAK_TEST_ARCHS}"
"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests"
}
# Jack up some memory stress so we can catch more bugs.
export MallocScribble=YES
export MallocPreScribble=YES
export MallocGuardEdges=YES
export NSAutoreleaseFreedObjectCheckEnabled=YES
# Turn on the mostly undocumented OBJC_DEBUG stuff.
export OBJC_DEBUG_FRAGILE_SUPERCLASSES=YES
export OBJC_DEBUG_UNLOAD=YES
# Turned off due to the amount of false positives from NS classes.
# export OBJC_DEBUG_FINALIZERS=YES
export OBJC_DEBUG_NIL_SYNC=YES
if [ $GTM_DISABLE_ZOMBIES -eq 0 ]; then
GTMXcodeNote ${LINENO} "Enabling zombies"
# CFZombieLevel disabled because it doesn't play well with the
# security framework
# export CFZombieLevel=3
export NSZombieEnabled=YES
fi
if [ ! $GTM_DO_NOT_REMOVE_GCOV_DATA ]; then
if [ "${CONFIGURATION_TEMP_DIR}" != "-" ]; then
if [ -d "${CONFIGURATION_TEMP_DIR}" ]; then
GTMXcodeNote ${LINENO} "Removing gcov data files from ${CONFIGURATION_TEMP_DIR}"
(cd "${CONFIGURATION_TEMP_DIR}" && \
find . -type f -name "*.gcda" -print0 | xargs -0 rm -f )
fi
fi
fi
# If leaks testing is enabled, we have to go through our convoluted path
# to handle architectures that don't allow us to do leak testing.
if [ $GTM_ENABLE_LEAKS -ne 0 ]; then
RunTests
else
GTMXcodeNote ${LINENO} "Leak checking disabled."
"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests"
fi
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/RunMacOSUnitTests.sh | Shell | bsd | 7,323 |
//
// GTMIPhoneUnitTestDelegate.h
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
// Application delegate that runs all test methods in registered classes
// extending SenTestCase. The application is terminated afterwards.
// You can also run the tests directly from your application by invoking
// runTests and clean up, restore data, etc. before the application
// terminates.
@interface GTMIPhoneUnitTestDelegate : NSObject {
@private
NSUInteger totalFailures_;
NSUInteger totalSuccesses_;
}
// Runs through all the registered classes and runs test methods on any
// that are subclasses of SenTestCase. Prints results and run time to
// the default output.
- (void)runTests;
// Fetch the number of successes or failures from the last runTests.
- (NSUInteger)totalSuccesses;
- (NSUInteger)totalFailures;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestDelegate.h | Objective-C | bsd | 1,409 |
//
// GTMUnitTestingUtilities.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import <objc/objc.h>
// Collection of utilities for unit testing
@interface GTMUnitTestingUtilities : NSObject
// Returns YES if we are currently being unittested.
+ (BOOL)areWeBeingUnitTested;
// Sets up the user interface so that we can run consistent UI unittests on
// it. This includes setting scroll bar types, setting selection colors
// setting color spaces etc so that everything is consistent across machines.
// This should be called in main, before NSApplicationMain is called.
+ (void)setUpForUIUnitTests;
// Syntactic sugar combining the above, and wrapping them in an
// NSAutoreleasePool so that your main can look like this:
// int main(int argc, const char *argv[]) {
// [UnitTestingUtilities setUpForUIUnitTestsIfBeingTested];
// return NSApplicationMain(argc, argv);
// }
+ (void)setUpForUIUnitTestsIfBeingTested;
// Check if the screen saver is running. Some unit tests don't work when
// the screen saver is active.
+ (BOOL)isScreenSaverActive;
// Allows for posting either a keydown or a keyup with all the modifiers being
// applied. Passing a 'g' with NSKeyDown and NSShiftKeyMask
// generates two events (a shift key key down and a 'g' key keydown). Make sure
// to balance this with a keyup, or things could get confused. Events get posted
// using the CGRemoteOperation events which means that it gets posted in the
// system event queue. Thus you can affect other applications if your app isn't
// the active app (or in some cases, such as hotkeys, even if it is).
// Arguments:
// type - Event type. Currently accepts NSKeyDown and NSKeyUp
// keyChar - character on the keyboard to type. Make sure it is lower case.
// If you need upper case, pass in the NSShiftKeyMask in the
// modifiers. i.e. to generate "G" pass in 'g' and NSShiftKeyMask.
// to generate "+" pass in '=' and NSShiftKeyMask.
// cocoaModifiers - an int made up of bit masks. Handles NSAlphaShiftKeyMask,
// NSShiftKeyMask, NSControlKeyMask, NSAlternateKeyMask, and
// NSCommandKeyMask
+ (void)postKeyEvent:(NSEventType)type
character:(CGCharCode)keyChar
modifiers:(UInt32)cocoaModifiers;
// Syntactic sugar for posting a keydown immediately followed by a key up event
// which is often what you really want.
// Arguments:
// keyChar - character on the keyboard to type. Make sure it is lower case.
// If you need upper case, pass in the NSShiftKeyMask in the
// modifiers. i.e. to generate "G" pass in 'g' and NSShiftKeyMask.
// to generate "+" pass in '=' and NSShiftKeyMask.
// cocoaModifiers - an int made up of bit masks. Handles NSAlphaShiftKeyMask,
// NSShiftKeyMask, NSControlKeyMask, NSAlternateKeyMask, and
// NSCommandKeyMask
+ (void)postTypeCharacterEvent:(CGCharCode)keyChar
modifiers:(UInt32)cocoaModifiers;
// Runs the event loop in NSDefaultRunLoopMode until date. Can be useful for
// testing user interface responses in a controlled timed event loop. For most
// uses using:
// [[NSRunLoop currentRunLoop] runUntilDate:date]
// will do. The only reason you would want to use this is if you were
// using the postKeyEvent:character:modifiers to send events and wanted to
// receive user input.
// Arguments:
// date - end of execution time
+ (void)runUntilDate:(NSDate*)date;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestingUtilities.h | Objective-C | bsd | 4,116 |
//
// main.m
// GTMUnitTestingTest
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Cocoa/Cocoa.h>
#import "GTMUnitTestingUtilities.h"
int main(int argc, char *argv[]) {
[GTMUnitTestingUtilities setUpForUIUnitTestsIfBeingTested];
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUIUnitTestingHarness/main.m | Objective-C | bsd | 865 |
//
// GTMDevLogUnitTestingBridge.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#include "GTMUnitTestDevLog.h"
//
// NOTE: Odds are this file should not be included in your project. It is
// only needed for some enhanced unit testing.
//
// By adding:
// #define _GTMDevLog _GTMUnitTestDevLog
// to your prefix header (like the GTM Framework does), this function then
// works to forward logging messages to the GTMUnitTestDevLog class to
// allow logging validation during unittest, otherwise the messages go to
// NSLog like normal.
//
// See GTMUnitTestDevLog.h for more information on checking logs in unittests.
//
void _GTMUnitTestDevLog(NSString *format, ...) {
Class devLogClass = NSClassFromString(@"GTMUnitTestDevLog");
va_list argList;
va_start(argList, format);
if (devLogClass) {
[devLogClass log:format args:argList];
} else {
NSLogv(format, argList); // COV_NF_LINE the class is in all our unittest setups
}
va_end(argList);
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMDevLogUnitTestingBridge.m | Objective-C | bsd | 1,532 |
//
// GTMUnitTestingUtilities.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMUnitTestingUtilities.h"
#import <AppKit/AppKit.h>
#import "GTMDefines.h"
#import "GTMGarbageCollection.h"
// The Users profile before we change it on them
static CMProfileRef gGTMCurrentColorProfile = NULL;
// Compares two color profiles
static BOOL GTMAreCMProfilesEqual(CMProfileRef a, CMProfileRef b);
// Stores the user's color profile away, and changes over to generic.
static void GTMSetColorProfileToGenericRGB();
// Restores the users profile.
static void GTMRestoreColorProfile(void);
static CGKeyCode GTMKeyCodeForCharCode(CGCharCode charCode);
@implementation GTMUnitTestingUtilities
// Returns YES if we are currently being unittested.
+ (BOOL)areWeBeingUnitTested {
BOOL answer = NO;
// Check to see if the SenTestProbe class is linked in before we call it.
Class SenTestProbeClass = NSClassFromString(@"SenTestProbe");
if (SenTestProbeClass != Nil) {
// Doing this little dance so we don't actually have to link
// SenTestingKit in
SEL selector = NSSelectorFromString(@"isTesting");
NSMethodSignature *sig = [SenTestProbeClass methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:selector];
[invocation invokeWithTarget:SenTestProbeClass];
[invocation getReturnValue:&answer];
}
return answer;
}
// Sets up the user interface so that we can run consistent UI unittests on it.
+ (void)setUpForUIUnitTests {
// Give some names to undocumented defaults values
const NSInteger MediumFontSmoothing = 2;
const NSInteger BlueTintedAppearance = 1;
// This sets up some basic values that we want as our defaults for doing pixel
// based user interface tests. These defaults only apply to the unit test app,
// except or the color profile which will be set system wide, and then
// restored when the tests complete.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Scroll arrows together bottom
[defaults setObject:@"DoubleMax" forKey:@"AppleScrollBarVariant"];
// Smallest font size to CG should perform antialiasing on
[defaults setInteger:4 forKey:@"AppleAntiAliasingThreshold"];
// Type of smoothing
[defaults setInteger:MediumFontSmoothing forKey:@"AppleFontSmoothing"];
// Blue aqua
[defaults setInteger:BlueTintedAppearance forKey:@"AppleAquaColorVariant"];
// Standard highlight colors
[defaults setObject:@"0.709800 0.835300 1.000000"
forKey:@"AppleHighlightColor"];
[defaults setObject:@"0.500000 0.500000 0.500000"
forKey:@"AppleOtherHighlightColor"];
// Use english plz
[defaults setObject:[NSArray arrayWithObject:@"en"] forKey:@"AppleLanguages"];
// How fast should we draw sheets. This speeds up the sheet tests considerably
[defaults setFloat:.001f forKey:@"NSWindowResizeTime"];
// Switch over the screen profile to "generic rgb". This installs an
// atexit handler to return our profile back when we are done.
GTMSetColorProfileToGenericRGB();
}
+ (void)setUpForUIUnitTestsIfBeingTested {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ([self areWeBeingUnitTested]) {
[self setUpForUIUnitTests];
}
[pool release];
}
+ (BOOL)isScreenSaverActive {
BOOL answer = NO;
ProcessSerialNumber psn;
if (GetFrontProcess(&psn) == noErr) {
CFDictionaryRef cfProcessInfo
= ProcessInformationCopyDictionary(&psn,
kProcessDictionaryIncludeAllInformationMask);
NSDictionary *processInfo = GTMCFAutorelease(cfProcessInfo);
NSString *bundlePath = [processInfo objectForKey:@"BundlePath"];
// ScreenSaverEngine is the frontmost app if the screen saver is actually
// running Security Agent is the frontmost app if the "enter password"
// dialog is showing
NSString *bundleName = [bundlePath lastPathComponent];
answer = ([bundleName isEqualToString:@"ScreenSaverEngine.app"]
|| [bundleName isEqualToString:@"SecurityAgent.app"]);
}
return answer;
}
// Allows for posting either a keydown or a keyup with all the modifiers being
// applied. Passing a 'g' with NSKeyDown and NSShiftKeyMask
// generates two events (a shift key key down and a 'g' key keydown). Make sure
// to balance this with a keyup, or things could get confused. Events get posted
// using the CGRemoteOperation events which means that it gets posted in the
// system event queue. Thus you can affect other applications if your app isn't
// the active app (or in some cases, such as hotkeys, even if it is).
// Arguments:
// type - Event type. Currently accepts NSKeyDown and NSKeyUp
// keyChar - character on the keyboard to type. Make sure it is lower case.
// If you need upper case, pass in the NSShiftKeyMask in the
// modifiers. i.e. to generate "G" pass in 'g' and NSShiftKeyMask.
// to generate "+" pass in '=' and NSShiftKeyMask.
// cocoaModifiers - an int made up of bit masks. Handles NSAlphaShiftKeyMask,
// NSShiftKeyMask, NSControlKeyMask, NSAlternateKeyMask, and
// NSCommandKeyMask
+ (void)postKeyEvent:(NSEventType)type
character:(CGCharCode)keyChar
modifiers:(UInt32)cocoaModifiers {
require(![self isScreenSaverActive], CantWorkWithScreenSaver);
require(type == NSKeyDown || type == NSKeyUp, CantDoEvent);
CGKeyCode code = GTMKeyCodeForCharCode(keyChar);
verify(code != 256);
CGEventRef event = CGEventCreateKeyboardEvent(NULL, code, type == NSKeyDown);
require(event, CantCreateEvent);
CGEventSetFlags(event, cocoaModifiers);
CGEventPost(kCGSessionEventTap, event);
CFRelease(event);
CantCreateEvent:
CantDoEvent:
CantWorkWithScreenSaver:
return;
}
// Syntactic sugar for posting a keydown immediately followed by a key up event
// which is often what you really want.
// Arguments:
// keyChar - character on the keyboard to type. Make sure it is lower case.
// If you need upper case, pass in the NSShiftKeyMask in the
// modifiers. i.e. to generate "G" pass in 'g' and NSShiftKeyMask.
// to generate "+" pass in '=' and NSShiftKeyMask.
// cocoaModifiers - an int made up of bit masks. Handles NSAlphaShiftKeyMask,
// NSShiftKeyMask, NSControlKeyMask, NSAlternateKeyMask, and
// NSCommandKeyMask
+ (void)postTypeCharacterEvent:(CGCharCode)keyChar modifiers:(UInt32)cocoaModifiers {
[self postKeyEvent:NSKeyDown character:keyChar modifiers:cocoaModifiers];
[self postKeyEvent:NSKeyUp character:keyChar modifiers:cocoaModifiers];
}
// Runs the event loop in NSDefaultRunLoopMode until date. Can be useful for
// testing user interface responses in a controlled timed event loop. For most
// uses using:
// [[NSRunLoop currentRunLoop] runUntilDate:date]
// will do. The only reason you would want to use this is if you were
// using the postKeyEvent:character:modifiers to send events and wanted to
// receive user input.
// Arguments:
// date - end of execution time
+ (void)runUntilDate:(NSDate*)date {
NSEvent *event;
while ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
untilDate:date
inMode:NSDefaultRunLoopMode
dequeue:YES])) {
[NSApp sendEvent:event];
}
}
@end
BOOL GTMAreCMProfilesEqual(CMProfileRef a, CMProfileRef b) {
BOOL equal = YES;
if (a != b) {
CMProfileMD5 aMD5;
CMProfileMD5 bMD5;
CMError aMD5Err = CMGetProfileMD5(a, aMD5);
CMError bMD5Err = CMGetProfileMD5(b, bMD5);
equal = (!aMD5Err &&
!bMD5Err &&
!memcmp(aMD5, bMD5, sizeof(CMProfileMD5))) ? YES : NO;
}
return equal;
}
void GTMRestoreColorProfile(void) {
if (gGTMCurrentColorProfile) {
CGDirectDisplayID displayID = CGMainDisplayID();
CMError error = CMSetProfileByAVID((UInt32)displayID,
gGTMCurrentColorProfile);
CMCloseProfile(gGTMCurrentColorProfile);
if (error) {
// COV_NF_START
// No way to force this case in a unittest.
_GTMDevLog(@"Failed to restore previous color profile! "
"You may need to open System Preferences : Displays : Color "
"and manually restore your color settings. (Error: %i)", error);
// COV_NF_END
} else {
_GTMDevLog(@"Color profile restored");
}
gGTMCurrentColorProfile = NULL;
}
}
void GTMSetColorProfileToGenericRGB(void) {
NSColorSpace *genericSpace = [NSColorSpace genericRGBColorSpace];
CMProfileRef genericProfile = (CMProfileRef)[genericSpace colorSyncProfile];
CMProfileRef previousProfile;
CGDirectDisplayID displayID = CGMainDisplayID();
CMError error = CMGetProfileByAVID((UInt32)displayID, &previousProfile);
if (error) {
// COV_NF_START
// No way to force this case in a unittest.
_GTMDevLog(@"Failed to get current color profile. "
"I will not be able to restore your current profile, thus I'm "
"not changing it. Many unit tests may fail as a result. (Error: %i)",
error);
return;
// COV_NF_END
}
if (GTMAreCMProfilesEqual(genericProfile, previousProfile)) {
CMCloseProfile(previousProfile);
return;
}
CFStringRef previousProfileName;
CFStringRef genericProfileName;
CMCopyProfileDescriptionString(previousProfile, &previousProfileName);
CMCopyProfileDescriptionString(genericProfile, &genericProfileName);
_GTMDevLog(@"Temporarily changing your system color profile from \"%@\" to \"%@\".",
previousProfileName, genericProfileName);
_GTMDevLog(@"This allows the pixel-based unit-tests to have consistent color "
"values across all machines.");
_GTMDevLog(@"The colors on your screen will change for the duration of the testing.");
if ((error = CMSetProfileByAVID((UInt32)displayID, genericProfile))) {
// COV_NF_START
// No way to force this case in a unittest.
_GTMDevLog(@"Failed to set color profile to \"%@\"! Many unit tests will fail as "
"a result. (Error: %i)", genericProfileName, error);
// COV_NF_END
} else {
gGTMCurrentColorProfile = previousProfile;
atexit(GTMRestoreColorProfile);
}
CFRelease(previousProfileName);
CFRelease(genericProfileName);
}
// Returns a virtual key code for a given charCode. Handles all of the
// NS*FunctionKeys as well.
static CGKeyCode GTMKeyCodeForCharCode(CGCharCode charCode) {
// character map taken from http://classicteck.com/rbarticles/mackeyboard.php
int characters[] = {
'a', 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 256, 'b', 'q', 'w',
'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5', '=', '9', '7', '-',
'8', '0', ']', 'o', 'u', '[', 'i', 'p', '\n', 'l', 'j', '\'', 'k', ';',
'\\', ',', '/', 'n', 'm', '.', '\t', ' ', '`', '\b', 256, '\e'
};
// function key map taken from
// file:///Developer/ADC%20Reference%20Library/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSEvent.html
int functionKeys[] = {
// NSUpArrowFunctionKey - NSF12FunctionKey
126, 125, 123, 124, 122, 120, 99, 118, 96, 97, 98, 100, 101, 109, 103, 111,
// NSF13FunctionKey - NSF28FunctionKey
105, 107, 113, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
// NSF29FunctionKey - NSScrollLockFunctionKey
256, 256, 256, 256, 256, 256, 256, 256, 117, 115, 256, 119, 116, 121, 256, 256,
// NSPauseFunctionKey - NSPrevFunctionKey
256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
// NSNextFunctionKey - NSModeSwitchFunctionKey
256, 256, 256, 256, 256, 256, 114, 1
};
CGKeyCode outCode = 0;
// Look in the function keys
if (charCode >= NSUpArrowFunctionKey && charCode <= NSModeSwitchFunctionKey) {
outCode = functionKeys[charCode - NSUpArrowFunctionKey];
} else {
// Look in our character map
for (size_t i = 0; i < (sizeof(characters) / sizeof (int)); i++) {
if (characters[i] == charCode) {
outCode = i;
break;
}
}
}
return outCode;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestingUtilities.m | Objective-C | bsd | 12,878 |
//
// GTMUIKit+UnitTestingTest.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <CoreGraphics/CoreGraphics.h>
#import "GTMUIKit+UnitTesting.h"
#import "GTMSenTestCase.h"
@interface GTMUIView_UnitTestingTest : SenTestCase <GTMUnitTestViewDrawer>
@end
@implementation GTMUIView_UnitTestingTest
- (void)testDrawing {
GTMAssertDrawingEqualToFile(self,
CGSizeMake(200,200),
@"GTMUIViewUnitTestingTest",
[UIApplication sharedApplication],
nil);
}
- (void)testState {
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)] autorelease];
UIView *subview = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)] autorelease];
[view addSubview:subview];
GTMAssertObjectStateEqualToStateNamed(view, @"GTMUIViewUnitTestingTest", nil);
}
- (void)testUIImage {
NSString* name = @"GTMUIViewUnitTestingTest";
UIImage* image =
[UIImage imageNamed:[name stringByAppendingPathExtension:@"png"]];
GTMAssertObjectImageEqualToImageNamed(image, name, nil);
}
- (void)gtm_unitTestViewDrawRect:(CGRect)rect contextInfo:(void*)contextInfo {
UIApplication *app = [UIApplication sharedApplication];
STAssertEqualObjects(app,
contextInfo,
@"Should be a UIApplication");
CGPoint center = CGPointMake(CGRectGetMidX(rect),
CGRectGetMidY(rect));
rect = CGRectMake(center.x - 50, center.y - 50, 100, 100);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(context, rect);
CGContextSetLineWidth(context, 5);
[[UIColor redColor] set];
CGContextStrokePath(context);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUIKit+UnitTestingTest.m | Objective-C | bsd | 2,303 |
//
// GTMSenTestCase.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import <unistd.h>
#if !GTM_IPHONE_SDK
#import "GTMGarbageCollection.h"
#endif // !GTM_IPHONE_SDK
#if GTM_IPHONE_SDK
#import <stdarg.h>
@interface NSException (GTMSenTestPrivateAdditions)
+ (NSException *)failureInFile:(NSString *)filename
atLine:(int)lineNumber
reason:(NSString *)reason;
@end
@implementation NSException (GTMSenTestPrivateAdditions)
+ (NSException *)failureInFile:(NSString *)filename
atLine:(int)lineNumber
reason:(NSString *)reason {
NSDictionary *userInfo =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:lineNumber], SenTestLineNumberKey,
filename, SenTestFilenameKey,
nil];
return [self exceptionWithName:SenTestFailureException
reason:reason
userInfo:userInfo];
}
@end
@implementation NSException (GTMSenTestAdditions)
+ (NSException *)failureInFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason = testDescription;
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
+ (NSException *)failureInCondition:(NSString *)condition
isTrue:(BOOL)isTrue
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason = [NSString stringWithFormat:@"'%@' should be %s. %@",
condition, isTrue ? "TRUE" : "FALSE", testDescription];
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
+ (NSException *)failureInEqualityBetweenObject:(id)left
andObject:(id)right
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason =
[NSString stringWithFormat:@"'%@' should be equal to '%@'. %@",
[left description], [right description], testDescription];
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
+ (NSException *)failureInEqualityBetweenValue:(NSValue *)left
andValue:(NSValue *)right
withAccuracy:(NSValue *)accuracy
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason;
if (accuracy) {
reason =
[NSString stringWithFormat:@"'%@' should be equal to '%@'. %@",
left, right, testDescription];
} else {
reason =
[NSString stringWithFormat:@"'%@' should be equal to '%@' +/-'%@'. %@",
left, right, accuracy, testDescription];
}
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
+ (NSException *)failureInRaise:(NSString *)expression
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason = [NSString stringWithFormat:@"'%@' should raise. %@",
expression, testDescription];
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
+ (NSException *)failureInRaise:(NSString *)expression
exception:(NSException *)exception
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ... {
NSString *testDescription = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
testDescription =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
NSString *reason;
if ([[exception name] isEqualToString:SenTestFailureException]) {
// it's our exception, assume it has the right description on it.
reason = [exception reason];
} else {
// not one of our exception, use the exceptions reason and our description
reason = [NSString stringWithFormat:@"'%@' raised '%@'. %@",
expression, [exception reason], testDescription];
}
return [self failureInFile:filename atLine:lineNumber reason:reason];
}
@end
NSString *STComposeString(NSString *formatString, ...) {
NSString *reason = @"";
if (formatString) {
va_list vl;
va_start(vl, formatString);
reason =
[[[NSString alloc] initWithFormat:formatString arguments:vl] autorelease];
va_end(vl);
}
return reason;
}
NSString *const SenTestFailureException = @"SenTestFailureException";
NSString *const SenTestFilenameKey = @"SenTestFilenameKey";
NSString *const SenTestLineNumberKey = @"SenTestLineNumberKey";
@interface SenTestCase (SenTestCasePrivate)
// our method of logging errors
+ (void)printException:(NSException *)exception fromTestName:(NSString *)name;
@end
@implementation SenTestCase
- (void)failWithException:(NSException*)exception {
[exception raise];
}
- (void)setUp {
}
- (void)performTest:(SEL)sel {
currentSelector_ = sel;
@try {
[self invokeTest];
} @catch (NSException *exception) {
[[self class] printException:exception
fromTestName:NSStringFromSelector(sel)];
[exception raise];
}
}
+ (void)printException:(NSException *)exception fromTestName:(NSString *)name {
NSDictionary *userInfo = [exception userInfo];
NSString *filename = [userInfo objectForKey:SenTestFilenameKey];
NSNumber *lineNumber = [userInfo objectForKey:SenTestLineNumberKey];
NSString *className = NSStringFromClass([self class]);
if ([filename length] == 0) {
filename = @"Unknown.m";
}
fprintf(stderr, "%s:%ld: error: -[%s %s] : %s\n",
[filename UTF8String],
(long)[lineNumber integerValue],
[className UTF8String],
[name UTF8String],
[[exception reason] UTF8String]);
fflush(stderr);
}
- (void)invokeTest {
NSException *e = nil;
@try {
// Wrap things in autorelease pools because they may
// have an STMacro in their dealloc which may get called
// when the pool is cleaned up
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// We don't log exceptions here, instead we let the person that called
// this log the exception. This ensures they are only logged once but the
// outer layers get the exceptions to report counts, etc.
@try {
[self setUp];
@try {
[self performSelector:currentSelector_];
} @catch (NSException *exception) {
e = [exception retain];
}
[self tearDown];
} @catch (NSException *exception) {
e = [exception retain];
}
[pool release];
} @catch (NSException *exception) {
e = [exception retain];
}
if (e) {
[e autorelease];
[e raise];
}
}
- (void)tearDown {
}
- (NSString *)description {
// This matches the description OCUnit would return to you
return [NSString stringWithFormat:@"-[%@ %@]", [self class],
NSStringFromSelector(currentSelector_)];
}
@end
#endif // GTM_IPHONE_SDK
@implementation GTMTestCase : SenTestCase
- (void)invokeTest {
Class devLogClass = NSClassFromString(@"GTMUnitTestDevLog");
if (devLogClass) {
[devLogClass performSelector:@selector(enableTracking)];
[devLogClass performSelector:@selector(verifyNoMoreLogsExpected)];
}
[super invokeTest];
if (devLogClass) {
[devLogClass performSelector:@selector(verifyNoMoreLogsExpected)];
[devLogClass performSelector:@selector(disableTracking)];
}
}
@end
// Leak detection
#if !GTM_IPHONE_DEVICE
// Don't want to get leaks on the iPhone Device as the device doesn't
// have 'leaks'. The simulator does though.
// COV_NF_START
// We don't have leak checking on by default, so this won't be hit.
static void _GTMRunLeaks(void) {
// This is an atexit handler. It runs leaks for us to check if we are
// leaking anything in our tests.
const char* cExclusionsEnv = getenv("GTM_LEAKS_SYMBOLS_TO_IGNORE");
NSMutableString *exclusions = [NSMutableString string];
if (cExclusionsEnv) {
NSString *exclusionsEnv = [NSString stringWithUTF8String:cExclusionsEnv];
NSArray *exclusionsArray = [exclusionsEnv componentsSeparatedByString:@","];
NSString *exclusion;
NSCharacterSet *wcSet = [NSCharacterSet whitespaceCharacterSet];
GTM_FOREACH_OBJECT(exclusion, exclusionsArray) {
exclusion = [exclusion stringByTrimmingCharactersInSet:wcSet];
[exclusions appendFormat:@"-exclude \"%@\" ", exclusion];
}
}
NSString *string
= [NSString stringWithFormat:@"/usr/bin/leaks %@%d"
@"| /usr/bin/sed -e 's/Leak: /Leaks:0: warning: Leak /'",
exclusions, getpid()];
int ret = system([string UTF8String]);
if (ret) {
fprintf(stderr, "%s:%d: Error: Unable to run leaks. 'system' returned: %d",
__FILE__, __LINE__, ret);
fflush(stderr);
}
}
// COV_NF_END
static __attribute__((constructor)) void _GTMInstallLeaks(void) {
BOOL checkLeaks = YES;
#if !GTM_IPHONE_SDK
checkLeaks = GTMIsGarbageCollectionEnabled() ? NO : YES;
#endif // !GTM_IPHONE_SDK
if (checkLeaks) {
checkLeaks = getenv("GTM_ENABLE_LEAKS") ? YES : NO;
if (checkLeaks) {
// COV_NF_START
// We don't have leak checking on by default, so this won't be hit.
fprintf(stderr, "Leak Checking Enabled\n");
fflush(stderr);
int ret = atexit(&_GTMRunLeaks);
_GTMDevAssert(ret == 0,
@"Unable to install _GTMRunLeaks as an atexit handler (%d)",
errno);
// COV_NF_END
}
}
}
#endif // !GTM_IPHONE_DEVICE
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMSenTestCase.m | Objective-C | bsd | 11,707 |
//
// GTMUnitTestDevLog.h
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import <Foundation/Foundation.h>
// GTMUnitTestDevLog tracks what messages are logged to verify that you only
// log what you expect to log during the running of unittests. This allows you
// to log with impunity from your actual core implementations and still be able
// to find unexpected logs in your output when running unittests.
// In your unittests you tell GTMUnitTestDevLog what messages you expect your
// test to spit out, and it will cause any that don't match to appear as errors
// in your unittest run output. You can match on exact strings or standard
// regexps.
// Set GTM_SHOW_UNITTEST_DEVLOGS in the environment to show the logs that that
// are expected and encountered. Otherwise they aren't display to keep the
// unit test results easier to read.
@interface GTMUnitTestDevLog : NSObject
// Log a message
+ (void)log:(NSString*)format, ...;
+ (void)log:(NSString*)format args:(va_list)args;
// Turn tracking on/off
+ (void)enableTracking;
+ (void)disableTracking;
+ (BOOL)isTrackingEnabled;
// Note that you are expecting a string that has an exact match. No need to
// escape any pattern characters.
+ (void)expectString:(NSString *)format, ...;
// Note that you are expecting a pattern. Pattern characters that you want
// exact matches on must be escaped. See [GTMRegex escapedPatternForString].
// Patterns match across newlines (kGTMRegexOptionSupressNewlineSupport) making
// it easier to match output from the descriptions of NS collection types such
// as NSArray and NSDictionary.
+ (void)expectPattern:(NSString *)format, ...;
// Note that you are expecting exactly 'n' strings
+ (void)expect:(NSUInteger)n casesOfString:(NSString *)format, ...;
// Note that you are expecting exactly 'n' patterns
+ (void)expect:(NSUInteger)n casesOfPattern:(NSString*)format, ...;
+ (void)expect:(NSUInteger)n casesOfPattern:(NSString*)format args:(va_list)args;
// Call when you want to verify that you have matched all the logs you expect
// to match. If your unittests inherit from GTMTestcase (like they should) you
// will get this called for free.
+ (void)verifyNoMoreLogsExpected;
// Resets the expected logs so that you don't have anything expected.
// In general should not be needed, unless you have a variable logging case
// of some sort.
+ (void)resetExpectedLogs;
@end
// Does the same as GTMUnitTestDevLog, but the logs are only expected in debug.
// ie-the expect requests don't count in release builds.
@interface GTMUnitTestDevLogDebug : GTMUnitTestDevLog
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestDevLog.h | Objective-C | bsd | 3,167 |
//
// GTMUIKit+UnitTesting.h
//
// Code for making unit testing of graphics/UI easier. Generally you
// will only want to look at the macros:
// GTMAssertDrawingEqualToFile
// GTMAssertViewRepEqualToFile
// and the protocol GTMUnitTestViewDrawer. When using these routines
// make sure you are using device colors and not calibrated/generic colors
// or else your test graphics WILL NOT match across devices/graphics cards.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <UIKit/UIKit.h>
#import "GTMNSObject+UnitTesting.h"
@protocol GTMUnitTestViewDrawer;
// Fails when the |a1|'s drawing in an area |a2| does not equal the image file named |a3|.
// See the description of the GTMAssertViewRepEqualToFile macro
// to understand how |a3| is found and written out.
// See the description of the GTMUnitTestView for a better idea
// how the view works.
// Implemented as a macro to match the rest of the SenTest macros.
//
// Args:
// a1: The object that implements the GTMUnitTestViewDrawer protocol
// that is doing the drawing.
// a2: The size of the drawing
// a3: The name of the image file to check against.
// Do not include the extension
// a4: contextInfo to pass to drawer
// description: A format string as in the printf() function.
// Can be nil or an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
//
#define GTMAssertDrawingEqualToFile(a1, a2, a3, a4, description, ...) \
do { \
id<GTMUnitTestViewDrawer> a1Drawer = (a1); \
CGSize a2Size = (a2); \
NSString* a3String = (a3); \
void *a4ContextInfo = (a4); \
CGRect frame = CGRectMake(0, 0, a2Size.width, a2Size.height); \
GTMUnitTestView *view = [[[GTMUnitTestView alloc] initWithFrame:frame drawer:a1Drawer contextInfo:a4ContextInfo] autorelease]; \
GTMAssertObjectImageEqualToImageNamed(view, a3String, STComposeString(description, ##__VA_ARGS__)); \
} while(0)
// Category for making unit testing of graphics/UI easier.
// Allows you to take a state of a view. Supports both image and state.
// See GTMNSObject+UnitTesting.h for details.
@interface UIView (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
// Encodes the state of an object in a manner suitable for comparing against a master state file
// This enables us to determine whether the object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder;
// Returns whether gtm_unitTestEncodeState should recurse into subviews
//
// Returns:
// should gtm_unitTestEncodeState pick up subview state.
- (BOOL)gtm_shouldEncodeStateForSubviews;
@end
// Category to help UIImage testing. UIImage can be tested using
// GTMAssertObjectImageEqualToImageNamed macro, which automatically creates
// result images and diff images in case test fails.
@interface UIImage (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
@end
// A view that allows you to delegate out drawing using the formal
// GTMUnitTestViewDelegate protocol
// This is useful when writing up unit tests for visual elements.
// Your test will often end up looking like this:
// - (void)testFoo {
// GTMAssertDrawingEqualToFile(self, CGSizeMake(200, 200), @"Foo", nil, nil);
// }
// and your testSuite will also implement the unitTestViewDrawRect method to do
// it's actual drawing. The above creates a view of size 200x200 that draws
// it's content using |self|'s unitTestViewDrawRect method and compares it to
// the contents of the file Foo.tif to make sure it's valid
@interface GTMUnitTestView : UIView {
@private
id<GTMUnitTestViewDrawer> drawer_; // delegate for doing drawing (STRONG)
void* contextInfo_; // info passed in by user for them to use when drawing
}
// Create a GTMUnitTestView.
//
// Args:
// rect: the area to draw.
// drawer: the object that will do the drawing via the GTMUnitTestViewDrawer
// protocol
// contextInfo:
- (id)initWithFrame:(CGRect)frame drawer:(id<GTMUnitTestViewDrawer>)drawer contextInfo:(void*)contextInfo;
@end
/// \cond Protocols
// Formal protocol for doing unit testing of views. See description of
// GTMUnitTestView for details.
@protocol GTMUnitTestViewDrawer <NSObject>
// Draw the view. Equivalent to drawRect on a standard UIView.
//
// Args:
// rect: the area to draw.
- (void)gtm_unitTestViewDrawRect:(CGRect)rect contextInfo:(void*)contextInfo;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUIKit+UnitTesting.h | Objective-C | bsd | 5,069 |
//
// GTMAppKit+UnitTesting.m
//
// Categories for making unit testing of graphics/UI easier.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <AppKit/AppKit.h>
#import "GTMNSObject+UnitTesting.h"
// Categories for making unit testing of graphics/UI easier.
// Allows you to take a state/images of instances of AppKit classes.
// See GTMNSObject+UnitTesting.h for details.
@interface NSApplication (GTMUnitTestingAdditions)
@end
@interface NSWindow (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
@end
@interface NSControl (GTMUnitTestingAdditions)
@end
@interface NSTextField (GTMUnitTestingAdditions)
@end
@interface NSButton (GTMUnitTestingAdditions)
@end
@interface NSCell (GTMUnitTestingAdditions)
@end
@interface NSImage (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
@end
@interface NSMenu (GTMUnitTestingAdditions)
@end
@interface NSMenuItem (GTMUnitTestingAdditions)
@end
@interface NSTabView (GTMUnitTestingAdditions)
@end
@interface NSTabViewItem (GTMUnitTestingAdditions)
@end
@protocol GTMUnitTestViewDrawer;
// Fails when the |a1|'s drawing in an area |a2| does not equal the image file named |a3|.
// See the description of the -gtm_pathForImageNamed method
// to understand how |a3| is found and written out.
// See the description of the GTMUnitTestView for a better idea
// how the view works.
// Implemented as a macro to match the rest of the SenTest macros.
//
// Args:
// a1: The object that implements the GTMUnitTestViewDrawer protocol
// that is doing the drawing.
// a2: The size of the drawing
// a3: The name of the image file to check against.
// Do not include the extension
// a4: contextInfo to pass to drawer
// description: A format string as in the printf() function.
// Can be nil or an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
//
#define GTMAssertDrawingEqualToImageNamed(a1, a2, a3, a4, description, ...) \
do { \
id<GTMUnitTestViewDrawer> a1Drawer = (a1); \
NSSize a2Size = (a2); \
NSString* a3String = (a3); \
void *a4ContextInfo = (a4); \
NSRect frame = NSMakeRect(0, 0, a2Size.width, a2Size.height); \
GTMUnitTestView *view = [[[GTMUnitTestView alloc] initWithFrame:frame drawer:a1Drawer contextInfo:a4ContextInfo] autorelease]; \
GTMAssertObjectImageEqualToImageNamed(view, a3String, STComposeString(description, ##__VA_ARGS__)); \
} while(0)
// Category for making unit testing of graphics/UI easier.
// Allows you to take a state of a view. Supports both image and state.
// See NSObject+UnitTesting.h for details.
@interface NSView (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
// Returns whether unitTestEncodeState should recurse into subviews
//
// If you have "Full keyboard access" in the
// Keyboard & Mouse > Keyboard Shortcuts preferences pane set to "Text boxes
// and Lists only" that Apple adds a set of subviews to NSTextFields. So in the
// case of NSTextFields we don't want to recurse into their subviews. There may
// be other cases like this, so instead of specializing unitTestEncodeState: to
// look for NSTextFields, NSTextFields will just not allow us to recurse into
// their subviews.
//
// Returns:
// should unitTestEncodeState pick up subview state.
- (BOOL)gtm_shouldEncodeStateForSubviews;
@end
// A view that allows you to delegate out drawing using the formal
// GTMUnitTestViewDelegate protocol
// This is useful when writing up unit tests for visual elements.
// Your test will often end up looking like this:
// - (void)testFoo {
// GTMAssertDrawingEqualToFile(self, NSMakeSize(200, 200), @"Foo", nil, nil);
// }
// and your testSuite will also implement the unitTestViewDrawRect method to do
// it's actual drawing. The above creates a view of size 200x200 that draws
// it's content using |self|'s unitTestViewDrawRect method and compares it to
// the contents of the file Foo.tif to make sure it's valid
@interface GTMUnitTestView : NSView {
@private
id<GTMUnitTestViewDrawer> drawer_; // delegate for doing drawing (STRONG)
void* contextInfo_; // info passed in by user for them to use when drawing
}
// Create a GTMUnitTestView.
//
// Args:
// rect: the area to draw.
// drawer: the object that will do the drawing via the GTMUnitTestViewDrawer
// protocol
// contextInfo:
- (id)initWithFrame:(NSRect)frame drawer:(id<GTMUnitTestViewDrawer>)drawer contextInfo:(void*)contextInfo;
@end
/// \cond Protocols
// Formal protocol for doing unit testing of views. See description of
// GTMUnitTestView for details.
@protocol GTMUnitTestViewDrawer <NSObject>
// Draw the view. Equivalent to drawRect on a standard NSView.
//
// Args:
// rect: the area to draw.
- (void)gtm_unitTestViewDrawRect:(NSRect)rect contextInfo:(void*)contextInfo;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMAppKit+UnitTesting.h | Objective-C | bsd | 5,450 |
//
// GTMAppKit+UnitTesting.m
//
// Categories for making unit testing of graphics/UI easier.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import "GTMAppKit+UnitTesting.h"
#import "GTMGeometryUtils.h"
#import "GTMMethodCheck.h"
#import "GTMGarbageCollection.h"
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
#define ENCODE_NSINTEGER(coder, i, key) [(coder) encodeInt:(i) forKey:(key)]
#else
#define ENCODE_NSINTEGER(coder, i, key) [(coder) encodeInteger:(i) forKey:(key)]
#endif
@implementation NSApplication (GMUnitTestingAdditions)
GTM_METHOD_CHECK(NSObject, gtm_unitTestEncodeState:);
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
ENCODE_NSINTEGER(inCoder, [[self mainWindow] windowNumber], @"ApplicationMainWindow");
// Descend down into the windows allowing them to store their state
NSWindow *window = nil;
int i = 0;
GTM_FOREACH_OBJECT(window, [self windows]) {
if ([window isVisible]) {
// Only record visible windows because invisible windows may be closing on us
// This appears to happen differently in 64 bit vs 32 bit, and items
// in the window may hold an extra retain count for a while until the
// event loop is spun. To avoid all this, we just don't record non
// visible windows.
// See rdar://5851458 for details.
[inCoder encodeObject:window forKey:[NSString stringWithFormat:@"Window %d", i]];
i = i + 1;
}
}
// and encode the menu bar
NSMenu *mainMenu = [self mainMenu];
if (mainMenu) {
[inCoder encodeObject:mainMenu forKey:@"MenuBar"];
}
}
@end
@implementation NSWindow (GMUnitTestingAdditions)
- (CGImageRef)gtm_unitTestImage {
return [[[self contentView] superview] gtm_unitTestImage];
}
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeObject:[self title] forKey:@"WindowTitle"];
[inCoder encodeBool:[self isVisible] forKey:@"WindowIsVisible"];
// Do not record if window is key, because users running unit tests
// and clicking around to other apps, could change this mid test causing
// issues.
// [inCoder encodeBool:[self isKeyWindow] forKey:@"WindowIsKey"];
[inCoder encodeBool:[self isMainWindow] forKey:@"WindowIsMain"];
[inCoder encodeObject:[self contentView] forKey:@"WindowContent"];
}
@end
@implementation NSControl (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeObject:[self class] forKey:@"ControlType"];
[inCoder encodeObject:[self objectValue] forKey:@"ControlValue"];
[inCoder encodeObject:[self selectedCell] forKey:@"ControlSelectedCell"];
ENCODE_NSINTEGER(inCoder, [self tag], @"ControlTag");
[inCoder encodeBool:[self isEnabled] forKey:@"ControlIsEnabled"];
}
@end
@implementation NSButton (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
NSString *alternateTitle = [self alternateTitle];
if (alternateTitle) {
[inCoder encodeObject:alternateTitle forKey:@"ButtonAlternateTitle"];
}
}
@end
@implementation NSTextField (GTMUnitTestingAdditions)
- (BOOL)gtm_shouldEncodeStateForSubviews {
return NO;
}
@end
@implementation NSCell (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
BOOL isImageCell = NO;
if ([self hasValidObjectValue]) {
id val = [self objectValue];
[inCoder encodeObject:val forKey:@"CellValue"];
isImageCell = [val isKindOfClass:[NSImage class]];
}
if (!isImageCell) {
// Image cells have a title that includes addresses that aren't going
// to be constant, so we don't encode them. All the info we need
// is going to be in the CellValue encoding.
[inCoder encodeObject:[self title] forKey:@"CellTitle"];
}
ENCODE_NSINTEGER(inCoder, [self state], @"CellState");
ENCODE_NSINTEGER(inCoder, [self tag], @"CellTag");
}
@end
@implementation NSImage (GTMUnitTestingAdditions)
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeObject:NSStringFromSize([self size]) forKey:@"ImageSize"];
[inCoder encodeObject:[self name] forKey:@"ImageName"];
}
- (CGImageRef)gtm_unitTestImage {
// Create up a context
NSSize size = [self size];
NSRect rect = GTMNSRectOfSize(size);
CGSize cgSize = GTMNSSizeToCGSize(size);
CGContextRef contextRef = GTMCreateUnitTestBitmapContextOfSizeWithData(cgSize,
NULL);
NSGraphicsContext *bitmapContext
= [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];
_GTMDevAssert(bitmapContext, @"Couldn't create ns bitmap context");
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:bitmapContext];
[self drawInRect:rect fromRect:rect operation:NSCompositeCopy fraction:1.0];
CGImageRef image = CGBitmapContextCreateImage(contextRef);
CFRelease(contextRef);
[NSGraphicsContext restoreGraphicsState];
return (CGImageRef)GTMCFAutorelease(image);
}
@end
@implementation NSMenu (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
// Hack here to work around
// rdar://5881796 Application menu item title wrong when accessed programatically
// which causes us to have different results on x86_64 vs x386.
// Hack is braced intentionally. We don't record the title of the
// "application" menu or it's menu title because they are wrong on 32 bit.
// They appear to work right on 64bit.
{
NSMenu *mainMenu = [NSApp mainMenu];
NSMenu *appleMenu = [[mainMenu itemAtIndex:0] submenu];
if (![self isEqual:appleMenu]) {
[inCoder encodeObject:[self title] forKey:@"MenuTitle"];
}
}
// Descend down into the menuitems allowing them to store their state
NSMenuItem *menuItem = nil;
int i = 0;
GTM_FOREACH_OBJECT(menuItem, [self itemArray]) {
[inCoder encodeObject:menuItem
forKey:[NSString stringWithFormat:@"MenuItem %d", i]];
++i;
}
}
@end
@implementation NSMenuItem (GTMUnitTestingAdditions)
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
// Hack here to work around
// rdar://5881796 Application menu item title wrong when accessed programatically
// which causes us to have different results on x86_64 vs x386.
// See comment above.
{
NSMenu *mainMenu = [NSApp mainMenu];
NSMenuItem *appleMenuItem = [mainMenu itemAtIndex:0];
if (![self isEqual:appleMenuItem]) {
[inCoder encodeObject:[self title] forKey:@"MenuItemTitle"];
}
}
[inCoder encodeObject:[self keyEquivalent] forKey:@"MenuItemKeyEquivalent"];
[inCoder encodeBool:[self isSeparatorItem] forKey:@"MenuItemIsSeparator"];
ENCODE_NSINTEGER(inCoder, [self state], @"MenuItemState");
[inCoder encodeBool:[self isEnabled] forKey:@"MenuItemIsEnabled"];
[inCoder encodeBool:[self isAlternate] forKey:@"MenuItemIsAlternate"];
[inCoder encodeObject:[self toolTip] forKey:@"MenuItemTooltip"];
ENCODE_NSINTEGER(inCoder, [self tag], @"MenuItemTag");
ENCODE_NSINTEGER(inCoder, [self indentationLevel], @"MenuItemIndentationLevel");
// Do our submenu if neccessary
if ([self hasSubmenu]) {
[inCoder encodeObject:[self submenu] forKey:@"MenuItemSubmenu"];
}
}
@end
@implementation NSTabView (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
NSTabViewItem *tab = nil;
int i = 0;
GTM_FOREACH_OBJECT(tab, [self tabViewItems]) {
NSString *key = [NSString stringWithFormat:@"TabItem %d", i];
[inCoder encodeObject:tab forKey:key];
i = i + 1;
}
}
@end
@implementation NSTabViewItem (GTMUnitTestingAdditions)
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeObject:[self label] forKey:@"TabLabel"];
[inCoder encodeObject:[self view] forKey:@"TabView"];
}
@end
// A view that allows you to delegate out drawing using the formal
// GTMUnitTestViewDelegate protocol above. This is useful when writing up unit
// tests for visual elements.
// Your test will often end up looking like this:
// - (void)testFoo {
// GTMAssertDrawingEqualToFile(self, NSMakeSize(200, 200), @"Foo", nil, nil);
// }
// and your testSuite will also implement the unitTestViewDrawRect method to do
// it's actual drawing. The above creates a view of size 200x200 that draws
// it's content using |self|'s unitTestViewDrawRect method and compares it to
// the contents of the file Foo.tif to make sure it's valid
@implementation GTMUnitTestView
- (id)initWithFrame:(NSRect)frame
drawer:(id<GTMUnitTestViewDrawer>)drawer
contextInfo:(void*)contextInfo {
self = [super initWithFrame:frame];
if (self != nil) {
drawer_ = [drawer retain];
contextInfo_ = contextInfo;
}
return self;
}
- (void)dealloc {
[drawer_ release];
[super dealloc];
}
- (void)drawRect:(NSRect)rect {
[drawer_ gtm_unitTestViewDrawRect:rect contextInfo:contextInfo_];
}
@end
@implementation NSView (GTMUnitTestingAdditions)
// Returns an image containing a representation of the object
// suitable for use in comparing against a master image.
// Does all of it's drawing with smoothfonts and antialiasing off
// to avoid issues with font smoothing settings and antialias differences
// between ppc and x86.
//
// Returns:
// an image of the object
- (CGImageRef)gtm_unitTestImage {
// Create up a context
NSRect bounds = [self bounds];
CGSize cgSize = GTMNSSizeToCGSize(bounds.size);
CGContextRef contextRef = GTMCreateUnitTestBitmapContextOfSizeWithData(cgSize,
NULL);
NSGraphicsContext *bitmapContext
= [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];
_GTMDevAssert(bitmapContext, @"Couldn't create ns bitmap context");
// Save our state and turn off font smoothing and antialias.
CGContextSaveGState(contextRef);
CGContextSetShouldSmoothFonts(contextRef, false);
CGContextSetShouldAntialias(contextRef, false);
[self displayRectIgnoringOpacity:bounds inContext:bitmapContext];
CGImageRef image = CGBitmapContextCreateImage(contextRef);
CFRelease(contextRef);
return (CGImageRef)GTMCFAutorelease(image);
}
// Returns whether gtm_unitTestEncodeState should recurse into subviews
// of a particular view.
// If you have "Full keyboard access" in the
// Keyboard & Mouse > Keyboard Shortcuts preferences pane set to "Text boxes
// and Lists only" that Apple adds a set of subviews to NSTextFields. So in the
// case of NSTextFields we don't want to recurse into their subviews. There may
// be other cases like this, so instead of specializing gtm_unitTestEncodeState: to
// look for NSTextFields, NSTextFields will just not allow us to recurse into
// their subviews.
//
// Returns:
// should gtm_unitTestEncodeState pick up subview state.
- (BOOL)gtm_shouldEncodeStateForSubviews {
return YES;
}
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeBool:[self isHidden] forKey:@"ViewIsHidden"];
[inCoder encodeObject:[self toolTip] forKey:@"ViewToolTip"];
NSArray *supportedAttrs = [self accessibilityAttributeNames];
if ([supportedAttrs containsObject:NSAccessibilityHelpAttribute]) {
NSString *help
= [self accessibilityAttributeValue:NSAccessibilityHelpAttribute];
[inCoder encodeObject:help forKey:@"ViewAccessibilityHelp"];
}
if ([supportedAttrs containsObject:NSAccessibilityDescriptionAttribute]) {
NSString *description
= [self accessibilityAttributeValue:NSAccessibilityDescriptionAttribute];
[inCoder encodeObject:description forKey:@"ViewAccessibilityDescription"];
}
NSMenu *menu = [self menu];
if (menu) {
[inCoder encodeObject:menu forKey:@"ViewMenu"];
}
if ([self gtm_shouldEncodeStateForSubviews]) {
NSView *subview = nil;
int i = 0;
GTM_FOREACH_OBJECT(subview, [self subviews]) {
[inCoder encodeObject:subview forKey:[NSString stringWithFormat:@"ViewSubView %d", i]];
i = i + 1;
}
}
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMAppKit+UnitTesting.m | Objective-C | bsd | 14,698 |
//
// GTMUIKit+UnitTesting.m
//
// Category for making unit testing of graphics/UI easier.
// Allows you to save a view out to a image file, and compare a view
// with a previously stored representation to make sure it hasn't changed.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMUIKit+UnitTesting.h"
#import "GTMCALayer+UnitTesting.h"
#import "GTMDefines.h"
#if !GTM_IPHONE_SDK
#error This file is for iPhone use only
#endif // GTM_IPHONE_SDK
// A view that allows you to delegate out drawing using the formal
// GTMUnitTestViewDelegate protocol above. This is useful when writing up unit
// tests for visual elements.
// Your test will often end up looking like this:
// - (void)testFoo {
// GTMAssertDrawingEqualToFile(self, CGSizeMake(200, 200), @"Foo", nil, nil);
// }
// and your testSuite will also implement the unitTestViewDrawRect method to do
// it's actual drawing. The above creates a view of size 200x200 that draws
// it's content using |self|'s unitTestViewDrawRect method and compares it to
// the contents of the file Foo.tif to make sure it's valid
@implementation GTMUnitTestView
- (id)initWithFrame:(CGRect)frame
drawer:(id<GTMUnitTestViewDrawer>)drawer
contextInfo:(void*)contextInfo{
self = [super initWithFrame:frame];
if (self != nil) {
drawer_ = [drawer retain];
contextInfo_ = contextInfo;
}
return self;
}
- (void)dealloc {
[drawer_ release];
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
[drawer_ gtm_unitTestViewDrawRect:rect contextInfo:contextInfo_];
}
@end
@implementation UIView (GTMUnitTestingAdditions)
// Returns an image containing a representation of the object
// suitable for use in comparing against a master image.
// NB this means that all colors should be from "NSDevice" color space
// Does all of it's drawing with smoothfonts and antialiasing off
// to avoid issues with font smoothing settings and antialias differences
// between ppc and x86.
//
// Returns:
// an image of the object
- (CGImageRef)gtm_unitTestImage {
CALayer* layer = [self layer];
return [layer gtm_unitTestImage];
}
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeBool:[self isHidden] forKey:@"ViewIsHidden"];
CALayer* layer = [self layer];
if (layer) {
[layer gtm_unitTestEncodeState:inCoder];
}
if ([self gtm_shouldEncodeStateForSubviews]) {
int i = 0;
for (UIView *subview in [self subviews]) {
[inCoder encodeObject:subview
forKey:[NSString stringWithFormat:@"ViewSubView %d", i]];
i++;
}
}
}
// Returns whether gtm_unitTestEncodeState should recurse into subviews
//
// Returns:
// should gtm_unitTestEncodeState pick up subview state.
- (BOOL)gtm_shouldEncodeStateForSubviews {
return YES;
}
- (BOOL)gtm_shouldEncodeStateForSublayersOfLayer:(CALayer*)layer {
return NO;
}
@end
@implementation UIImage (GTMUnitTestingAdditions)
- (CGImageRef)gtm_unitTestImage {
return [self CGImage];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUIKit+UnitTesting.m | Objective-C | bsd | 3,861 |
//
// GTMUnitTestingTest.h
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <AppKit/AppKit.h>
// GTMUnitTestingTestController controller so that initWithWindowNibName can
// find the appropriate bundle to load our nib from. See [GTMUnitTestingTest
// -testUnitTestingFramework] for more info
@interface GTMUnitTestingTestController : NSWindowController {
IBOutlet NSTextField *field_;
}
- (NSTextField *)textField;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestingTest.h | Objective-C | bsd | 989 |
//
// GTMTestHTTPServer.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMTestHTTPServer.h"
#import "GTMHTTPServer.h"
#import "GTMRegex.h"
static NSArray *GetSubPatternsOfFirstStringMatchedByPattern(NSString *stringToSearch,
NSString *pattern) {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
NSString *firstMatch = [regex firstSubStringMatchedInString:stringToSearch];
NSArray *subPatterns = [regex subPatternsOfString:firstMatch];
return subPatterns;
}
@implementation GTMTestHTTPServer
- (id)initWithDocRoot:(NSString *)docRoot {
self = [super init];
if (self) {
docRoot_ = [docRoot copy];
server_ = [[GTMHTTPServer alloc] initWithDelegate:self];
NSError *error = nil;
if ((docRoot == nil) || (![server_ start:&error])) {
_GTMDevLog(@"Failed to start up the webserver (docRoot='%@', error=%@)",
docRoot_, error);
[self release];
return nil;
}
}
return self;
}
- (void)dealloc {
[docRoot_ release];
[server_ release];
[super dealloc];
}
- (uint16_t)port {
return [server_ port];
}
- (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server
handleRequest:(GTMHTTPRequestMessage *)request {
_GTMDevAssert(server == server_, @"how'd we get a different server?!");
UInt32 resultStatus = 0;
NSData *data = nil;
// clients should treat dates as opaque, generally
NSString *modifiedDate = @"thursday";
NSString *postString = @"";
NSData *postData = [request body];
if ([postData length] > 0) {
postString = [[[NSString alloc] initWithData:postData
encoding:NSUTF8StringEncoding] autorelease];
}
NSDictionary *allHeaders = [request allHeaderFieldValues];
NSString *ifModifiedSince = [allHeaders objectForKey:@"If-Modified-Since"];
NSString *authorization = [allHeaders objectForKey:@"Authorization"];
NSString *path = [[request URL] absoluteString];
if ([path hasSuffix:@".auth"]) {
if (![authorization isEqualToString:@"GoogleLogin auth=GoodAuthToken"]) {
GTMHTTPResponseMessage *response =
[GTMHTTPResponseMessage emptyResponseWithCode:401];
return response;
} else {
path = [path substringToIndex:[path length] - 5];
}
}
NSString *overrideHeader = [allHeaders objectForKey:@"X-HTTP-Method-Override"];
NSString *httpCommand = [request method];
if ([httpCommand isEqualToString:@"POST"] &&
[overrideHeader length] > 1) {
httpCommand = overrideHeader;
}
NSArray *searchResult = nil;
if ([path hasSuffix:@"/accounts/ClientLogin"]) {
// it's a sign-in attempt; it's good unless the password is "bad" or
// "captcha"
// use regular expression to find the password
NSString *password = @"";
searchResult = GetSubPatternsOfFirstStringMatchedByPattern(path, @"Passwd=([^&\n]*)");
if ([searchResult count] == 2) {
password = [searchResult objectAtIndex:1];
}
if ([password isEqualToString:@"bad"]) {
resultStatus = 403;
} else if ([password isEqualToString:@"captcha"]) {
NSString *loginToken = @"";
NSString *loginCaptcha = @"";
searchResult = GetSubPatternsOfFirstStringMatchedByPattern(postString, @"logintoken=([^&\n]*)");
if ([searchResult count] == 2) {
loginToken = [searchResult objectAtIndex:1];
}
searchResult = GetSubPatternsOfFirstStringMatchedByPattern(postString, @"logincaptcha=([^&\n]*)");
if ([searchResult count] == 2) {
loginCaptcha = [searchResult objectAtIndex:1];
}
if ([loginToken isEqualToString:@"CapToken"] &&
[loginCaptcha isEqualToString:@"good"]) {
resultStatus = 200;
} else {
// incorrect captcha token or answer provided
resultStatus = 403;
}
} else {
// valid username/password
resultStatus = 200;
}
} else if ([httpCommand isEqualToString:@"DELETE"]) {
// it's an object delete; read and return empty data
resultStatus = 200;
} else {
// queries that have something like "?status=456" should fail with the
// status code
searchResult = GetSubPatternsOfFirstStringMatchedByPattern(path, @"status=([0-9]+)");
if ([searchResult count] == 2) {
resultStatus = [[searchResult objectAtIndex:1] intValue];
} else if ([ifModifiedSince isEqualToString:modifiedDate]) {
resultStatus = 304;
} else {
NSString *docPath = [docRoot_ stringByAppendingPathComponent:path];
data = [NSData dataWithContentsOfFile:docPath];
if (data) {
resultStatus = 200;
} else {
resultStatus = 404;
}
}
}
GTMHTTPResponseMessage *response =
[GTMHTTPResponseMessage responseWithBody:data
contentType:@"text/plain"
statusCode:resultStatus];
[response setValue:modifiedDate forHeaderField:@"Last-Modified"];
[response setValue:[NSString stringWithFormat:@"TestCookie=%@", [path lastPathComponent]]
forHeaderField:@"Set-Cookie"];
return response;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMTestHTTPServer.m | Objective-C | bsd | 5,743 |
//
// GTMSenTestCase.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
// Portions of this file fall under the following license, marked with
// SENTE_BEGIN - SENTE_END
//
// Copyright (c) 1997-2005, Sen:te (Sente SA). All rights reserved.
//
// Use of this source code is governed by the following license:
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL Sente SA OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Note: this license is equivalent to the FreeBSD license.
//
// This notice may not be removed from this file.
// Some extra test case macros that would have been convenient for SenTestingKit
// to provide. I didn't stick GTM in front of the Macro names, so that they would
// be easy to remember.
#import "GTMDefines.h"
#if (!GTM_IPHONE_SDK)
#import <SenTestingKit/SenTestingKit.h>
#else
#import <Foundation/Foundation.h>
#ifdef __cplusplus
extern "C" {
#endif
NSString *STComposeString(NSString *, ...);
#ifdef __cplusplus
}
#endif
#endif // !GTM_IPHONE_SDK
// Generates a failure when a1 != noErr
// Args:
// a1: should be either an OSErr or an OSStatus
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNoErr(a1, description, ...) \
do { \
@try {\
OSStatus a1value = (a1); \
if (a1value != noErr) { \
NSString *_expression = [NSString stringWithFormat:@"Expected noErr, got %ld for (%s)", a1value, #a1]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat:@"(%s) == noErr fails", #a1] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 != a2
// Args:
// a1: received value. Should be either an OSErr or an OSStatus
// a2: expected value. Should be either an OSErr or an OSStatus
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertErr(a1, a2, description, ...) \
do { \
@try {\
OSStatus a1value = (a1); \
OSStatus a2value = (a2); \
if (a1value != a2value) { \
NSString *_expression = [NSString stringWithFormat:@"Expected %s(%ld) but got %ld for (%s)", #a2, a2value, a1value, #a1]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat:@"(%s) == (%s) fails", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is NULL
// Args:
// a1: should be a pointer (use STAssertNotNil for an object)
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNotNULL(a1, description, ...) \
do { \
@try {\
const void* a1value = (a1); \
if (a1value == NULL) { \
NSString *_expression = [NSString stringWithFormat:@"(%s) != NULL", #a1]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat:@"(%s) != NULL fails", #a1] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is not NULL
// Args:
// a1: should be a pointer (use STAssertNil for an object)
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNULL(a1, description, ...) \
do { \
@try {\
const void* a1value = (a1); \
if (a1value != NULL) { \
NSString *_expression = [NSString stringWithFormat:@"(%s) == NULL", #a1]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat:@"(%s) == NULL fails", #a1] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is equal to a2. This test is for C scalars,
// structs and unions.
// Args:
// a1: argument 1
// a2: argument 2
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNotEquals(a1, a2, description, ...) \
do { \
@try {\
if (@encode(__typeof__(a1)) != @encode(__typeof__(a2))) { \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:[@"Type mismatch -- " stringByAppendingString:STComposeString(description, ##__VA_ARGS__)]]]; \
} else { \
__typeof__(a1) a1value = (a1); \
__typeof__(a2) a2value = (a2); \
NSValue *a1encoded = [NSValue value:&a1value withObjCType:@encode(__typeof__(a1))]; \
NSValue *a2encoded = [NSValue value:&a2value withObjCType:@encode(__typeof__(a2))]; \
if ([a1encoded isEqualToValue:a2encoded]) { \
NSString *_expression = [NSString stringWithFormat:@"(%s) != (%s)", #a1, #a2]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat:@"(%s) != (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is equal to a2. This test is for objects.
// Args:
// a1: argument 1. object.
// a2: argument 2. object.
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNotEqualObjects(a1, a2, desc, ...) \
do { \
@try {\
id a1value = (a1); \
id a2value = (a2); \
if ( (@encode(__typeof__(a1value)) == @encode(id)) && \
(@encode(__typeof__(a2value)) == @encode(id)) && \
![(id)a1value isEqual:(id)a2value] ) continue; \
NSString *_expression = [NSString stringWithFormat:@"%s('%@') != %s('%@')", #a1, [a1 description], #a2, [a2 description]]; \
if (desc) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(desc, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) != (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(desc, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is not 'op' to a2. This test is for C scalars.
// Args:
// a1: argument 1
// a2: argument 2
// op: operation
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertOperation(a1, a2, op, description, ...) \
do { \
@try {\
if (@encode(__typeof__(a1)) != @encode(__typeof__(a2))) { \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:[@"Type mismatch -- " stringByAppendingString:STComposeString(description, ##__VA_ARGS__)]]]; \
} else { \
__typeof__(a1) a1value = (a1); \
__typeof__(a2) a2value = (a2); \
if (!(a1value op a2value)) { \
double a1DoubleValue = a1value; \
double a2DoubleValue = a2value; \
NSString *_expression = [NSString stringWithFormat:@"%s (%lg) %s %s (%lg)", #a1, a1DoubleValue, #op, #a2, a2DoubleValue]; \
if (description) { \
_expression = [NSString stringWithFormat:@"%@: %@", _expression, STComposeString(description, ##__VA_ARGS__)]; \
} \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:_expression]]; \
} \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException \
failureInRaise:[NSString stringWithFormat:@"(%s) %s (%s)", #a1, #op, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when a1 is not > a2. This test is for C scalars.
// Args:
// a1: argument 1
// a2: argument 2
// op: operation
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertGreaterThan(a1, a2, description, ...) \
STAssertOperation(a1, a2, >, description, ##__VA_ARGS__)
// Generates a failure when a1 is not >= a2. This test is for C scalars.
// Args:
// a1: argument 1
// a2: argument 2
// op: operation
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertGreaterThanOrEqual(a1, a2, description, ...) \
STAssertOperation(a1, a2, >=, description, ##__VA_ARGS__)
// Generates a failure when a1 is not < a2. This test is for C scalars.
// Args:
// a1: argument 1
// a2: argument 2
// op: operation
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertLessThan(a1, a2, description, ...) \
STAssertOperation(a1, a2, <, description, ##__VA_ARGS__)
// Generates a failure when a1 is not <= a2. This test is for C scalars.
// Args:
// a1: argument 1
// a2: argument 2
// op: operation
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertLessThanOrEqual(a1, a2, description, ...) \
STAssertOperation(a1, a2, <=, description, ##__VA_ARGS__)
// Generates a failure when string a1 is not equal to string a2. This call
// differs from STAssertEqualObjects in that strings that are different in
// composition (precomposed vs decomposed) will compare equal if their final
// representation is equal.
// ex O + umlaut decomposed is the same as O + umlaut composed.
// Args:
// a1: string 1
// a2: string 2
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertEqualStrings(a1, a2, description, ...) \
do { \
@try {\
id a1value = (a1); \
id a2value = (a2); \
if (a1value == a2value) continue; \
if ([a1value isKindOfClass:[NSString class]] && \
[a2value isKindOfClass:[NSString class]] && \
[a1value compare:a2value options:0] == NSOrderedSame) continue; \
[self failWithException:[NSException failureInEqualityBetweenObject: a1value \
andObject: a2value \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when string a1 is equal to string a2. This call
// differs from STAssertEqualObjects in that strings that are different in
// composition (precomposed vs decomposed) will compare equal if their final
// representation is equal.
// ex O + umlaut decomposed is the same as O + umlaut composed.
// Args:
// a1: string 1
// a2: string 2
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNotEqualStrings(a1, a2, description, ...) \
do { \
@try {\
id a1value = (a1); \
id a2value = (a2); \
if ([a1value isKindOfClass:[NSString class]] && \
[a2value isKindOfClass:[NSString class]] && \
[a1value compare:a2value options:0] != NSOrderedSame) continue; \
[self failWithException:[NSException failureInEqualityBetweenObject: a1value \
andObject: a2value \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) != (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when c-string a1 is not equal to c-string a2.
// Args:
// a1: string 1
// a2: string 2
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertEqualCStrings(a1, a2, description, ...) \
do { \
@try {\
const char* a1value = (a1); \
const char* a2value = (a2); \
if (a1value == a2value) continue; \
if (strcmp(a1value, a2value) == 0) continue; \
[self failWithException:[NSException failureInEqualityBetweenObject: [NSString stringWithUTF8String:a1value] \
andObject: [NSString stringWithUTF8String:a2value] \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
// Generates a failure when c-string a1 is equal to c-string a2.
// Args:
// a1: string 1
// a2: string 2
// description: A format string as in the printf() function. Can be nil or
// an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
#define STAssertNotEqualCStrings(a1, a2, description, ...) \
do { \
@try {\
const char* a1value = (a1); \
const char* a2value = (a2); \
if (strcmp(a1value, a2value) != 0) continue; \
[self failWithException:[NSException failureInEqualityBetweenObject: [NSString stringWithUTF8String:a1value] \
andObject: [NSString stringWithUTF8String:a2value] \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) != (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
#if GTM_IPHONE_SDK
// SENTE_BEGIN
/*" Generates a failure when !{ [a1 isEqualTo:a2] } is false
(or one is nil and the other is not).
_{a1 The object on the left.}
_{a2 The object on the right.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertEqualObjects(a1, a2, description, ...) \
do { \
@try {\
id a1value = (a1); \
id a2value = (a2); \
if (a1value == a2value) continue; \
if ( (@encode(__typeof__(a1value)) == @encode(id)) && \
(@encode(__typeof__(a2value)) == @encode(id)) && \
[(id)a1value isEqual: (id)a2value] ) continue; \
[self failWithException:[NSException failureInEqualityBetweenObject: a1value \
andObject: a2value \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
/*" Generates a failure when a1 is not equal to a2. This test is for
C scalars, structs and unions.
_{a1 The argument on the left.}
_{a2 The argument on the right.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertEquals(a1, a2, description, ...) \
do { \
@try {\
if (@encode(__typeof__(a1)) != @encode(__typeof__(a2))) { \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:[@"Type mismatch -- " stringByAppendingString:STComposeString(description, ##__VA_ARGS__)]]]; \
} else { \
__typeof__(a1) a1value = (a1); \
__typeof__(a2) a2value = (a2); \
NSValue *a1encoded = [NSValue value:&a1value withObjCType: @encode(__typeof__(a1))]; \
NSValue *a2encoded = [NSValue value:&a2value withObjCType: @encode(__typeof__(a2))]; \
if (![a1encoded isEqualToValue:a2encoded]) { \
[self failWithException:[NSException failureInEqualityBetweenValue: a1encoded \
andValue: a2encoded \
withAccuracy: nil \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
#define STAbsoluteDifference(left,right) (MAX(left,right)-MIN(left,right))
/*" Generates a failure when a1 is not equal to a2 within + or - accuracy is false.
This test is for scalars such as floats and doubles where small differences
could make these items not exactly equal, but also works for all scalars.
_{a1 The scalar on the left.}
_{a2 The scalar on the right.}
_{accuracy The maximum difference between a1 and a2 for these values to be
considered equal.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertEqualsWithAccuracy(a1, a2, accuracy, description, ...) \
do { \
@try {\
if (@encode(__typeof__(a1)) != @encode(__typeof__(a2))) { \
[self failWithException:[NSException failureInFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:[@"Type mismatch -- " stringByAppendingString:STComposeString(description, ##__VA_ARGS__)]]]; \
} else { \
__typeof__(a1) a1value = (a1); \
__typeof__(a2) a2value = (a2); \
__typeof__(accuracy) accuracyvalue = (accuracy); \
if (STAbsoluteDifference(a1value, a2value) > accuracyvalue) { \
NSValue *a1encoded = [NSValue value:&a1value withObjCType:@encode(__typeof__(a1))]; \
NSValue *a2encoded = [NSValue value:&a2value withObjCType:@encode(__typeof__(a2))]; \
NSValue *accuracyencoded = [NSValue value:&accuracyvalue withObjCType:@encode(__typeof__(accuracy))]; \
[self failWithException:[NSException failureInEqualityBetweenValue: a1encoded \
andValue: a2encoded \
withAccuracy: accuracyencoded \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == (%s)", #a1, #a2] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
/*" Generates a failure unconditionally.
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STFail(description, ...) \
[self failWithException:[NSException failureInFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]
/*" Generates a failure when a1 is not nil.
_{a1 An object.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertNil(a1, description, ...) \
do { \
@try {\
id a1value = (a1); \
if (a1value != nil) { \
NSString *_a1 = [NSString stringWithUTF8String: #a1]; \
NSString *_expression = [NSString stringWithFormat:@"((%@) == nil)", _a1]; \
[self failWithException:[NSException failureInCondition: _expression \
isTrue: NO \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) == nil fails", #a1] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
/*" Generates a failure when a1 is nil.
_{a1 An object.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertNotNil(a1, description, ...) \
do { \
@try {\
id a1value = (a1); \
if (a1value == nil) { \
NSString *_a1 = [NSString stringWithUTF8String: #a1]; \
NSString *_expression = [NSString stringWithFormat:@"((%@) != nil)", _a1]; \
[self failWithException:[NSException failureInCondition: _expression \
isTrue: NO \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
}\
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) != nil fails", #a1] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while(0)
/*" Generates a failure when expression evaluates to false.
_{expr The expression that is tested.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertTrue(expr, description, ...) \
do { \
BOOL _evaluatedExpression = (expr);\
if (!_evaluatedExpression) {\
NSString *_expression = [NSString stringWithUTF8String: #expr];\
[self failWithException:[NSException failureInCondition: _expression \
isTrue: NO \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} while (0)
/*" Generates a failure when expression evaluates to false and in addition will
generate error messages if an exception is encountered.
_{expr The expression that is tested.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertTrueNoThrow(expr, description, ...) \
do { \
@try {\
BOOL _evaluatedExpression = (expr);\
if (!_evaluatedExpression) {\
NSString *_expression = [NSString stringWithUTF8String: #expr];\
[self failWithException:[NSException failureInCondition: _expression \
isTrue: NO \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"(%s) ", #expr] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while (0)
/*" Generates a failure when the expression evaluates to true.
_{expr The expression that is tested.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertFalse(expr, description, ...) \
do { \
BOOL _evaluatedExpression = (expr);\
if (_evaluatedExpression) {\
NSString *_expression = [NSString stringWithUTF8String: #expr];\
[self failWithException:[NSException failureInCondition: _expression \
isTrue: YES \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} while (0)
/*" Generates a failure when the expression evaluates to true and in addition
will generate error messages if an exception is encountered.
_{expr The expression that is tested.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertFalseNoThrow(expr, description, ...) \
do { \
@try {\
BOOL _evaluatedExpression = (expr);\
if (_evaluatedExpression) {\
NSString *_expression = [NSString stringWithUTF8String: #expr];\
[self failWithException:[NSException failureInCondition: _expression \
isTrue: YES \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} \
} \
@catch (id anException) {\
[self failWithException:[NSException failureInRaise:[NSString stringWithFormat: @"!(%s) ", #expr] \
exception:anException \
inFile:[NSString stringWithUTF8String:__FILE__] \
atLine:__LINE__ \
withDescription:STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while (0)
/*" Generates a failure when expression does not throw an exception.
_{expression The expression that is evaluated.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.
"*/
#define STAssertThrows(expr, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (id anException) { \
continue; \
}\
[self failWithException:[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: nil \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
} while (0)
/*" Generates a failure when expression does not throw an exception of a
specific class.
_{expression The expression that is evaluated.}
_{specificException The specified class of the exception.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertThrowsSpecific(expr, specificException, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (specificException *anException) { \
continue; \
}\
@catch (id anException) {\
NSString *_descrip = STComposeString(@"(Expected exception: %@) %@", NSStringFromClass([specificException class]), description);\
[self failWithException:[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
continue; \
}\
NSString *_descrip = STComposeString(@"(Expected exception: %@) %@", NSStringFromClass([specificException class]), description);\
[self failWithException:[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: nil \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
} while (0)
/*" Generates a failure when expression does not throw an exception of a
specific class with a specific name. Useful for those frameworks like
AppKit or Foundation that throw generic NSException w/specific names
(NSInvalidArgumentException, etc).
_{expression The expression that is evaluated.}
_{specificException The specified class of the exception.}
_{aName The name of the specified exception.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertThrowsSpecificNamed(expr, specificException, aName, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (specificException *anException) { \
if ([aName isEqualToString: [anException name]]) continue; \
NSString *_descrip = STComposeString(@"(Expected exception: %@ (name: %@)) %@", NSStringFromClass([specificException class]), aName, description);\
[self failWithException: \
[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
continue; \
}\
@catch (id anException) {\
NSString *_descrip = STComposeString(@"(Expected exception: %@) %@", NSStringFromClass([specificException class]), description);\
[self failWithException: \
[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
continue; \
}\
NSString *_descrip = STComposeString(@"(Expected exception: %@) %@", NSStringFromClass([specificException class]), description);\
[self failWithException: \
[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: nil \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
} while (0)
/*" Generates a failure when expression does throw an exception.
_{expression The expression that is evaluated.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertNoThrow(expr, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (id anException) { \
[self failWithException:[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
} while (0)
/*" Generates a failure when expression does throw an exception of the specitied
class. Any other exception is okay (i.e. does not generate a failure).
_{expression The expression that is evaluated.}
_{specificException The specified class of the exception.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertNoThrowSpecific(expr, specificException, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (specificException *anException) { \
[self failWithException:[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(description, ##__VA_ARGS__)]]; \
}\
@catch (id anythingElse) {\
; \
}\
} while (0)
/*" Generates a failure when expression does throw an exception of a
specific class with a specific name. Useful for those frameworks like
AppKit or Foundation that throw generic NSException w/specific names
(NSInvalidArgumentException, etc).
_{expression The expression that is evaluated.}
_{specificException The specified class of the exception.}
_{aName The name of the specified exception.}
_{description A format string as in the printf() function. Can be nil or
an empty string but must be present.}
_{... A variable number of arguments to the format string. Can be absent.}
"*/
#define STAssertNoThrowSpecificNamed(expr, specificException, aName, description, ...) \
do { \
@try { \
(expr);\
} \
@catch (specificException *anException) { \
if ([aName isEqualToString: [anException name]]) { \
NSString *_descrip = STComposeString(@"(Expected exception: %@ (name: %@)) %@", NSStringFromClass([specificException class]), aName, description);\
[self failWithException: \
[NSException failureInRaise: [NSString stringWithUTF8String:#expr] \
exception: anException \
inFile: [NSString stringWithUTF8String:__FILE__] \
atLine: __LINE__ \
withDescription: STComposeString(_descrip, ##__VA_ARGS__)]]; \
} \
continue; \
}\
@catch (id anythingElse) {\
; \
}\
} while (0)
@interface NSException (GTMSenTestAdditions)
+ (NSException *)failureInFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ...;
+ (NSException *)failureInCondition:(NSString *)condition
isTrue:(BOOL)isTrue
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ...;
+ (NSException *)failureInEqualityBetweenObject:(id)left
andObject:(id)right
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ...;
+ (NSException *)failureInEqualityBetweenValue:(NSValue *)left
andValue:(NSValue *)right
withAccuracy:(NSValue *)accuracy
inFile:(NSString *)filename
atLine:(int) ineNumber
withDescription:(NSString *)formatString, ...;
+ (NSException *)failureInRaise:(NSString *)expression
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ...;
+ (NSException *)failureInRaise:(NSString *)expression
exception:(NSException *)exception
inFile:(NSString *)filename
atLine:(int)lineNumber
withDescription:(NSString *)formatString, ...;
@end
// SENTE_END
@interface SenTestCase : NSObject {
SEL currentSelector_;
}
- (void)setUp;
- (void)invokeTest;
- (void)tearDown;
- (void)performTest:(SEL)sel;
- (void)failWithException:(NSException*)exception;
@end
GTM_EXTERN NSString *const SenTestFailureException;
GTM_EXTERN NSString *const SenTestFilenameKey;
GTM_EXTERN NSString *const SenTestLineNumberKey;
#endif // GTM_IPHONE_SDK
// All unittest cases in GTM should inherit from GTMTestCase. It makes sure
// to set up our logging system correctly to verify logging calls.
// See GTMUnitTestDevLog.h for details
@interface GTMTestCase : SenTestCase
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMSenTestCase.h | Objective-C | bsd | 50,060 |
//
// GTMIPhoneUnitTestMain.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#if !GTM_IPHONE_SDK
#error GTMIPhoneUnitTestMain for iPhone only
#endif
#import <UIKit/UIKit.h>
// Creates an application that runs all tests from classes extending
// SenTestCase, outputs results and test run time, and terminates right
// afterwards.
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"GTMIPhoneUnitTestDelegate");
[pool release];
return retVal;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMIPhoneUnitTestMain.m | Objective-C | bsd | 1,130 |
//
// GTMNSObject+UnitTesting.h
//
// Utilities for doing advanced unittesting with objects.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import <Foundation/Foundation.h>
#if GTM_MACOS_SDK
#import <ApplicationServices/ApplicationServices.h>
#elif GTM_IPHONE_SDK
#import <CoreGraphics/CoreGraphics.h>
#endif
#import "GTMSenTestCase.h"
// Utility functions for GTMAssert* Macros. Don't use them directly
// but use the macros below instead
BOOL GTMIsObjectImageEqualToImageNamed(id object,
NSString *filename,
NSString **error);
BOOL GTMIsObjectStateEqualToStateNamed(id object,
NSString *filename,
NSString **error);
// Fails when image of |a1| does not equal image in image file named |a2|
//
// Generates a failure when the unittest image of |a1| is not equal to the
// image stored in the image file named |a2|, or |a2| does not exist in the
// executable code's bundle.
// If |a2| does not exist in the executable code's bundle, we save a image
// representation of |a1| in the save directory with name |a2|. This can then
// be included in the bundle as the master to test against.
// If |a2| != |a1|, we save a image representation of |a1| in the save
// directory named |a2|_Failed and a file named |a2|_Failed_Diff showing the
// diff in red so that we can see what has changed.
// See pathForImageNamed to see how name is searched for.
// The save directory is specified by +gtm_setUnitTestSaveToDirectory, and is
// the desktop by default.
// Implemented as a macro to match the rest of the SenTest macros.
//
// Args:
// a1: The object to be checked. Must implement the -createUnitTestImage method.
// a2: The name of the image file to check against.
// Do not include the extension
// description: A format string as in the printf() function.
// Can be nil or an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
//
#define GTMAssertObjectImageEqualToImageNamed(a1, a2, description, ...) \
do { \
id a1Object = (a1); \
NSString* a2String = (a2); \
NSString *failString = nil; \
BOOL isGood = GTMIsObjectImageEqualToImageNamed(a1Object, a2String, &failString); \
if (!isGood) { \
if (description) { \
STFail(@"%@: %@", failString, STComposeString(description, ##__VA_ARGS__)); \
} else { \
STFail(@"%@", failString); \
} \
} \
} while(0)
// Fails when state of |a1| does not equal state in file |a2|
//
// Generates a failure when the unittest state of |a1| is not equal to the
// state stored in the state file named |a2|, or |a2| does not exist in the
// executable code's bundle.
// If |a2| does not exist in the executable code's bundle, we save a state
// representation of |a1| in the save directiry with name |a2|. This can then
// be included in the bundle as the master to test against.
// If |a2| != |a1|, we save a state representation of |a1| in the save
// directory with name |a2|_Failed so that we can compare the two files to see
// what has changed.
// The save directory is specified by +gtm_setUnitTestSaveToDirectory, and is
// the desktop by default.
// Implemented as a macro to match the rest of the SenTest macros.
//
// Args:
// a1: The object to be checked. Must implement the -createUnitTestImage method.
// a2: The name of the state file to check against.
// Do not include the extension
// description: A format string as in the printf() function.
// Can be nil or an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
//
#define GTMAssertObjectStateEqualToStateNamed(a1, a2, description, ...) \
do { \
id a1Object = (a1); \
NSString* a2String = (a2); \
NSString *failString = nil; \
BOOL isGood = GTMIsObjectStateEqualToStateNamed(a1Object, a2String, &failString); \
if (!isGood) { \
if (description) { \
STFail(@"%@: %@", failString, STComposeString(description, ##__VA_ARGS__)); \
} else { \
STFail(@"%@", failString); \
} \
} \
} while(0);
// test both GTMAssertObjectImageEqualToImageNamed and GTMAssertObjectStateEqualToStateNamed
//
// Combines the above two macros into a single ubermacro for comparing
// both state and image. When only the best will do...
#define GTMAssertObjectEqualToStateAndImageNamed(a1, a2, description, ...) \
do { \
GTMAssertObjectImageEqualToImageNamed(a1, a2, description, ##__VA_ARGS__); \
GTMAssertObjectStateEqualToStateNamed(a1, a2, description, ##__VA_ARGS__); \
} while (0)
// Create a CGBitmapContextRef appropriate for using in creating a unit test
// image. If data is non-NULL, returns the buffer that the bitmap is
// using for it's underlying storage. You must free this buffer using
// free. If data is NULL, uses it's own internal storage.
// Defined as a C function instead of an obj-c method because you have to
// release the CGContextRef that is returned.
//
// Returns:
// an CGContextRef of the object. Caller must release
CGContextRef GTMCreateUnitTestBitmapContextOfSizeWithData(CGSize size,
unsigned char **data);
// GTMUnitTestingImaging protocol is for objects which need to save their
// image for using with the unit testing categories
@protocol GTMUnitTestingImaging
// Create a CGImageRef containing a representation suitable for use in
// comparing against a master image.
//
// Returns:
// an CGImageRef of the object.
- (CGImageRef)gtm_unitTestImage;
@end
// GTMUnitTestingEncoding protocol is for objects which need to save their
// "state" for using with the unit testing categories
@protocol GTMUnitTestingEncoding
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state. Encode data in the coder in the same
// manner that you would encode data in any other Keyed NSCoder subclass.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder;
@end
// Category for saving and comparing object state and image for unit tests
//
// The GTMUnitTestAdditions category gives object the ability to store their
// state for use in unittesting in two different manners.
// 1) Objects can elect to save their "image" that we can compare at
// runtime to an image file to make sure that the representation hasn't
// changed. All views and Windows can save their image. In the case of Windows,
// they are "bluescreened" so that any transparent areas can be compared between
// machines.
// 2) Objects can elect to save their "state". State is the attributes that we
// want to verify when running unit tests. Applications, Windows, Views,
// Controls and Cells currently return a variety of state information. If you
// want to customize the state information that a particular object returns, you
// can do it via the GTMUnitTestingEncodedObjectNotification. Items that have
// delegates (Applications/Windows) can also have their delegates return state
// information if appropriate via the unitTestEncoderDidEncode:inCoder: delegate
// method.
// To compare state/image in your unit tests, you can use the three macros above
// GTMAssertObjectStateEqualToStateNamed, GTMAssertObjectImageEqualToImageNamed and
// GTMAssertObjectEqualToStateAndImageNamed.
@interface NSObject (GTMUnitTestingAdditions) <GTMUnitTestingEncoding>
// Allows you to control where the unit test utilities save any files
// (image or state) that they create on your behalf. By default they
// will save to the desktop.
+ (void)gtm_setUnitTestSaveToDirectory:(NSString*)path;
+ (NSString *)gtm_getUnitTestSaveToDirectory;
// Checks to see that system settings are valid for doing an image comparison.
// Most of these are set by our unit test app. See the unit test app main.m
// for details.
//
// Returns:
// YES if we can do image comparisons for this object type.
- (BOOL)gtm_areSystemSettingsValidForDoingImage;
// Return the type of image to work with. Only valid types on the iPhone
// are kUTTypeJPEG and kUTTypePNG. MacOS supports several more.
- (CFStringRef)gtm_imageUTI;
// Return the extension to be used for saving unittest images
//
// Returns
// An extension (e.g. "png")
- (NSString*)gtm_imageExtension;
// Return image data in the format expected for gtm_imageExtension
// So for a "png" extension I would expect "png" data
//
// Returns
// NSData for image
- (NSData*)gtm_imageDataForImage:(CGImageRef)image;
// Save the unitTestImage to a image file with name
// |name|.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension
// in the save folder (desktop by default)
//
// Args:
// name: The name for the image file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToImageNamed:(NSString*)name;
// Save unitTestImage of |self| to an image file at path |path|.
// All non-drawn areas will be transparent.
//
// Args:
// name: The name for the image file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToImageAt:(NSString*)path;
// Compares unitTestImage of |self| to the image located at |path|
//
// Args:
// path: the path to the image file you want to compare against.
// If diff is non-nil, it will contain an auto-released diff of the images.
//
// Returns:
// YES if they are equal, NO is they are not
// If diff is non-nil, it will contain a diff of the images. Must
// be released by caller.
//
- (BOOL)gtm_compareWithImageAt:(NSString*)path diffImage:(CGImageRef*)diff;
// Find the path for a image by name in your bundle.
// Searches for the following:
// "name.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersionBugfix.arch.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.extension"
// "name.OSVersionMajor.OSVersionMinor.arch.extension"
// "name.arch.OSVersionMajor.extension"
// "name.OSVersionMajor.arch.extension"
// "name.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension"
// "name.OSVersionMajor.OSVersionMinorextension"
// "name.OSVersionMajor.extension"
// "name.extension"
// Do not include the extension on your name.
//
// Args:
// name: The name for the image file you would like to find.
//
// Returns:
// the path if the image exists in your bundle
// or nil if no image to be found
//
- (NSString *)gtm_pathForImageNamed:(NSString*)name;
// Generates a CGImageRef from the image at |path|
// Args:
// path: The path to the image.
//
// Returns:
// An autoreleased CGImageRef own, or nil if no image at path
- (CGImageRef)gtm_imageWithContentsOfFile:(NSString*)path;
// Generates a path for a image in the save directory, which is desktop
// by default.
// Path will be:
// SaveDir/|name|.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension
//
// Args:
// name: The name for the image file you would like to generate a path for.
//
// Returns:
// the path
//
- (NSString *)gtm_saveToPathForImageNamed:(NSString*)name;
// Gives us a representation of unitTestImage of |self|.
//
// Returns:
// a representation if successful
// nil if failed
//
- (NSData *)gtm_imageRepresentation;
// Return the extension to be used for saving unittest states
//
// Returns
// An extension (e.g. "gtmUTState")
- (NSString*)gtm_stateExtension;
// Save the encoded unit test state to a state file with name
// |name|.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension
// in the save folder (desktop by default)
//
// Args:
// name: The name for the state file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToStateNamed:(NSString*)name;
// Save encoded unit test state of |self| to a state file at path |path|.
//
// Args:
// name: The name for the state file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToStateAt:(NSString*)path;
// Compares encoded unit test state of |self| to the state file located at |path|
//
// Args:
// path: the path to the state file you want to compare against.
//
// Returns:
// YES if they are equal, NO is they are not
//
- (BOOL)gtm_compareWithStateAt:(NSString*)path;
// Find the path for a state by name in your bundle.
// Searches for:
// "name.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersionBugfix.arch.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.extension"
// "name.OSVersionMajor.OSVersionMinor.arch.extension"
// "name.arch.OSVersionMajor.extension"
// "name.OSVersionMajor.arch.extension"
// "name.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension"
// "name.OSVersionMajor.OSVersionMinor.extension"
// "name.OSVersionMajor.extension"
// "name.extension"
// Do not include the extension on your name.
//
// Args:
// name: The name for the state file you would like to find.
//
// Returns:
// the path if the state exists in your bundle
// or nil if no state to be found
//
- (NSString *)gtm_pathForStateNamed:(NSString*)name;
// Generates a path for a state in the save directory, which is desktop
// by default.
// Path will be:
// SaveDir/|name|.arch.OSVersionMajor.OSVersionMinor.OSVersionBugfix.extension
//
// Args:
// name: The name for the state file you would like to generate a path for.
//
// Returns:
// the path
//
- (NSString *)gtm_saveToPathForStateNamed:(NSString*)name;
// Gives us the encoded unit test state for |self|
//
// Returns:
// the encoded state if successful
// nil if failed
//
- (NSDictionary *)gtm_stateRepresentation;
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state. Encode data in the coder in the same
// manner that you would encode data in any other Keyed NSCoder subclass.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder;
@end
// Informal protocol for delegates that wanst to be able to add state info
// when state info is collected for their "owned" objects
@interface NSObject (GTMUnitTestingEncodingAdditions)
// Delegate function for unit test objects that have delegates. Delegates have
// the option of encoding more data into the coder to store their state for
// unittest usage.
- (void)gtm_unitTestEncoderWillEncode:(id)sender inCoder:(NSCoder*)inCoder;
@end
// Whenever an object is encoded by the unit test encoder, it send out a
// notification so that objects who want to add data to the encoded objects unit
// test state can do so. The Coder will be in the userInfo dictionary for the
// notification under the GTMUnitTestingEncoderKey key.
GTM_EXTERN NSString *const GTMUnitTestingEncodedObjectNotification;
// Key for finding the encoder in the userInfo dictionary for
// GTMUnitTestingEncodedObjectNotification notifications.
GTM_EXTERN NSString *const GTMUnitTestingEncoderKey;
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMNSObject+UnitTesting.h | Objective-C | bsd | 15,978 |
//
// GTMUnitTestDevLog.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMUnitTestDevLog.h"
#import "GTMRegex.h"
#import "GTMSenTestCase.h"
#if !GTM_IPHONE_SDK
// Add support for grabbing messages from Carbon.
#import <CoreServices/CoreServices.h>
static void GTMDevLogDebugAssert(OSType componentSignature,
UInt32 options,
const char *assertionString,
const char *exceptionLabelString,
const char *errorString,
const char *fileName,
long lineNumber,
void *value,
ConstStr255Param outputMsg) {
NSString *outLog = [[[NSString alloc] initWithBytes:&(outputMsg[1])
length:StrLength(outputMsg)
encoding:NSMacOSRomanStringEncoding]
autorelease];
_GTMDevLog(@"%@", outLog); // Don't want any percents in outLog honored
}
static inline void GTMInstallDebugAssertOutputHandler(void) {
InstallDebugAssertOutputHandler(GTMDevLogDebugAssert);
}
static inline void GTMUninstallDebugAssertOutputHandler(void) {
InstallDebugAssertOutputHandler(NULL);
}
#else // GTM_IPHONE_SDK
static inline void GTMInstallDebugAssertOutputHandler(void) {};
static inline void GTMUninstallDebugAssertOutputHandler(void) {};
#endif // GTM_IPHONE_SDK
@interface GTMUnttestDevLogAssertionHandler : NSAssertionHandler
@end
@implementation GTMUnttestDevLogAssertionHandler
- (void)handleFailureInMethod:(SEL)selector
object:(id)object
file:(NSString *)fileName
lineNumber:(NSInteger)line
description:(NSString *)format, ... {
va_list argList;
va_start(argList, format);
NSString *descStr
= [[[NSString alloc] initWithFormat:format arguments:argList] autorelease];
va_end(argList);
// You need a format that will be useful in logs, but won't trip up Xcode or
// any other build systems parsing of the output.
NSString *outLog
= [NSString stringWithFormat:@"RecordedNSAssert in %@ - %@ (%@:%ld)",
NSStringFromSelector(selector),
descStr,
fileName, (long)line];
_GTMDevLog(@"%@", outLog); // Don't want any percents in outLog honored
[NSException raise:NSInternalInconsistencyException
format:@"NSAssert raised"];
}
- (void)handleFailureInFunction:(NSString *)functionName
file:(NSString *)fileName
lineNumber:(NSInteger)line
description:(NSString *)format, ... {
va_list argList;
va_start(argList, format);
NSString *descStr
= [[[NSString alloc] initWithFormat:format arguments:argList] autorelease];
va_end(argList);
// You need a format that will be useful in logs, but won't trip up Xcode or
// any other build systems parsing of the output.
NSString *outLog
= [NSString stringWithFormat:@"RecordedNSAssert in %@ - %@ (%@:%ld)",
functionName,
descStr,
fileName, (long)line];
_GTMDevLog(@"%@", outLog); // Don't want any percents in outLog honored
[NSException raise:NSInternalInconsistencyException
format:@"NSAssert raised"];
}
@end
@implementation GTMUnitTestDevLog
// If unittests are ever being run on separate threads, this may need to be
// made a thread local variable.
static BOOL gTrackingEnabled = NO;
+ (NSMutableArray *)patterns {
static NSMutableArray *patterns = nil;
if (!patterns) {
patterns = [[NSMutableArray array] retain];
}
return patterns;
}
+ (BOOL)isTrackingEnabled {
return gTrackingEnabled;
}
+ (void)enableTracking {
GTMInstallDebugAssertOutputHandler();
NSMutableDictionary *threadDictionary
= [[NSThread currentThread] threadDictionary];
if ([threadDictionary objectForKey:@"NSAssertionHandler"] != nil) {
NSLog(@"Warning: replacing NSAssertionHandler to capture assertions");
}
// Install an assertion handler to capture those.
GTMUnttestDevLogAssertionHandler *handler =
[[[GTMUnttestDevLogAssertionHandler alloc] init] autorelease];
[threadDictionary setObject:handler forKey:@"NSAssertionHandler"];
gTrackingEnabled = YES;
}
+ (void)disableTracking {
GTMUninstallDebugAssertOutputHandler();
// Clear our assertion handler back out.
NSMutableDictionary *threadDictionary
= [[NSThread currentThread] threadDictionary];
[threadDictionary removeObjectForKey:@"NSAssertionHandler"];
gTrackingEnabled = NO;
}
+ (void)log:(NSString*)format, ... {
va_list argList;
va_start(argList, format);
[self log:format args:argList];
va_end(argList);
}
+ (void)log:(NSString*)format args:(va_list)args {
if ([self isTrackingEnabled]) {
NSString *logString = [[[NSString alloc] initWithFormat:format
arguments:args] autorelease];
@synchronized(self) {
NSMutableArray *patterns = [self patterns];
BOOL logError = [patterns count] == 0 ? YES : NO;
GTMRegex *regex = nil;
if (!logError) {
regex = [[[patterns objectAtIndex:0] retain] autorelease];
logError = [regex matchesString:logString] ? NO : YES;
[patterns removeObjectAtIndex:0];
}
if (logError) {
if (regex) {
[NSException raise:SenTestFailureException
format:@"Unexpected log: %@\nExpected: %@",
logString, regex];
} else {
[NSException raise:SenTestFailureException
format:@"Unexpected log: %@", logString];
}
} else {
static BOOL envChecked = NO;
static BOOL showExpectedLogs = YES;
if (!envChecked) {
showExpectedLogs = getenv("GTM_SHOW_UNITTEST_DEVLOGS") ? YES : NO;
}
if (showExpectedLogs) {
NSLog(@"Expected Log: %@", logString);
}
}
}
} else {
NSLogv(format, args);
}
}
+ (void)expectString:(NSString *)format, ... {
va_list argList;
va_start(argList, format);
NSString *string = [[[NSString alloc] initWithFormat:format
arguments:argList] autorelease];
va_end(argList);
NSString *pattern = [GTMRegex escapedPatternForString:string];
[self expect:1 casesOfPattern:pattern];
}
+ (void)expectPattern:(NSString *)format, ... {
va_list argList;
va_start(argList, format);
[self expect:1 casesOfPattern:format args:argList];
va_end(argList);
}
+ (void)expect:(NSUInteger)n casesOfString:(NSString *)format, ... {
va_list argList;
va_start(argList, format);
NSString *string = [[[NSString alloc] initWithFormat:format
arguments:argList] autorelease];
va_end(argList);
NSString *pattern = [GTMRegex escapedPatternForString:string];
[self expect:n casesOfPattern:pattern];
}
+ (void)expect:(NSUInteger)n casesOfPattern:(NSString*)format, ... {
va_list argList;
va_start(argList, format);
[self expect:n casesOfPattern:format args:argList];
va_end(argList);
}
+ (void)expect:(NSUInteger)n
casesOfPattern:(NSString*)format
args:(va_list)args {
NSString *pattern = [[[NSString alloc] initWithFormat:format
arguments:args] autorelease];
GTMRegex *regex = [GTMRegex regexWithPattern:pattern
options:kGTMRegexOptionSupressNewlineSupport];
@synchronized(self) {
NSMutableArray *patterns = [self patterns];
for (NSUInteger i = 0; i < n; ++i) {
[patterns addObject:regex];
}
}
}
+ (void)verifyNoMoreLogsExpected {
@synchronized(self) {
NSMutableArray *patterns = [self patterns];
if ([patterns count] > 0) {
NSMutableArray *patternsCopy = [[patterns copy] autorelease];
[self resetExpectedLogs];
[NSException raise:SenTestFailureException
format:@"Logs still expected %@", patternsCopy];
}
}
}
+ (void)resetExpectedLogs {
@synchronized(self) {
NSMutableArray *patterns = [self patterns];
[patterns removeAllObjects];
}
}
@end
@implementation GTMUnitTestDevLogDebug
+ (void)expect:(NSUInteger)n
casesOfPattern:(NSString*)format
args:(va_list)args {
#if DEBUG
// In debug, let the base work happen
[super expect:n casesOfPattern:format args:args];
#else
// nothing when not in debug
#endif
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestDevLog.m | Objective-C | bsd | 9,287 |
//
// GTMTestTimerTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMTestTimer.h"
@interface GTMTestTimerTest : GTMTestCase
@end
@implementation GTMTestTimerTest
- (void)testTimer {
GTMTestTimer *timer = GTMTestTimerCreate();
STAssertNotNULL(timer, nil);
GTMTestTimerRetain(timer);
GTMTestTimerRelease(timer);
STAssertEqualsWithAccuracy(GTMTestTimerGetSeconds(timer), 0.0, 0.0, nil);
GTMTestTimerStart(timer);
STAssertTrue(GTMTestTimerIsRunning(timer), nil);
NSRunLoop *loop = [NSRunLoop currentRunLoop];
[loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
GTMTestTimerStop(timer);
// We use greater than (and an almost absurd less than) because
// these tests are very dependant on machine load, and we don't want
// automated tests reporting false negatives.
STAssertGreaterThan(GTMTestTimerGetSeconds(timer), 0.1, nil);
STAssertGreaterThan(GTMTestTimerGetMilliseconds(timer), 100.0,nil);
STAssertGreaterThan(GTMTestTimerGetMicroseconds(timer), 100000.0, nil);
// Check to make sure we're not WAY off the mark (by a factor of 10)
STAssertLessThan(GTMTestTimerGetMicroseconds(timer), 1000000.0, nil);
[loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
GTMTestTimerStart(timer);
[loop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
STAssertGreaterThan(GTMTestTimerGetSeconds(timer), 0.2, nil);
GTMTestTimerStop(timer);
STAssertEquals(GTMTestTimerGetIterations(timer), (NSUInteger)2, nil);
GTMTestTimerRelease(timer);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMTestTimerTest.m | Objective-C | bsd | 2,120 |
//
// GTMUnitTestingTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <SenTestingKit/SenTestingKit.h>
#import "GTMUnitTestingTest.h"
#import "GTMAppKit+UnitTesting.h"
NSString *const kGTMWindowNibName = @"GTMUnitTestingTest";
NSString *const kGTMWindowSaveFileName = @"GTMUnitTestingWindow";
@interface GTMUnitTestingTest : GTMTestCase {
int expectedFailureCount_;
}
@end
// GTMUnitTestingTest support classes
@interface GTMUnitTestingView : NSObject <GTMUnitTestViewDrawer> {
BOOL goodContext_;
}
- (BOOL)hadGoodContext;
@end
@interface GTMUnitTestingDelegate : NSObject {
BOOL didEncode_;
}
- (BOOL)didEncode;
@end
@interface GTMUnitTestingProxyTest : NSProxy
@end
@implementation GTMUnitTestingTest
// Brings up the window defined in the nib and takes a snapshot of it.
// We use the "empty" GTMUnitTestingTestController controller so that
// initWithWindowNibName can find the appropriate bundle to load our nib from.
// For some reason when running unit tests, with all the injecting going on
// the nib loader can get confused as to where it should load a nib from.
// Having a NSWindowController subclass in the same bundle as the nib seems
// to help the nib loader find the nib, and any custom classes that are attached
// to it.
- (void)testUnitTestingFramework {
// set up our delegates so we can test delegate handling
GTMUnitTestingDelegate *appDelegate = [[GTMUnitTestingDelegate alloc] init];
[NSApp setDelegate:appDelegate];
// Get our window
GTMUnitTestingTestController *testWindowController
= [[GTMUnitTestingTestController alloc] initWithWindowNibName:kGTMWindowNibName];
NSWindow *window = [testWindowController window];
// Test the app state. This will cover windows and menus
GTMAssertObjectStateEqualToStateNamed(NSApp,
@"GTMUnitTestingTestApp",
@"Testing the app state");
// Test the window image and state
GTMAssertObjectEqualToStateAndImageNamed(window,
kGTMWindowSaveFileName,
@"Testing the window image and state");
// Verify that all of our delegate encoders got called
STAssertTrue([appDelegate didEncode], @"app delegate didn't get called?");
// Clean up
[NSApp setDelegate:nil];
[appDelegate release];
[testWindowController release];
}
- (void)testViewUnitTesting {
GTMUnitTestingView *unitTestingView = [[GTMUnitTestingView alloc] init];
GTMAssertDrawingEqualToImageNamed(unitTestingView,
NSMakeSize(200,200),
@"GTMUnitTestingView",
NSApp,
@"Testing view drawing");
STAssertTrue([unitTestingView hadGoodContext], @"bad context?");
[unitTestingView release];
}
- (void)testImageUnitTesting {
NSImage *image = [NSImage imageNamed:@"NSApplicationIcon"];
GTMUnitTestingDelegate *imgDelegate = [[GTMUnitTestingDelegate alloc] init];
[image setDelegate:imgDelegate];
GTMAssertObjectEqualToStateAndImageNamed(image,
@"GTMUnitTestingImage",
@"Testing NSImage image and state");
STAssertTrue([imgDelegate didEncode], @"imgDelegate didn't get called?");
[image setDelegate:nil];
[imgDelegate release];
}
- (void)testFailures {
NSString *const bogusTestName = @"GTMUnitTestTestingFailTest";
NSString *tempDir = NSTemporaryDirectory();
STAssertNotNil(tempDir, @"No Temp Dir?");
NSString *originalPath = [NSObject gtm_getUnitTestSaveToDirectory];
STAssertNotNil(originalPath, @"No save dir?");
[NSObject gtm_setUnitTestSaveToDirectory:tempDir];
STAssertEqualObjects(tempDir, [NSObject gtm_getUnitTestSaveToDirectory],
@"Save to dir not set?");
NSString *statePath = [self gtm_saveToPathForStateNamed:bogusTestName];
STAssertNotNil(statePath, @"no state path?");
NSString *imagePath = [self gtm_saveToPathForImageNamed:bogusTestName];
STAssertNotNil(imagePath, @"no image path?");
GTMUnitTestingTestController *testWindowController
= [[GTMUnitTestingTestController alloc] initWithWindowNibName:kGTMWindowNibName];
NSWindow *window = [testWindowController window];
// Test against a golden master filename that doesn't exist
expectedFailureCount_ = 2;
GTMAssertObjectEqualToStateAndImageNamed(window,
bogusTestName,
@"Creating image and state files");
STAssertEquals(expectedFailureCount_, 0,
@"Didn't get expected failures creating files");
// Change our image and state and verify failures
[[testWindowController textField] setStringValue:@"Foo"];
expectedFailureCount_ = 2;
GTMAssertObjectEqualToStateAndImageNamed(window,
kGTMWindowSaveFileName,
@"Testing the window image and state");
STAssertEquals(expectedFailureCount_, 0,
@"Didn't get expected failures testing files");
// Now change the size of our image and verify failures
NSRect oldFrame = [window frame];
NSRect newFrame = oldFrame;
newFrame.size.width += 1;
[window setFrame:newFrame display:YES];
expectedFailureCount_ = 1;
GTMAssertObjectImageEqualToImageNamed(window,
kGTMWindowSaveFileName,
@"Testing the changed window size");
[window setFrame:oldFrame display:YES];
// Set our unit test save dir to a bogus directory and
// run the tests again.
[NSObject gtm_setUnitTestSaveToDirectory:@"/zim/blatz/foo/bob/bar"];
expectedFailureCount_ = 2;
GTMAssertObjectEqualToStateAndImageNamed(window,
kGTMWindowSaveFileName,
@"Testing the window image and state");
STAssertEquals(expectedFailureCount_, 0,
@"Didn't get expected failures testing files");
expectedFailureCount_ = 2;
GTMAssertObjectEqualToStateAndImageNamed(window,
@"GTMUnitTestingWindowDoesntExist",
@"Testing the window image and state");
STAssertEquals(expectedFailureCount_, 0,
@"Didn't get expected failures testing files");
// Reset our unit test save dir
[NSObject gtm_setUnitTestSaveToDirectory:nil];
// Test against something that doesn't have an image
expectedFailureCount_ = 1;
GTMAssertObjectImageEqualToImageNamed(@"a string",
@"GTMStringsDontHaveImages",
@"Testing that strings should fail");
STAssertEquals(expectedFailureCount_, 0, @"Didn't get expected failures testing files");
// Test against something that doesn't implement our support
expectedFailureCount_ = 1;
GTMUnitTestingProxyTest *proxy = [[GTMUnitTestingProxyTest alloc] init];
GTMAssertObjectStateEqualToStateNamed(proxy,
@"NSProxiesDontDoState",
@"Testing that NSProxy should fail");
STAssertEquals(expectedFailureCount_, 0, @"Didn't get expected failures testing proxy");
[proxy release];
[window close];
}
- (void)failWithException:(NSException *)anException {
if (expectedFailureCount_ > 0) {
expectedFailureCount_ -= 1;
} else {
[super failWithException:anException]; // COV_NF_LINE - not expecting exception
}
}
@end
@implementation GTMUnitTestingTestController
- (NSTextField *)textField {
return field_;
}
@end
@implementation GTMUnitTestingDelegate
- (void)gtm_unitTestEncoderWillEncode:(id)sender inCoder:(NSCoder*)inCoder {
// Test various encodings
[inCoder encodeBool:YES forKey:@"BoolTest"];
[inCoder encodeInt:1 forKey:@"IntTest"];
[inCoder encodeInt32:1 forKey:@"Int32Test"];
[inCoder encodeInt64:1 forKey:@"Int64Test"];
[inCoder encodeFloat:1.0f forKey:@"FloatTest"];
[inCoder encodeDouble:1.0 forKey:@"DoubleTest"];
[inCoder encodeBytes:(const uint8_t*)"BytesTest" length:9 forKey:@"BytesTest"];
didEncode_ = YES;
}
- (BOOL)didEncode {
return didEncode_;
}
@end
@implementation GTMUnitTestingView
- (void)gtm_unitTestViewDrawRect:(NSRect)rect contextInfo:(void*)contextInfo {
[[NSColor redColor] set];
NSRectFill(rect);
goodContext_ = [(id)contextInfo isEqualTo:NSApp];
}
- (BOOL)hadGoodContext {
return goodContext_;
}
@end
// GTMUnitTestingProxyTest is for testing the case where we don't conform to
// the GTMUnitTestingEncoding protocol.
@implementation GTMUnitTestingProxyTest
- (id)init {
return self;
}
- (BOOL)conformsToProtocol:(Protocol *)protocol {
return NO;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestingTest.m | Objective-C | bsd | 9,636 |
//
// GTMTestHTTPServer.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
@class GTMHTTPServer;
// This is a HTTP Server that can respond to certain requests that look like
// Google service logins. It takes extra url arguments to tell it what to
// return for testing the code using it. See GTMHTTPFetcherTest for an example
// of its usage.
@interface GTMTestHTTPServer : NSObject {
NSString *docRoot_;
GTMHTTPServer *server_;
}
// Any url that isn't a specific server request (login, etc.), will be fetched
// off |docRoot| (to allow canned repsonses).
- (id)initWithDocRoot:(NSString *)docRoot;
// fetch the port the server is running on
- (uint16_t)port;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMTestHTTPServer.h | Objective-C | bsd | 1,273 |
//
// GTMNSObject+UnitTesting.m
//
// An informal protocol for doing advanced unittesting with objects.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSObject+UnitTesting.h"
#import "GTMSystemVersion.h"
#import "GTMGarbageCollection.h"
#if GTM_IPHONE_SDK
#import <UIKit/UIKit.h>
#else
#import <AppKit/AppKit.h>
#endif
NSString *const GTMUnitTestingEncodedObjectNotification
= @"GTMUnitTestingEncodedObjectNotification";
NSString *const GTMUnitTestingEncoderKey = @"GTMUnitTestingEncoderKey";
#if GTM_IPHONE_SDK
// No UTIs on iPhone. Only two we need.
const CFStringRef kUTTypePNG = CFSTR("public.png");
const CFStringRef kUTTypeJPEG = CFSTR("public.jpeg");
#endif
// This class exists so that we can locate our bundle using [NSBundle
// bundleForClass:]. We don't use [NSBundle mainBundle] because when we are
// being run as a unit test, we aren't the mainBundle
@interface GTMUnitTestingAdditionsBundleFinder : NSObject {
// Nothing here
}
// or here
@end
@implementation GTMUnitTestingAdditionsBundleFinder
// Nothing here. We're just interested in the name for finding our bundle.
@end
BOOL GTMIsObjectImageEqualToImageNamed(id object,
NSString* filename,
NSString **error) {
NSString *failString = nil;
if (error) {
*error = nil;
}
BOOL isGood = [object respondsToSelector:@selector(gtm_unitTestImage)];
if (isGood) {
if ([object gtm_areSystemSettingsValidForDoingImage]) {
NSString *aPath = [object gtm_pathForImageNamed:filename];
CGImageRef diff = nil;
isGood = aPath != nil;
if (isGood) {
isGood = [object gtm_compareWithImageAt:aPath diffImage:&diff];
}
if (!isGood) {
if (aPath) {
filename = [filename stringByAppendingString:@"_Failed"];
}
BOOL aSaved = [object gtm_saveToImageNamed:filename];
NSString *fileNameWithExtension
= [NSString stringWithFormat:@"%@.%@",
filename, [object gtm_imageExtension]];
NSString *fullSavePath = [object gtm_saveToPathForImageNamed:filename];
if (NO == aSaved) {
if (!aPath) {
failString = [NSString stringWithFormat:@"File %@ did not exist in "
@"bundle. Tried to save as %@ and failed.",
fileNameWithExtension, fullSavePath];
} else {
failString = [NSString stringWithFormat:@"Object image different "
@"than file %@. Tried to save as %@ and failed.",
aPath, fullSavePath];
}
} else {
if (!aPath) {
failString = [NSString stringWithFormat:@"File %@ did not exist in "
@" bundle. Saved to %@", fileNameWithExtension,
fullSavePath];
} else {
NSString *diffPath = [filename stringByAppendingString:@"_Diff"];
diffPath = [object gtm_saveToPathForImageNamed:diffPath];
NSData *data = nil;
if (diff) {
data = [object gtm_imageDataForImage:diff];
}
if ([data writeToFile:diffPath atomically:YES]) {
failString = [NSString stringWithFormat:@"Object image different "
@"than file %@. Saved image to %@. "
@"Saved diff to %@",
aPath, fullSavePath, diffPath];
} else {
failString = [NSString stringWithFormat:@"Object image different "
@"than file %@. Saved image to %@. Unable to save "
@"diff. Most likely the image and diff are "
@"different sizes.",
aPath, fullSavePath];
}
}
}
}
CGImageRelease(diff);
} else {
failString = @"systemSettings not valid for taking image"; // COV_NF_LINE
}
} else {
failString = @"Object does not conform to GTMUnitTestingImaging protocol";
}
if (error) {
*error = failString;
}
return isGood;
}
BOOL GTMIsObjectStateEqualToStateNamed(id object,
NSString* filename,
NSString **error) {
NSString *failString = nil;
if (error) {
*error = nil;
}
BOOL isGood = [object conformsToProtocol:@protocol(GTMUnitTestingEncoding)];
if (isGood) {
NSString *aPath = [object gtm_pathForStateNamed:filename];
isGood = aPath != nil;
if (isGood) {
isGood = [object gtm_compareWithStateAt:aPath];
}
if (!isGood) {
if (aPath) {
filename = [filename stringByAppendingString:@"_Failed"];
}
BOOL aSaved = [object gtm_saveToStateNamed:filename];
NSString *fileNameWithExtension = [NSString stringWithFormat:@"%@.%@",
filename, [object gtm_stateExtension]];
NSString *fullSavePath = [object gtm_saveToPathForStateNamed:filename];
if (NO == aSaved) {
if (!aPath) {
failString = [NSString stringWithFormat:@"File %@ did not exist in "
@"bundle. Tried to save as %@ and failed.",
fileNameWithExtension, fullSavePath];
} else {
failString = [NSString stringWithFormat:@"Object state different "
@"than file %@. Tried to save as %@ and failed.",
aPath, fullSavePath];
}
} else {
if (!aPath) {
failString = [NSString stringWithFormat:@"File %@ did not exist in "
@ "bundle. Saved to %@", fileNameWithExtension,
fullSavePath];
} else {
failString = [NSString stringWithFormat:@"Object state different "
@"than file %@. Saved to %@", aPath, fullSavePath];
}
}
}
} else {
failString = @"Object does not conform to GTMUnitTestingEncoding protocol";
}
if (error) {
*error = failString;
}
return isGood;
}
CGContextRef GTMCreateUnitTestBitmapContextOfSizeWithData(CGSize size,
unsigned char **data) {
CGContextRef context = NULL;
size_t height = size.height;
size_t width = size.width;
size_t bytesPerRow = width * 4;
size_t bitsPerComponent = 8;
CGColorSpaceRef cs = NULL;
#if GTM_IPHONE_SDK
cs = CGColorSpaceCreateDeviceRGB();
#else
cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
#endif
_GTMDevAssert(cs, @"Couldn't create colorspace");
CGBitmapInfo info
= kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault;
if (data) {
*data = (unsigned char*)calloc(bytesPerRow, height);
_GTMDevAssert(*data, @"Couldn't create bitmap");
}
context = CGBitmapContextCreate(data ? *data : NULL, width, height,
bitsPerComponent, bytesPerRow, cs, info);
_GTMDevAssert(context, @"Couldn't create an context");
if (!data) {
CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));
}
CGContextSetRenderingIntent(context, kCGRenderingIntentRelativeColorimetric);
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextSetShouldAntialias(context, NO);
CGContextSetAllowsAntialiasing(context, NO);
CGContextSetShouldSmoothFonts(context, NO);
CGColorSpaceRelease(cs);
return context;
}
@interface NSObject (GTMUnitTestingAdditionsPrivate)
/// Find the path for a file named name.extension in your bundle.
// Searches for the following:
// "name.extension",
// "name.arch.extension",
// "name.arch.OSVersionMajor.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.extension"
// "name.arch.OSVersionMajor.extension"
// "name.OSVersionMajor.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.arch.extension"
// "name.OSVersionMajor.extension"
// "name.OSVersionMajor.OSVersionMinor.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.extension"
// Do not include the ".extension" extension on your name.
//
// Args:
// name: The name for the file you would like to find.
// extension: the extension for the file you would like to find
//
// Returns:
// the path if the file exists in your bundle
// or nil if no file is found
//
- (NSString *)gtm_pathForFileNamed:(NSString*)name
extension:(NSString*)extension;
- (NSString *)gtm_saveToPathForFileNamed:(NSString*)name
extension:(NSString*)extension;
- (CGImageRef)gtm_unitTestImage;
// Returns nil if there is no override
- (NSString *)gtm_getOverrideDefaultUnitTestSaveToDirectory;
@end
// This is a keyed coder for storing unit test state data. It is used only by
// the GTMUnitTestingAdditions category. Most of the work is done in
// encodeObject:forKey:.
@interface GTMUnitTestingKeyedCoder : NSCoder {
NSMutableDictionary *dictionary_; // storage for data (STRONG)
}
// get the data stored in coder.
//
// Returns:
// NSDictionary with currently stored data.
- (NSDictionary*)dictionary;
@end
// Small utility function for checking to see if a is b +/- 1.
GTM_INLINE BOOL almostEqual(unsigned char a, unsigned char b) {
unsigned char diff = a > b ? a - b : b - a;
BOOL notEqual = diff < 2;
return notEqual;
}
@implementation GTMUnitTestingKeyedCoder
// Set up storage for coder. Stores type and version.
// Version 1
//
// Returns:
// self
- (id)init {
self = [super init];
if (self != nil) {
dictionary_ = [[NSMutableDictionary alloc] initWithCapacity:2];
[dictionary_ setObject:@"GTMUnitTestingArchive" forKey:@"$GTMArchive"];
// Version number can be changed here.
[dictionary_ setObject:[NSNumber numberWithInt:1] forKey:@"$GTMVersion"];
}
return self;
}
// Standard dealloc
- (void)dealloc {
[dictionary_ release];
[super dealloc];
}
// Utility function for checking for a key value. We don't want duplicate keys
// in any of our dictionaries as we may be writing over data stored by previous
// objects.
//
// Arguments:
// key - key to check for in dictionary
- (void)checkForKey:(NSString*)key {
_GTMDevAssert(![dictionary_ objectForKey:key],
@"Key already exists for %@", key);
}
// Key routine for the encoder. We store objects in our dictionary based on
// their key. As we encode objects we send out notifications to let other
// classes doing tests add their specific data to the base types. If we can't
// encode the object (it doesn't support gtm_unitTestEncodeState) and we don't
// get any info back from the notifier, we attempt to store it's description.
//
// Arguments:
// objv - object to be encoded
// key - key to encode it with
//
- (void)encodeObject:(id)objv forKey:(NSString *)key {
// Sanity checks
if (!objv) return;
[self checkForKey:key];
// Set up a new dictionary for the current object
NSMutableDictionary *curDictionary = dictionary_;
dictionary_ = [[NSMutableDictionary alloc] initWithCapacity:0];
// If objv responds to gtm_unitTestEncodeState get it to record
// its data.
if ([objv respondsToSelector:@selector(gtm_unitTestEncodeState:)]) {
[objv gtm_unitTestEncodeState:self];
}
// We then send out a notification to let other folks
// add data for this object
NSDictionary *notificationDict
= [NSDictionary dictionaryWithObject:self forKey:GTMUnitTestingEncoderKey];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:GTMUnitTestingEncodedObjectNotification
object:objv
userInfo:notificationDict];
// If we got anything from the object, or from the notification, store it in
// our dictionary. Otherwise store the description.
if ([dictionary_ count] > 0) {
[curDictionary setObject:dictionary_ forKey:key];
} else {
NSString *description = [objv description];
// If description has a pointer value in it, we don't want to store it
// as the pointer value can change from run to run
if (description && [description rangeOfString:@"0x"].length == 0) {
[curDictionary setObject:description forKey:key];
} else {
_GTMDevAssert(NO, @"Unable to encode forKey: %@", key); // COV_NF_LINE
}
}
[dictionary_ release];
dictionary_ = curDictionary;
}
// Basic encoding methods for POD types.
//
// Arguments:
// *v - value to encode
// key - key to encode it in
- (void)encodeBool:(BOOL)boolv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithBool:boolv] forKey:key];
}
- (void)encodeInt:(int)intv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithInt:intv] forKey:key];
}
- (void)encodeInt32:(int32_t)intv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithLong:intv] forKey:key];
}
- (void)encodeInt64:(int64_t)intv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithLongLong:intv] forKey:key];
}
- (void)encodeFloat:(float)realv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithFloat:realv] forKey:key];
}
- (void)encodeDouble:(double)realv forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSNumber numberWithDouble:realv] forKey:key];
}
- (void)encodeBytes:(const uint8_t *)bytesp
length:(unsigned)lenv
forKey:(NSString *)key {
[self checkForKey:key];
[dictionary_ setObject:[NSData dataWithBytes:bytesp
length:lenv]
forKey:key];
}
// Get our storage back as an NSDictionary
//
// Returns:
// NSDictionary containing our encoded info
-(NSDictionary*)dictionary {
return [[dictionary_ retain] autorelease];
}
@end
static NSString *gGTMUnitTestSaveToDirectory = nil;
@implementation NSObject (GTMUnitTestingAdditions)
+ (void)gtm_setUnitTestSaveToDirectory:(NSString*)path {
@synchronized([self class]) {
[gGTMUnitTestSaveToDirectory autorelease];
gGTMUnitTestSaveToDirectory = [path copy];
}
}
+ (NSString *)gtm_getUnitTestSaveToDirectory {
NSString *result = nil;
@synchronized([self class]) {
if (!gGTMUnitTestSaveToDirectory) {
#if GTM_IPHONE_SDK
// Developer build, use their home directory Desktop.
gGTMUnitTestSaveToDirectory
= [[[[[NSHomeDirectory() stringByDeletingLastPathComponent]
stringByDeletingLastPathComponent]
stringByDeletingLastPathComponent]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:@"Desktop"];
#else
NSArray *desktopDirs
= NSSearchPathForDirectoriesInDomains(NSDesktopDirectory,
NSUserDomainMask,
YES);
gGTMUnitTestSaveToDirectory = [desktopDirs objectAtIndex:0];
#endif
// Did we get overridden?
NSString *override = [self gtm_getOverrideDefaultUnitTestSaveToDirectory];
if (override) {
gGTMUnitTestSaveToDirectory = override;
}
[gGTMUnitTestSaveToDirectory retain];
}
result = gGTMUnitTestSaveToDirectory;
}
return result;
}
// Return nil if there is no override
- (NSString *)gtm_getOverrideDefaultUnitTestSaveToDirectory {
NSString *result = nil;
// If we have an environment variable that ends in "BUILD_NUMBER" odds are
// we're on an automated build system, so use the build products dir as an
// override instead of writing on the desktop.
NSDictionary *env = [[NSProcessInfo processInfo] environment];
NSString *key;
GTM_FOREACH_KEY(key, env) {
if ([key hasSuffix:@"BUILD_NUMBER"]) {
break;
}
}
if (key) {
result = [env objectForKey:@"BUILT_PRODUCTS_DIR"];
}
if (result && [result length] == 0) {
result = nil;
}
return result;
}
/// Find the path for a file named name.extension in your bundle.
// Searches for the following:
// "name.extension",
// "name.arch.extension",
// "name.arch.OSVersionMajor.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.extension"
// "name.arch.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.extension"
// "name.arch.OSVersionMajor.extension"
// "name.OSVersionMajor.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.arch.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.arch.extension"
// "name.OSVersionMajor.extension"
// "name.OSVersionMajor.OSVersionMinor.extension"
// "name.OSVersionMajor.OSVersionMinor.OSVersion.bugfix.extension"
// Do not include the ".extension" extension on your name.
//
// Args:
// name: The name for the file you would like to find.
// extension: the extension for the file you would like to find
//
// Returns:
// the path if the file exists in your bundle
// or nil if no file is found
//
- (NSString *)gtm_pathForFileNamed:(NSString*)name
extension:(NSString*)extension {
NSString *thePath = nil;
Class bundleClass = [GTMUnitTestingAdditionsBundleFinder class];
NSBundle *myBundle = [NSBundle bundleForClass:bundleClass];
_GTMDevAssert(myBundle,
@"Couldn't find bundle for class: %@ searching for file:%@.%@",
NSStringFromClass(bundleClass), name, extension);
// System Version
SInt32 major, minor, bugFix;
[GTMSystemVersion getMajor:&major minor:&minor bugFix:&bugFix];
NSString *systemVersions[4];
systemVersions[0] = [NSString stringWithFormat:@".%d.%d.%d",
major, minor, bugFix];
systemVersions[1] = [NSString stringWithFormat:@".%d.%d", major, minor];
systemVersions[2] = [NSString stringWithFormat:@".%d", major];
systemVersions[3] = @"";
NSString *extensions[2];
extensions[0]
= [NSString stringWithFormat:@".%@",
[GTMSystemVersion runtimeArchitecture]];
extensions[1] = @"";
size_t i, j;
// Note that we are searching for the most exact match first.
for (i = 0;
!thePath && i < sizeof(extensions) / sizeof(*extensions);
++i) {
for (j = 0;
!thePath && j < sizeof(systemVersions) / sizeof(*systemVersions);
j++) {
NSString *fullName = [NSString stringWithFormat:@"%@%@%@",
name, extensions[i], systemVersions[j]];
thePath = [myBundle pathForResource:fullName ofType:extension];
if (thePath) break;
fullName = [NSString stringWithFormat:@"%@%@%@",
name, systemVersions[j], extensions[i]];
thePath = [myBundle pathForResource:fullName ofType:extension];
}
}
return thePath;
}
- (NSString *)gtm_saveToPathForFileNamed:(NSString*)name
extension:(NSString*)extension {
NSString *systemArchitecture = [GTMSystemVersion runtimeArchitecture];
SInt32 major, minor, bugFix;
[GTMSystemVersion getMajor:&major minor:&minor bugFix:&bugFix];
NSString *fullName = [NSString stringWithFormat:@"%@.%@.%d.%d.%d",
name, systemArchitecture, major, minor, bugFix];
NSString *basePath = [[self class] gtm_getUnitTestSaveToDirectory];
return [[basePath stringByAppendingPathComponent:fullName]
stringByAppendingPathExtension:extension];
}
#pragma mark UnitTestImage
// Checks to see that system settings are valid for doing an image comparison.
// To be overridden by subclasses.
// Returns:
// YES if we can do image comparisons for this object type.
- (BOOL)gtm_areSystemSettingsValidForDoingImage {
return YES;
}
- (CFStringRef)gtm_imageUTI {
#if GTM_IPHONE_SDK
return kUTTypePNG;
#else
// Currently can't use PNG on Leopard. (10.5.2)
// Radar:5844618 PNG importer/exporter in ImageIO is lossy
return kUTTypeTIFF;
#endif
}
// Return the extension to be used for saving unittest images
//
// Returns
// An extension (e.g. "png")
- (NSString*)gtm_imageExtension {
CFStringRef uti = [self gtm_imageUTI];
#if GTM_IPHONE_SDK
if (CFEqual(uti, kUTTypePNG)) {
return @"png";
} else if (CFEqual(uti, kUTTypeJPEG)) {
return @"jpg";
} else {
_GTMDevAssert(NO, @"Illegal UTI for iPhone");
}
return nil;
#else
CFStringRef extension
= UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
_GTMDevAssert(extension, @"No extension for uti: %@", uti);
return GTMCFAutorelease(extension);
#endif
}
// Return image data in the format expected for gtm_imageExtension
// So for a "png" extension I would expect "png" data
//
// Returns
// NSData for image
- (NSData*)gtm_imageDataForImage:(CGImageRef)image {
NSData *data = nil;
#if GTM_IPHONE_SDK
// iPhone support
UIImage *uiImage = [UIImage imageWithCGImage:image];
CFStringRef uti = [self gtm_imageUTI];
if (CFEqual(uti, kUTTypePNG)) {
data = UIImagePNGRepresentation(uiImage);
} else if (CFEqual(uti, kUTTypeJPEG)) {
data = UIImageJPEGRepresentation(uiImage, 1.0f);
} else {
_GTMDevAssert(NO, @"Illegal UTI for iPhone");
}
#else
data = [NSMutableData data];
CGImageDestinationRef dest
= CGImageDestinationCreateWithData((CFMutableDataRef)data,
[self gtm_imageUTI],
1,
NULL);
// LZW Compression for TIFF
NSDictionary *tiffDict
= [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:NSTIFFCompressionLZW],
(const NSString*)kCGImagePropertyTIFFCompression,
nil];
NSDictionary *destProps
= [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:1.0f],
(const NSString*)kCGImageDestinationLossyCompressionQuality,
tiffDict,
(const NSString*)kCGImagePropertyTIFFDictionary,
nil];
CGImageDestinationAddImage(dest, image, (CFDictionaryRef)destProps);
CGImageDestinationFinalize(dest);
CFRelease(dest);
#endif
return data;
}
// Save the unitTestImage to an image file with name |name| at
// ~/Desktop/|name|.extension.
//
// Note: When running under Pulse automation output is redirected to the
// Pulse base directory.
//
// Args:
// name: The name for the image file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToImageNamed:(NSString*)name {
NSString *newPath = [self gtm_saveToPathForImageNamed:name];
return [self gtm_saveToImageAt:newPath];
}
// Save unitTestImage of |self| to an image file at path |path|.
//
// Args:
// name: The name for the image file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToImageAt:(NSString*)path {
if (!path) return NO;
NSData *data = [self gtm_imageRepresentation];
return [data writeToFile:path atomically:YES];
}
// Generates a CGImageRef from the image at |path|
// Args:
// path: The path to the image.
//
// Returns:
// A CGImageRef that you own, or nil if no image at path
- (CGImageRef)gtm_imageWithContentsOfFile:(NSString*)path {
CGImageRef imageRef = nil;
#if GTM_IPHONE_SDK
UIImage *image = [UIImage imageWithContentsOfFile:path];
if (image) {
imageRef = CGImageRetain(image.CGImage);
}
#else
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, (CFStringRef)path,
kCFURLPOSIXPathStyle, NO);
if (url) {
CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, NULL);
CFRelease(url);
if (imageSource) {
imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
CFRelease(imageSource);
}
}
#endif
return (CGImageRef)GTMCFAutorelease(imageRef);
}
/// Compares unitTestImage of |self| to the image located at |path|
//
// Args:
// path: the path to the image file you want to compare against.
// If diff is non-nil, it will contain an auto-released diff of the images.
//
// Returns:
// YES if they are equal, NO is they are not
// If diff is non-nil, it will contain an auto-released diff of the images.
//
- (BOOL)gtm_compareWithImageAt:(NSString*)path diffImage:(CGImageRef*)diff {
BOOL answer = NO;
if (diff) {
*diff = nil;
}
CGImageRef fileRep = [self gtm_imageWithContentsOfFile:path];
_GTMDevAssert(fileRep, @"Unable to create imagerep from %@", path);
CGImageRef imageRep = [self gtm_unitTestImage];
_GTMDevAssert(imageRep, @"Unable to create imagerep for %@", self);
size_t fileHeight = CGImageGetHeight(fileRep);
size_t fileWidth = CGImageGetWidth(fileRep);
size_t imageHeight = CGImageGetHeight(imageRep);
size_t imageWidth = CGImageGetWidth(imageRep);
if (fileHeight == imageHeight && fileWidth == imageWidth) {
// if all the sizes are equal, run through the bytes and compare
// them for equality.
// Do an initial fast check, if this fails and the caller wants a
// diff, we'll do the slow path and create the diff. The diff path
// could be optimized, but probably not necessary at this point.
answer = YES;
CGSize imageSize = CGSizeMake(fileWidth, fileHeight);
CGRect imageRect = CGRectMake(0, 0, fileWidth, fileHeight);
unsigned char *fileData;
unsigned char *imageData;
CGContextRef fileContext
= GTMCreateUnitTestBitmapContextOfSizeWithData(imageSize, &fileData);
_GTMDevAssert(fileContext, @"Unable to create filecontext");
CGContextDrawImage(fileContext, imageRect, fileRep);
CGContextRef imageContext
= GTMCreateUnitTestBitmapContextOfSizeWithData(imageSize, &imageData);
_GTMDevAssert(imageContext, @"Unable to create imageContext");
CGContextDrawImage(imageContext, imageRect, imageRep);
size_t fileBytesPerRow = CGBitmapContextGetBytesPerRow(fileContext);
size_t imageBytesPerRow = CGBitmapContextGetBytesPerRow(imageContext);
size_t row, col;
_GTMDevAssert(imageWidth * 4 <= imageBytesPerRow,
@"We expect image data to be 32bit RGBA");
for (row = 0; row < fileHeight && answer; row++) {
answer = memcmp(fileData + fileBytesPerRow * row,
imageData + imageBytesPerRow * row,
imageWidth * 4) == 0;
}
if (!answer && diff) {
answer = YES;
unsigned char *diffData;
CGContextRef diffContext
= GTMCreateUnitTestBitmapContextOfSizeWithData(imageSize, &diffData);
_GTMDevAssert(diffContext, @"Can't make diff context");
size_t diffRowBytes = CGBitmapContextGetBytesPerRow(diffContext);
for (row = 0; row < imageHeight; row++) {
uint32_t *imageRow = (uint32_t*)(imageData + imageBytesPerRow * row);
uint32_t *fileRow = (uint32_t*)(fileData + fileBytesPerRow * row);
uint32_t* diffRow = (uint32_t*)(diffData + diffRowBytes * row);
for (col = 0; col < imageWidth; col++) {
uint32_t imageColor = imageRow[col];
uint32_t fileColor = fileRow[col];
unsigned char imageAlpha = imageColor & 0xF;
unsigned char imageBlue = imageColor >> 8 & 0xF;
unsigned char imageGreen = imageColor >> 16 & 0xF;
unsigned char imageRed = imageColor >> 24 & 0xF;
unsigned char fileAlpha = fileColor & 0xF;
unsigned char fileBlue = fileColor >> 8 & 0xF;
unsigned char fileGreen = fileColor >> 16 & 0xF;
unsigned char fileRed = fileColor >> 24 & 0xF;
// Check to see if color is almost right.
// No matter how hard I've tried, I've still gotten occasionally
// screwed over by colorspaces not mapping correctly, and small
// sampling errors coming in. This appears to work for most cases.
// Almost equal is defined to check within 1% on all components.
BOOL equal = almostEqual(imageRed, fileRed) &&
almostEqual(imageGreen, fileGreen) &&
almostEqual(imageBlue, fileBlue) &&
almostEqual(imageAlpha, fileAlpha);
answer &= equal;
if (diff) {
uint32_t newColor;
if (equal) {
newColor = (((uint32_t)imageRed) << 24) +
(((uint32_t)imageGreen) << 16) +
(((uint32_t)imageBlue) << 8) +
(((uint32_t)imageAlpha) / 2);
} else {
newColor = 0xFF0000FF;
}
diffRow[col] = newColor;
}
}
}
*diff = CGBitmapContextCreateImage(diffContext);
free(diffData);
CFRelease(diffContext);
}
free(fileData);
CFRelease(fileContext);
free(imageData);
CFRelease(imageContext);
}
return answer;
}
// Find the path for an image by name in your bundle.
// Do not include the extension on your name.
//
// Args:
// name: The name for the image file you would like to find.
//
// Returns:
// the path if the image exists in your bundle
// or nil if no image to be found
//
- (NSString *)gtm_pathForImageNamed:(NSString*)name {
return [self gtm_pathForFileNamed:name
extension:[self gtm_imageExtension]];
}
- (NSString *)gtm_saveToPathForImageNamed:(NSString*)name {
return [self gtm_saveToPathForFileNamed:name
extension:[self gtm_imageExtension]];
}
// Gives us a representation of unitTestImage of |self|.
//
// Returns:
// a representation of image if successful
// nil if failed
//
- (NSData *)gtm_imageRepresentation {
CGImageRef imageRep = [self gtm_unitTestImage];
NSData *data = [self gtm_imageDataForImage:imageRep];
_GTMDevAssert(data, @"unable to create %@ from %@",
[self gtm_imageExtension], self);
return data;
}
#pragma mark UnitTestState
// Return the extension to be used for saving unittest states
//
// Returns
// An extension (e.g. "gtmUTState")
- (NSString*)gtm_stateExtension {
return @"gtmUTState";
}
// Save the encoded unit test state to a state file with name |name| at
// ~/Desktop/|name|.extension.
//
// Note: When running under Pulse automation output is redirected to the
// Pulse base directory.
//
// Args:
// name: The name for the state file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToStateNamed:(NSString*)name {
NSString *newPath = [self gtm_saveToPathForStateNamed:name];
return [self gtm_saveToStateAt:newPath];
}
// Save encoded unit test state of |self| to a state file at path |path|.
//
// Args:
// name: The name for the state file you would like saved.
//
// Returns:
// YES if the file was successfully saved.
//
- (BOOL)gtm_saveToStateAt:(NSString*)path {
if (!path) return NO;
NSDictionary *dictionary = [self gtm_stateRepresentation];
return [dictionary writeToFile:path atomically:YES];
}
// Compares encoded unit test state of |self| to the state file located at
// |path|
//
// Args:
// path: the path to the state file you want to compare against.
//
// Returns:
// YES if they are equal, NO is they are not
//
- (BOOL)gtm_compareWithStateAt:(NSString*)path {
NSDictionary *masterDict = [NSDictionary dictionaryWithContentsOfFile:path];
_GTMDevAssert(masterDict, @"Unable to create dictionary from %@", path);
NSDictionary *selfDict = [self gtm_stateRepresentation];
return [selfDict isEqual: masterDict];
}
// Find the path for a state by name in your bundle.
// Do not include the extension.
//
// Args:
// name: The name for the state file you would like to find.
//
// Returns:
// the path if the state exists in your bundle
// or nil if no state to be found
//
- (NSString *)gtm_pathForStateNamed:(NSString*)name {
return [self gtm_pathForFileNamed:name extension:[self gtm_stateExtension]];
}
- (NSString *)gtm_saveToPathForStateNamed:(NSString*)name {
return [self gtm_saveToPathForFileNamed:name
extension:[self gtm_stateExtension]];
}
// Gives us the encoded unit test state |self|
//
// Returns:
// the encoded state if successful
// nil if failed
//
- (NSDictionary *)gtm_stateRepresentation {
NSDictionary *dictionary = nil;
if ([self conformsToProtocol:@protocol(GTMUnitTestingEncoding)]) {
id<GTMUnitTestingEncoding> encoder = (id<GTMUnitTestingEncoding>)self;
GTMUnitTestingKeyedCoder *archiver;
archiver = [[[GTMUnitTestingKeyedCoder alloc] init] autorelease];
[encoder gtm_unitTestEncodeState:archiver];
dictionary = [archiver dictionary];
}
return dictionary;
}
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state. Encode data in the coder in the same
// manner that you would encode data in any other Keyed NSCoder subclass.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
// All impls of gtm_unitTestEncodeState
// should be calling [super gtm_unitTestEncodeState] as their first action.
_GTMDevAssert([inCoder isKindOfClass:[GTMUnitTestingKeyedCoder class]],
@"Coder must be of kind GTMUnitTestingKeyedCoder");
// If the object has a delegate, give it a chance to respond
if ([self respondsToSelector:@selector(delegate)]) {
id delegate = [self performSelector:@selector(delegate)];
if (delegate &&
[delegate respondsToSelector:@selector(gtm_unitTestEncoderWillEncode:inCoder:)]) {
[delegate gtm_unitTestEncoderWillEncode:self inCoder:inCoder];
}
}
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMNSObject+UnitTesting.m | Objective-C | bsd | 34,403 |
//
// GTMUnitTestingBindingTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMUnitTestingTest.h"
#import "GTMNSObject+BindingUnitTesting.h"
@interface GTMUnitTestingBindingTest : GTMTestCase {
int expectedFailureCount_;
}
@end
@interface GTMUnitTestingBindingBadClass : NSObject
@end
@implementation GTMUnitTestingBindingTest
// Iterates through all of our subviews testing the exposed bindings
- (void)doSubviewBindingTest:(NSView*)view {
NSArray *subviews = [view subviews];
NSView *subview;
GTM_FOREACH_OBJECT(subview, subviews) {
GTMTestExposedBindings(subview, @"testing %@", subview);
[self doSubviewBindingTest:subview];
}
}
- (void)testBindings {
// Get our window to work with and test it's bindings
GTMUnitTestingTestController *testWindowController
= [[GTMUnitTestingTestController alloc] initWithWindowNibName:@"GTMUnitTestingTest"];
NSWindow *window = [testWindowController window];
GTMTestExposedBindings(window, @"Window failed binding test");
[self doSubviewBindingTest:[window contentView]];
[window close];
[testWindowController release];
// Run a test against something with no bindings.
// We're expecting a failure here.
expectedFailureCount_ = 1;
GTMTestExposedBindings(@"foo", @"testing no bindings");
STAssertEquals(expectedFailureCount_, 0, @"Didn't get expected failures testing bindings");
// Run test against some with bad bindings.
// We're expecting failures here.
expectedFailureCount_ = 4;
GTMUnitTestingBindingBadClass *bad = [[[GTMUnitTestingBindingBadClass alloc] init] autorelease];
GTMTestExposedBindings(bad, @"testing bad bindings");
STAssertEquals(expectedFailureCount_, 0, @"Didn't get expected failures testing bad bindings");
}
- (void)failWithException:(NSException *)anException {
if (expectedFailureCount_ > 0) {
expectedFailureCount_ -= 1;
} else {
[super failWithException:anException]; // COV_NF_LINE - not expecting exception
}
}
@end
// Forces several error cases in our binding tests to test them
@implementation GTMUnitTestingBindingBadClass
NSString *const kGTMKeyWithNoClass = @"keyWithNoClass";
NSString *const kGTMKeyWithNoValue = @"keyWithNoValue";
NSString *const kGTMKeyWeCantSet = @"keyWeCantSet";
NSString *const kGTMKeyThatIsntEqual = @"keyThatIsntEqual";
- (NSArray *)exposedBindings {
return [NSArray arrayWithObjects:kGTMKeyWithNoClass,
kGTMKeyWithNoValue,
kGTMKeyWeCantSet,
kGTMKeyThatIsntEqual,
nil];
}
- (NSArray*)gtm_unitTestExposedBindingsTestValues:(NSString*)binding {
GTMBindingUnitTestData *data
= [GTMBindingUnitTestData testWithIdentityValue:kGTMKeyThatIsntEqual];
return [NSArray arrayWithObject:data];
}
- (Class)valueClassForBinding:(NSString*)binding {
return [binding isEqualTo:kGTMKeyWithNoClass] ? nil : [NSString class];
}
- (id)valueForKey:(NSString*)binding {
if ([binding isEqualTo:kGTMKeyWithNoValue]) {
[NSException raise:NSUndefinedKeyException format:nil];
}
return @"foo";
}
- (void)setValue:(id)value forKey:(NSString*)binding {
if ([binding isEqualTo:kGTMKeyWeCantSet]) {
[NSException raise:NSUndefinedKeyException format:nil];
}
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMUnitTestingBindingTest.m | Objective-C | bsd | 3,901 |
//
// GTMCALayer+UnitTesting.h
//
// Code for making unit testing of graphics/UI easier. Generally you
// will only want to look at the macros:
// GTMAssertDrawingEqualToFile
// GTMAssertViewRepEqualToFile
// and the protocol GTMUnitTestCALayerDrawer. When using these routines
// make sure you are using device colors and not calibrated/generic colors
// or else your test graphics WILL NOT match across devices/graphics cards.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <QuartzCore/QuartzCore.h>
#import "GTMNSObject+UnitTesting.h"
// Category for making unit testing of graphics/UI easier.
// Allows you to take a state of a view. Supports both image and state.
// See GTMNSObject+UnitTesting.h for details.
@interface CALayer (GTMUnitTestingAdditions) <GTMUnitTestingImaging>
// Returns whether gtm_unitTestEncodeState should recurse into sublayers
//
// Returns:
// should gtm_unitTestEncodeState pick up sublayer state.
- (BOOL)gtm_shouldEncodeStateForSublayers;
@end
@interface NSObject (GTMCALayerUnitTestingDelegateMethods)
// Delegate method that allows a delegate for a layer to
// decide whether we should recurse
- (BOOL)gtm_shouldEncodeStateForSublayersOfLayer:(CALayer*)layer;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMCALayer+UnitTesting.h | Objective-C | bsd | 1,796 |
#!/bin/bash
# RunIPhoneUnitTest.sh
# Copyright 2008 Google Inc.
#
# 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.
#
# Runs all unittests through the iPhone simulator. We don't handle running them
# on the device. To run on the device just choose "run".
set -o errexit
set -o nounset
set -o verbose
# Controlling environment variables:
# GTM_DISABLE_ZOMBIES -
# Set to a non-zero value to turn on zombie checks. You will probably
# want to turn this off if you enable leaks.
GTM_DISABLE_ZOMBIES=${GTM_DISABLE_ZOMBIES:=1}
# GTM_ENABLE_LEAKS -
# Set to a non-zero value to turn on the leaks check. You will probably want
# to disable zombies, otherwise you will get a lot of false positives.
# GTM_DISABLE_TERMINATION
# Set to a non-zero value so that the app doesn't terminate when it's finished
# running tests. This is useful when using it with external tools such
# as Instruments.
# GTM_LEAKS_SYMBOLS_TO_IGNORE
# List of comma separated symbols that leaks should ignore. Mainly to control
# leaks in frameworks you don't have control over.
# Search this file for GTM_LEAKS_SYMBOLS_TO_IGNORE to see examples.
# Please feel free to add other symbols as you find them but make sure to
# reference Radars or other bug systems so we can track them.
# GTM_REMOVE_GCOV_DATA
# Before starting the test, remove any *.gcda files for the current run so
# you won't get errors when the source file has changed and the data can't
# be merged.
#
GTM_REMOVE_GCOV_DATA=${GTM_REMOVE_GCOV_DATA:=0}
ScriptDir=$(dirname "$(echo $0 | sed -e "s,^\([^/]\),$(pwd)/\1,")")
ScriptName=$(basename "$0")
ThisScript="${ScriptDir}/${ScriptName}"
GTMXcodeNote() {
echo ${ThisScript}:${1}: note: GTM ${2}
}
if [ "$PLATFORM_NAME" == "iphonesimulator" ]; then
# We kill the iPhone simulator because otherwise we run into issues where
# the unittests fail becuase the simulator is currently running, and
# at this time the iPhone SDK won't allow two simulators running at the same
# time.
set +e
/usr/bin/killall "iPhone Simulator"
set -e
if [ $GTM_REMOVE_GCOV_DATA -ne 0 ]; then
if [ "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" != "-" ]; then
if [ -d "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" ]; then
GTMXcodeNote ${LINENO} "Removing any .gcda files"
(cd "${OBJECT_FILE_DIR}-${CURRENT_VARIANT}" && \
find . -type f -name "*.gcda" -print0 | xargs -0 rm -f )
fi
fi
fi
export DYLD_ROOT_PATH="$SDKROOT"
export DYLD_FRAMEWORK_PATH="$CONFIGURATION_BUILD_DIR"
export IPHONE_SIMULATOR_ROOT="$SDKROOT"
export CFFIXED_USER_HOME="$TEMP_FILES_DIR/iPhone Simulator User Dir"
# See http://developer.apple.com/technotes/tn2004/tn2124.html for an
# explanation of these environment variables.
export MallocScribble=YES
export MallocPreScribble=YES
export MallocGuardEdges=YES
export MallocStackLogging=YES
export NSAutoreleaseFreedObjectCheckEnabled=YES
# Turn on the mostly undocumented OBJC_DEBUG stuff.
export OBJC_DEBUG_FRAGILE_SUPERCLASSES=YES
export OBJC_DEBUG_UNLOAD=YES
# Turned off due to the amount of false positives from NS classes.
# export OBJC_DEBUG_FINALIZERS=YES
export OBJC_DEBUG_NIL_SYNC=YES
export OBJC_PRINT_REPLACED_METHODS=YES
if [ $GTM_DISABLE_ZOMBIES -eq 0 ]; then
GTMXcodeNote ${LINENO} "Enabling zombies"
export CFZombieLevel=3
export NSZombieEnabled=YES
fi
# Cleanup user home and documents directory
if [ -d "$CFFIXED_USER_HOME" ]; then
rm -rf "$CFFIXED_USER_HOME"
fi
mkdir "$CFFIXED_USER_HOME"
mkdir "$CFFIXED_USER_HOME/Documents"
# 6251475 iPhone simulator leaks @ CFHTTPCookieStore shutdown if
# CFFIXED_USER_HOME empty
GTM_LEAKS_SYMBOLS_TO_IGNORE="CFHTTPCookieStore"
"$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents
else
GTMXcodeNote ${LINENO} "Skipping running of unittests for device build."
fi
exit 0
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/RunIPhoneUnitTest.sh | Shell | bsd | 4,429 |
//
// GTMNSObject+BindingUnitTesting.h
//
// Utilities for doing advanced unittesting with object bindings.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#include <Foundation/Foundation.h>
// Utility functions for GTMTestExposedBindings Macro. Don't use it directly
// but use the macro below instead
BOOL GTMDoExposedBindingsFunctionCorrectly(NSObject *object,
NSArray **errors);
// Tests the setters and getters for exposed bindings
// For objects that expose bindings, this tests them for you, saving you from
// having to write a whole pile of set/get test code if you add binding support.
// You will need to implement valueClassForBinding: for your bindings,
// and you may possibly want to implement unitTestExposedBindingsToIgnore
// and unitTestExposedBindingsTestValues. See descriptions of those
// methods below for details.
// Implemented as a macro to match the rest of the SenTest macros.
//
// Args:
// a1: The object to be checked.
// description: A format string as in the printf() function.
// Can be nil or an empty string but must be present.
// ...: A variable number of arguments to the format string. Can be absent.
//
#define GTMTestExposedBindings(a1, description, ...) \
do { \
NSObject *a1Object = (a1); \
NSArray *errors = nil; \
BOOL isGood = GTMDoExposedBindingsFunctionCorrectly(a1Object, &errors); \
if (!isGood) { \
NSString *failString; \
GTM_FOREACH_OBJECT(failString, errors) { \
if (description) { \
STFail(@"%@: %@", failString, STComposeString(description, ##__VA_ARGS__)); \
} else { \
STFail(@"%@", failString); \
} \
} \
} \
} while(0)
// Utility class for setting up Binding Tests. Basically a pair of a value to
// set a binding to, followed by the expected return value.
// See description of gtm_unitTestExposedBindingsTestValues: below
// for example of usage.
@interface GTMBindingUnitTestData : NSObject {
@private
id valueToSet_;
id expectedValue_;
}
+ (id)testWithIdentityValue:(id)value;
+ (id)testWithValue:(id)value expecting:(id)expecting;
- (id)initWithValue:(id)value expecting:(id)expecting;
- (id)valueToSet;
- (id)expectedValue;
@end
@interface NSObject (GTMBindingUnitTestingAdditions)
// Allows you to ignore certain bindings when running GTMTestExposedBindings
// If you have bindings you want to ignore, add them to the array returned
// by this method. The standard way to implement this would be:
// - (NSMutableArray*)unitTestExposedBindingsToIgnore {
// NSMutableArray *array = [super unitTestExposedBindingsToIgnore];
// [array addObject:@"bindingToIgnore1"];
// ...
// return array;
// }
// The NSObject implementation by default will ignore NSFontBoldBinding,
// NSFontFamilyNameBinding, NSFontItalicBinding, NSFontNameBinding and
// NSFontSizeBinding if your exposed bindings contains NSFontBinding because
// the NSFont*Bindings are NOT KVC/KVO compliant.
- (NSMutableArray*)gtm_unitTestExposedBindingsToIgnore;
// Allows you to set up test values for your different bindings.
// if you have certain values you want to test against your bindings, add
// them to the array returned by this method. The array is an array of
// GTMBindingUnitTestData.
// The standard way to implement this would be:
// - (NSMutableArray*)gtm_unitTestExposedBindingsTestValues:(NSString*)binding {
// NSMutableArray *dict = [super unitTestExposedBindingsTestValues:binding];
// if ([binding isEqualToString:@"myBinding"]) {
// MySpecialBindingValueSet *value
// = [[[MySpecialBindingValueSet alloc] init] autorelease];
// [array addObject:[GTMBindingUnitTestData testWithIdentityValue:value]];
// ...
// else if ([binding isEqualToString:@"myBinding2"]) {
// ...
// }
// return array;
// }
// The NSObject implementation handles many of the default bindings, and
// gives you a reasonable set of test values to start.
// See the implementation for the current list of bindings, and values that we
// set for those bindings.
- (NSMutableArray*)gtm_unitTestExposedBindingsTestValues:(NSString*)binding;
// A special version of isEqualTo to test whether two binding values are equal
// by default it calls directly to isEqualTo: but can be overridden for special
// cases (like NSImages) where the standard isEqualTo: isn't sufficient.
- (BOOL)gtm_unitTestIsEqualTo:(id)value;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMNSObject+BindingUnitTesting.h | Objective-C | bsd | 4,990 |
//
// GTMCALayer+UnitTesting.m
//
// Category for making unit testing of graphics/UI easier.
// Allows you to save a view out to a image file, and compare a view
// with a previously stored representation to make sure it hasn't changed.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMCALayer+UnitTesting.h"
#import "GTMGarbageCollection.h"
@implementation CALayer (GTMUnitTestingAdditions)
// Returns an image containing a representation of the object
// suitable for use in comparing against a master image.
// NB this means that all colors should be from "NSDevice" color space
// Does all of it's drawing with smoothfonts and antialiasing off
// to avoid issues with font smoothing settings and antialias differences
// between ppc and x86.
//
// Returns:
// an image of the object
- (CGImageRef)gtm_unitTestImage {
CGRect bounds = [self bounds];
CGSize size = CGSizeMake(CGRectGetWidth(bounds), CGRectGetHeight(bounds));
CGContextRef context = GTMCreateUnitTestBitmapContextOfSizeWithData(size,
NULL);
_GTMDevAssert(context, @"Couldn't create context");
// iPhone renders are flipped
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, size.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(context, transform);
[self renderInContext:context];
CGImageRef image = CGBitmapContextCreateImage(context);
CFRelease(context);
return (CGImageRef)GTMCFAutorelease(image);
}
// Encodes the state of an object in a manner suitable for comparing
// against a master state file so we can determine whether the
// object is in a suitable state.
//
// Arguments:
// inCoder - the coder to encode our state into
- (void)gtm_unitTestEncodeState:(NSCoder*)inCoder {
[super gtm_unitTestEncodeState:inCoder];
[inCoder encodeBool:[self isHidden] forKey:@"LayerIsHidden"];
[inCoder encodeBool:[self isDoubleSided] forKey:@"LayerIsDoublesided"];
[inCoder encodeBool:[self isOpaque] forKey:@"LayerIsOpaque"];
[inCoder encodeFloat:[self opacity] forKey:@"LayerOpacity"];
// TODO: There is a ton more we can add here. What are we interested in?
if ([self gtm_shouldEncodeStateForSublayers]) {
int i = 0;
for (CALayer *subLayer in [self sublayers]) {
[inCoder encodeObject:subLayer
forKey:[NSString stringWithFormat:@"CALayerSubLayer %d", i]];
i = i + 1;
}
}
}
// Returns whether gtm_unitTestEncodeState should recurse into sublayers
//
// Returns:
// should gtm_unitTestEncodeState pick up sublayer state.
- (BOOL)gtm_shouldEncodeStateForSublayers {
BOOL value = YES;
if([self.delegate respondsToSelector:@selector(gtm_shouldEncodeStateForSublayersOfLayer:)]) {
value = [self.delegate gtm_shouldEncodeStateForSublayersOfLayer:self];
}
return value;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/UnitTesting/GTMCALayer+UnitTesting.m | Objective-C | bsd | 3,468 |
//
// GTMHTTPFetcher.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
// This is essentially a wrapper around NSURLConnection for POSTs and GETs.
// If setPostData: is called, then POST is assumed.
//
// When would you use this instead of NSURLConnection?
//
// - When you just want the result from a GET or POST
// - When you want the "standard" behavior for connections (redirection handling
// an so on)
// - When you want to avoid cookie collisions with Safari and other applications
// - When you want to provide if-modified-since headers
// - When you need to set a credential for the http
// - When you want to avoid changing WebKit's cookies
//
// This is assumed to be a one-shot fetch request; don't reuse the object
// for a second fetch.
//
// The fetcher may be created auto-released, in which case it will release
// itself after the fetch completion callback. The fetcher
// is implicitly retained as long as a connection is pending.
//
// But if you may need to cancel the fetcher, allocate it with initWithRequest:
// and have the delegate release the fetcher in the callbacks.
//
// Sample usage:
//
// NSURLRequest *request = [NSURLRequest requestWithURL:myURL];
// GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher httpFetcherWithRequest:request];
//
// [myFetcher setPostData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; // for POSTs
//
// [myFetcher setCredential:[NSURLCredential authCredentialWithUsername:@"foo"
// password:@"bar"]]; // optional http credential
//
// [myFetcher setFetchHistory:myMutableDictionary]; // optional, for persisting modified-dates
//
// [myFetcher beginFetchWithDelegate:self
// didFinishSelector:@selector(myFetcher:finishedWithData:)
// didFailSelector:@selector(myFetcher:failedWithError:)];
//
// Upon fetch completion, the callback selectors are invoked; they should have
// these signatures (you can use any callback method names you want so long as
// the signatures match these):
//
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData;
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error;
//
// NOTE: Fetches may retrieve data from the server even though the server
// returned an error. The failWithError selector is called when the server
// status is >= 300 (along with any server-supplied data, usually
// some html explaining the error).
// Status codes are at <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
//
//
// Proxies:
//
// Proxy handling is invisible so long as the system has a valid credential in
// the keychain, which is normally true (else most NSURL-based apps would have
// difficulty.) But when there is a proxy authetication error, the the fetcher
// will call the failedWithError: method with the NSURLChallenge in the error's
// userInfo. The error method can get the challenge info like this:
//
// NSURLAuthenticationChallenge *challenge
// = [[error userInfo] objectForKey:kGTMHTTPFetcherErrorChallengeKey];
// BOOL isProxyChallenge = [[challenge protectionSpace] isProxy];
//
// If a proxy error occurs, you can ask the user for the proxy username/password
// and call fetcher's setProxyCredential: to provide those for the
// next attempt to fetch.
//
//
// Cookies:
//
// There are three supported mechanisms for remembering cookies between fetches.
//
// By default, GTMHTTPFetcher uses a mutable array held statically to track
// cookies for all instantiated fetchers. This avoids server cookies being set
// by servers for the application from interfering with Safari cookie settings,
// and vice versa. The fetcher cookies are lost when the application quits.
//
// To rely instead on WebKit's global NSHTTPCookieStorage, call
// setCookieStorageMethod: with kGTMHTTPFetcherCookieStorageMethodSystemDefault.
//
// If you provide a fetch history (such as for periodic checks, described
// below) then the cookie storage mechanism is set to use the fetch
// history rather than the static storage.
//
//
// Fetching for periodic checks:
//
// The fetcher object can track "Last-modified" dates on returned data and
// provide an "If-modified-since" header. This allows the server to save
// bandwidth by providing a "Nothing changed" status message instead of response
// data.
//
// To get this behavior, provide a persistent mutable dictionary to setFetchHistory:,
// and look for the failedWithError: callback with code 304
// (kGTMHTTPFetcherStatusNotModified) like this:
//
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error {
// if ([[error domain] isEqual:kGTMHTTPFetcherStatusDomain] &&
// ([error code] == kGTMHTTPFetcherStatusNotModified)) {
// // [[error userInfo] objectForKey:kGTMHTTPFetcherStatusDataKey] is
// // empty; use the data from the previous finishedWithData: for this URL
// } else {
// // handle other server status code
// }
// }
//
// The fetchHistory mutable dictionary should be maintained by the client between
// fetches and given to each fetcher intended to have the If-modified-since header
// or the same cookie storage.
//
//
// Monitoring received data
//
// The optional received data selector should have the signature
//
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar;
//
// The bytes received so far are [dataReceivedSoFar length]. This number may go down
// if a redirect causes the download to begin again from a new server.
// If supplied by the server, the anticipated total download size is available as
// [[myFetcher response] expectedContentLength] (may be -1 for unknown
// download sizes.)
//
//
// Automatic retrying of fetches
//
// The fetcher can optionally create a timer and reattempt certain kinds of
// fetch failures (status codes 408, request timeout; 503, service unavailable;
// 504, gateway timeout; networking errors NSURLErrorTimedOut and
// NSURLErrorNetworkConnectionLost.) The user may set a retry selector to
// customize the type of errors which will be retried.
//
// Retries are done in an exponential-backoff fashion (that is, after 1 second,
// 2, 4, 8, and so on.)
//
// Enabling automatic retries looks like this:
// [myFetcher setIsRetryEnabled:YES];
//
// With retries enabled, the success or failure callbacks are called only
// when no more retries will be attempted. Calling the fetcher's stopFetching
// method will terminate the retry timer, without the finished or failure
// selectors being invoked.
//
// Optionally, the client may set the maximum retry interval:
// [myFetcher setMaxRetryInterval:60.]; // in seconds; default is 600 seconds
//
// Also optionally, the client may provide a callback selector to determine
// if a status code or other error should be retried.
// [myFetcher setRetrySelector:@selector(myFetcher:willRetry:forError:)];
//
// If set, the retry selector should have the signature:
// -(BOOL)fetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error
// and return YES to set the retry timer or NO to fail without additional
// fetch attempts.
//
// The retry method may return the |suggestedWillRetry| argument to get the
// default retry behavior. Server status codes are present in the error
// argument, and have the domain kGTMHTTPFetcherStatusDomain. The user's method
// may look something like this:
//
// -(BOOL)myFetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error {
//
// // perhaps examine [error domain] and [error code], or [fetcher retryCount]
// //
// // return YES to start the retry timer, NO to proceed to the failure
// // callback, or |suggestedWillRetry| to get default behavior for the
// // current error domain and code values.
// return suggestedWillRetry;
// }
#pragma once
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
#undef _EXTERN
#undef _INITIALIZE_AS
#ifdef GTMHTTPFETCHER_DEFINE_GLOBALS
#define _EXTERN
#define _INITIALIZE_AS(x) =x
#else
#define _EXTERN extern
#define _INITIALIZE_AS(x)
#endif
// notifications & errors
_EXTERN NSString* const kGTMHTTPFetcherErrorDomain _INITIALIZE_AS(@"com.google.mactoolbox.HTTPFetcher");
_EXTERN NSString* const kGTMHTTPFetcherStatusDomain _INITIALIZE_AS(@"com.google.mactoolbox.HTTPStatus");
_EXTERN NSString* const kGTMHTTPFetcherErrorChallengeKey _INITIALIZE_AS(@"challenge");
_EXTERN NSString* const kGTMHTTPFetcherStatusDataKey _INITIALIZE_AS(@"data"); // any data returns w/ a kGTMHTTPFetcherStatusDomain error
// fetch history mutable dictionary keys
_EXTERN NSString* const kGTMHTTPFetcherHistoryLastModifiedKey _INITIALIZE_AS(@"FetchHistoryLastModified");
_EXTERN NSString* const kGTMHTTPFetcherHistoryDatedDataKey _INITIALIZE_AS(@"FetchHistoryDatedDataCache");
_EXTERN NSString* const kGTMHTTPFetcherHistoryCookiesKey _INITIALIZE_AS(@"FetchHistoryCookies");
enum {
kGTMHTTPFetcherErrorDownloadFailed = -1,
kGTMHTTPFetcherErrorAuthenticationChallengeFailed = -2,
kGTMHTTPFetcherStatusNotModified = 304
};
enum {
kGTMHTTPFetcherCookieStorageMethodStatic = 0,
kGTMHTTPFetcherCookieStorageMethodFetchHistory = 1,
kGTMHTTPFetcherCookieStorageMethodSystemDefault = 2
};
typedef NSUInteger GTMHTTPFetcherCookieStorageMethod;
/// async retrieval of an http get or post
@interface GTMHTTPFetcher : NSObject {
NSMutableURLRequest *request_;
NSURLConnection *connection_; // while connection_ is non-nil, delegate_ is retained
NSMutableData *downloadedData_;
NSURLCredential *credential_; // username & password
NSURLCredential *proxyCredential_; // credential supplied to proxy servers
NSData *postData_;
NSInputStream *postStream_;
NSMutableData *loggedStreamData_;
NSURLResponse *response_; // set in connection:didReceiveResponse:
id delegate_; // WEAK (though retained during an open connection)
SEL finishedSEL_; // should by implemented by delegate
SEL failedSEL_; // should be implemented by delegate
SEL receivedDataSEL_; // optional, set with setReceivedDataSelector
id userData_; // retained, if set by caller
NSArray *runLoopModes_; // optional, for 10.5 and later
NSMutableDictionary *fetchHistory_; // if supplied by the caller, used for Last-Modified-Since checks and cookies
BOOL shouldCacheDatedData_; // if true, remembers and returns data marked with a last-modified date
GTMHTTPFetcherCookieStorageMethod cookieStorageMethod_; // constant from above
BOOL isRetryEnabled_; // user wants auto-retry
SEL retrySEL_; // optional; set with setRetrySelector
NSTimer *retryTimer_;
unsigned int retryCount_;
NSTimeInterval maxRetryInterval_; // default 600 seconds
NSTimeInterval minRetryInterval_; // random between 1 and 2 seconds
NSTimeInterval retryFactor_; // default interval multiplier is 2
NSTimeInterval lastRetryInterval_;
}
/// create a fetcher
//
// httpFetcherWithRequest will return an autoreleased fetcher, but if
// the connection is successfully created, the connection should retain the
// fetcher for the life of the connection as well. So the caller doesn't have
// to retain the fetcher explicitly unless they want to be able to cancel it.
+ (GTMHTTPFetcher *)httpFetcherWithRequest:(NSURLRequest *)request;
// designated initializer
- (id)initWithRequest:(NSURLRequest *)request;
- (NSMutableURLRequest *)request;
- (void)setRequest:(NSURLRequest *)theRequest;
// setting the credential is optional; it is used if the connection receives
// an authentication challenge
- (NSURLCredential *)credential;
- (void)setCredential:(NSURLCredential *)theCredential;
// setting the proxy credential is optional; it is used if the connection
// receives an authentication challenge from a proxy
- (NSURLCredential *)proxyCredential;
- (void)setProxyCredential:(NSURLCredential *)theCredential;
// if post data or stream is not set, then a GET retrieval method is assumed
- (NSData *)postData;
- (void)setPostData:(NSData *)theData;
// beware: In 10.4, NSInputStream fails to copy or retain
// the data it was initialized with, contrary to docs.
// NOTE: if logging is enabled and GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING is
// 1, postStream will return a GTMProgressMonitorInputStream that wraps your
// stream (so the upload can be logged).
- (NSInputStream *)postStream;
- (void)setPostStream:(NSInputStream *)theStream;
- (GTMHTTPFetcherCookieStorageMethod)cookieStorageMethod;
- (void)setCookieStorageMethod:(GTMHTTPFetcherCookieStorageMethod)method;
// returns cookies from the currently appropriate cookie storage
- (NSArray *)cookiesForURL:(NSURL *)theURL;
// the delegate is not retained except during the connection
- (id)delegate;
- (void)setDelegate:(id)theDelegate;
// the delegate's optional receivedData selector has a signature like:
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar;
- (SEL)receivedDataSelector;
- (void)setReceivedDataSelector:(SEL)theSelector;
// retrying; see comments at the top of the file. Calling
// setIsRetryEnabled(YES) resets the min and max retry intervals.
- (BOOL)isRetryEnabled;
- (void)setIsRetryEnabled:(BOOL)flag;
// retry selector is optional for retries.
//
// If present, it should have the signature:
// -(BOOL)fetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error
// and return YES to cause a retry. See comments at the top of this file.
- (SEL)retrySelector;
- (void)setRetrySelector:(SEL)theSel;
// retry intervals must be strictly less than maxRetryInterval, else
// they will be limited to maxRetryInterval and no further retries will
// be attempted. Setting maxRetryInterval to 0.0 will reset it to the
// default value, 600 seconds.
- (NSTimeInterval)maxRetryInterval;
- (void)setMaxRetryInterval:(NSTimeInterval)secs;
// Starting retry interval. Setting minRetryInterval to 0.0 will reset it
// to a random value between 1.0 and 2.0 seconds. Clients should normally not
// call this except for unit testing.
- (NSTimeInterval)minRetryInterval;
- (void)setMinRetryInterval:(NSTimeInterval)secs;
// Multiplier used to increase the interval between retries, typically 2.0.
// Clients should not need to call this.
- (double)retryFactor;
- (void)setRetryFactor:(double)multiplier;
// number of retries attempted
- (unsigned int)retryCount;
// interval delay to precede next retry
- (NSTimeInterval)nextRetryInterval;
/// Begin fetching the request.
//
/// |delegate| can optionally implement the two selectors |finishedSEL| and
/// |networkFailedSEL| or pass nil for them.
/// Returns YES if the fetch is initiated. Delegate is retained between
/// the beginFetch call until after the finish/fail callbacks.
//
// finishedSEL has a signature like:
// - (void)fetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data
// failedSEL has a signature like:
// - (void)fetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error
//
- (BOOL)beginFetchWithDelegate:(id)delegate
didFinishSelector:(SEL)finishedSEL
didFailSelector:(SEL)networkFailedSEL;
// Returns YES if this is in the process of fetching a URL
- (BOOL)isFetching;
/// Cancel the fetch of the request that's currently in progress
- (void)stopFetching;
/// return the status code from the server response
- (NSInteger)statusCode;
/// the response, once it's been received
- (NSURLResponse *)response;
- (void)setResponse:(NSURLResponse *)response;
// Fetch History is a useful, but a little complex at times...
//
// The caller should provide a mutable dictionary that can be used for storing
// Last-Modified-Since checks and cookie storage (setFetchHistory implicity
// calls setCookieStorageMethod w/
// kGTMHTTPFetcherCookieStorageMethodFetchHistory if you passed a dictionary,
// kGTMHTTPFetcherCookieStorageMethodStatic if you passed nil.
//
// The caller can hold onto the dictionary to reuse the modification dates and
// cookies across multiple fetcher instances.
//
// With a fetch history dictionary setup, the http fetcher cache has the
// modification dates returned by the servers cached, and future fetches will
// return 304 to indicate the data hasn't changed since then (the data in the
// NSError object will be of length zero to show nothing was fetched). This
// reduces load on the server when the response data has not changed. See
// shouldCacheDatedData below for additional 304 support.
//
// Side effect: setFetchHistory: implicitly calls setCookieStorageMethod:
- (NSMutableDictionary *)fetchHistory;
- (void)setFetchHistory:(NSMutableDictionary *)fetchHistory;
// For fetched data with a last-modified date, the fetcher can optionally cache
// the response data in the fetch history and return cached data instead of a
// 304 error. Set this to NO if you want to manually handle last-modified and
// status 304 (Not changed) rather than be delivered cached data from previous
// fetches. Default is NO. When a cache result is returned, the didFinish
// selector is called with the data, and [fetcher status] returns 200.
//
// If the caller has already provided a fetchHistory dictionary, they can also
// enable fetcher handling of 304 (not changed) status responses. By setting
// shouldCacheDatedData to YES, the fetcher will save any response that has a
// last modifed reply header into the fetchHistory. Then any future fetches
// using that same fetchHistory will automatically load the cached response and
// return it to the caller (with a status of 200) in place of the 304 server
// reply.
- (BOOL)shouldCacheDatedData;
- (void)setShouldCacheDatedData:(BOOL)flag;
// Delete the last-modified dates and cached data from the fetch history.
- (void)clearDatedDataHistory;
/// userData is retained for the convenience of the caller
- (id)userData;
- (void)setUserData:(id)theObj;
// using the fetcher while a modal dialog is displayed requires setting the
// run-loop modes to include NSModalPanelRunLoopMode
//
// setting run loop modes does nothing if they are not supported,
// such as on 10.4
- (NSArray *)runLoopModes;
- (void)setRunLoopModes:(NSArray *)modes;
+ (BOOL)doesSupportRunLoopModes;
+ (NSArray *)defaultRunLoopModes;
+ (void)setDefaultRunLoopModes:(NSArray *)modes;
// users who wish to replace GTMHTTPFetcher's use of NSURLConnection
// can do so globally here. The replacement should be a subclass of
// NSURLConnection.
+ (Class)connectionClass;
+ (void)setConnectionClass:(Class)theClass;
@end
// GTM HTTP Logging
//
// All traffic using GTMHTTPFetcher can be easily logged. Call
//
// [GTMHTTPFetcher setIsLoggingEnabled:YES];
//
// to begin generating log files.
//
// Log files are put into a folder on the desktop called "GTMHTTPDebugLogs"
// unless another directory is specified with +setLoggingDirectory.
//
// Each run of an application gets a separate set of log files. An html
// file is generated to simplify browsing the run's http transactions.
// The html file includes javascript links for inline viewing of uploaded
// and downloaded data.
//
// A symlink is created in the logs folder to simplify finding the html file
// for the latest run of the application; the symlink is called
//
// AppName_http_log_newest.html
//
// For better viewing of XML logs, use Camino or Firefox rather than Safari.
//
// Projects may define GTM_HTTPFETCHER_ENABLE_LOGGING to 0 to remove all of the
// logging code (it defaults to 1). By default, any data uploaded via PUT/POST
// w/ and NSInputStream will not be logged. You can enable this logging by
// defining GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING to 1 (it defaults to 0).
//
@interface GTMHTTPFetcher (GTMHTTPFetcherLogging)
// Note: the default logs directory is ~/Desktop/GTMHTTPDebugLogs; it will be
// created as needed. If a custom directory is set, the directory should
// already exist.
+ (void)setLoggingDirectory:(NSString *)path;
+ (NSString *)loggingDirectory;
// client apps can turn logging on and off
+ (void)setIsLoggingEnabled:(BOOL)flag;
+ (BOOL)isLoggingEnabled;
// client apps can optionally specify process name and date string used in
// log file names
+ (void)setLoggingProcessName:(NSString *)str;
+ (NSString *)loggingProcessName;
+ (void)setLoggingDateStamp:(NSString *)str;
+ (NSString *)loggingDateStamp;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPFetcher.h | Objective-C | bsd | 21,151 |
//
// GTMScriptRunner.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
/// Encapsulates the interaction with an interpreter for running scripts.
// This class manages the interaction with some command-line interpreter (e.g.,
// a shell, perl, python) and allows you to run expressions through the
// interpreter, and even full scripts that reside in files on disk. By default,
// the "/bin/sh" interpreter is used, but others may be explicitly specified.
// This can be a convenient way to run quick shell commands from Cocoa, or even
// interact with other shell tools such as "bc", or even "gdb".
//
// It's important to note that by default commands and scripts will have their
// environments erased before execution. You can control the environment they
// get with the -setEnvironment: method.
//
// The best way to show what this class does is to show some examples.
//
// Examples:
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// NSString *output = [sr run:@"ls -l /dev/null"];
// /* output == "crw-rw-rw- 1 root wheel 3, 2 Mar 22 10:35 /dev/null" */
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// NSString *output = [sr runScript:@"/path/to/my/script.sh"];
// /* output == the standard output from the script*/
//
// GTMScriptRunner *sr = [GTMScriptRunner runnerWithPerl];
// NSString *output = [sr run:@"print 'A'x4"];
// /* output == "AAAA" */
//
// See the unit test file for more examples.
//
@interface GTMScriptRunner : NSObject {
@private
NSString *interpreter_;
NSArray *interpreterArgs_;
NSDictionary *environment_;
BOOL trimsWhitespace_;
}
// Convenience methods for returning autoreleased GTMScriptRunner instances, that
// are associated with the specified interpreter. The default interpreter
// (returned from +runner is "/bin/sh").
+ (GTMScriptRunner *)runner;
+ (GTMScriptRunner *)runnerWithBash;
+ (GTMScriptRunner *)runnerWithPerl;
+ (GTMScriptRunner *)runnerWithPython;
// Returns an autoreleased GTMScriptRunner instance associated with the specified
// interpreter, and the given args. The specified args are the arguments that
// should be applied to the interpreter itself, not scripts run through the
// interpreter. For example, to start an interpreter using "perl -w", you could
// do:
// [GTMScriptRunner runnerWithInterpreter:@"/usr/bin/perl"
// withArgs:[NSArray arrayWithObject:@"-w"]];
//
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp;
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp
withArgs:(NSArray *)args;
// Returns a GTMScriptRunner associated with |interp|
- (id)initWithInterpreter:(NSString *)interp;
// Returns a GTMScriptRunner associated with |interp| and |args| applied to the
// specified interpreter. This method is the designated initializer.
- (id)initWithInterpreter:(NSString *)interp withArgs:(NSArray *)args;
// Runs the specified command string by sending it through the interpreter's
// standard input. The standard output is returned. The standard error is
// discarded.
- (NSString *)run:(NSString *)cmds;
// Same as the previous method, except the standard error is returned in |err|
// if specified.
- (NSString *)run:(NSString *)cmds standardError:(NSString **)err;
// Runs the file at |path| using the interpreter.
- (NSString *)runScript:(NSString *)path;
// Runs the file at |path|, passing it |args| as arguments.
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args;
// Same as above, except the standard error is returned in |err| if specified.
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args
standardError:(NSString **)err;
// Returns the environment dictionary to use for the inferior process that will
// run the interpreter. A return value of nil means that the interpreter's
// environment should be erased.
- (NSDictionary *)environment;
// Sets the environment dictionary to use for the interpreter process. See
// NSTask's -setEnvironment: documentation for details about the dictionary.
// Basically, it's just a dict of key/value pairs corresponding to environment
// keys and values. Setting a value of nil means that the environment should be
// erased before running the interpreter.
//
// *** The default is nil. ***
//
// By default, all interpreters will run with a clean environment. If you want
// the interpreter process to inherit your current environment you'll need to
// do the following:
//
// GTMScriptRunner *sr = [GTMScriptRunner runner];
// [sr setEnvironment:[[NSProcessInfo processInfo] environment]];
//
// SECURITY NOTE: That said, in general you should NOT do this because an
// attacker can modify the environment that would then get sent to your scripts.
// And if your binary is suid, then you ABSOLUTELY should not do this.
//
- (void)setEnvironment:(NSDictionary *)newEnv;
// Sets (and returns) whether or not whitespace is automatically trimmed from
// the ends of the returned strings. The default is YES, so trailing newlines
// will be removed.
- (BOOL)trimsWhitespace;
- (void)setTrimsWhitespace:(BOOL)trim;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMScriptRunner.h | Objective-C | bsd | 5,737 |
//
// GTMNSAppleEventDescriptor+Foundation.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMFourCharCode.h"
#import <Carbon/Carbon.h> // Needed Solely For keyASUserRecordFields
// Map of types to selectors.
static NSMutableDictionary *gTypeMap = nil;
@implementation NSAppleEventDescriptor (GTMAppleEventDescriptorArrayAdditions)
+ (void)gtm_registerSelector:(SEL)selector
forTypes:(DescType*)types
count:(NSUInteger)count {
if (selector && types && count > 0) {
@synchronized(self) {
if (!gTypeMap) {
gTypeMap = [[NSMutableDictionary alloc] init];
}
NSString *selString = NSStringFromSelector(selector);
for (NSUInteger i = 0; i < count; ++i) {
NSNumber *key = [NSNumber numberWithUnsignedInt:types[i]];
NSString *exists = [gTypeMap objectForKey:key];
if (exists) {
_GTMDevLog(@"%@ being replaced with %@ exists for type: %@",
exists, selString, key);
}
[gTypeMap setObject:selString forKey:key];
}
}
}
}
- (id)gtm_objectValue {
id value = nil;
// Check our registered types to see if we have anything
if (gTypeMap) {
@synchronized(gTypeMap) {
DescType type = [self descriptorType];
NSNumber *key = [NSNumber numberWithUnsignedInt:type];
NSString *selectorString = [gTypeMap objectForKey:key];
if (selectorString) {
SEL selector = NSSelectorFromString(selectorString);
value = [self performSelector:selector];
} else {
value = [self stringValue];
}
}
}
return value;
}
- (NSArray*)gtm_arrayValue {
NSUInteger count = [self numberOfItems];
NSAppleEventDescriptor *workingDesc = self;
if (count == 0) {
// Create a list to work with.
workingDesc = [self coerceToDescriptorType:typeAEList];
count = [workingDesc numberOfItems];
}
NSMutableArray *items = [NSMutableArray arrayWithCapacity:count];
for (NSUInteger i = 1; i <= count; ++i) {
NSAppleEventDescriptor *desc = [workingDesc descriptorAtIndex:i];
id value = [desc gtm_objectValue];
if (!value) {
_GTMDevLog(@"Unknown type of descriptor %@", [desc description]);
return nil;
}
[items addObject:value];
}
return items;
}
- (NSDictionary*)gtm_dictionaryValue {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSAppleEventDescriptor *userRecord = [self descriptorForKeyword:keyASUserRecordFields];
if (userRecord) {
NSEnumerator *userItems = [[userRecord gtm_arrayValue] objectEnumerator];
NSString *key;
while ((key = [userItems nextObject])) {
NSString *value = [userItems nextObject];
if (!value) {
_GTMDevLog(@"Got a key %@ with no value in %@", key, userItems);
return nil;
}
[dictionary setObject:value forKey:key];
}
} else {
NSUInteger count = [self numberOfItems];
for (NSUInteger i = 1; i <= count; ++i) {
AEKeyword key = [self keywordForDescriptorAtIndex:i];
NSAppleEventDescriptor *desc = [self descriptorForKeyword:key];
id value = [desc gtm_objectValue];
if (!value) {
_GTMDevLog(@"Unknown type of descriptor %@", [desc description]);
return nil;
}
[dictionary setObject:value
forKey:[GTMFourCharCode fourCharCodeWithFourCharCode:key]];
}
}
return dictionary;
}
- (NSNull*)gtm_nullValue {
return [NSNull null];
}
+ (NSAppleEventDescriptor*)gtm_descriptorWithDouble:(double)real {
return [NSAppleEventDescriptor descriptorWithDescriptorType:typeIEEE64BitFloatingPoint
bytes:&real
length:sizeof(real)];
}
+ (NSAppleEventDescriptor*)gtm_descriptorWithFloat:(float)real {
return [NSAppleEventDescriptor descriptorWithDescriptorType:typeIEEE32BitFloatingPoint
bytes:&real
length:sizeof(real)];
}
+ (NSAppleEventDescriptor*)gtm_descriptorWithCGFloat:(CGFloat)real {
#if CGFLOAT_IS_DOUBLE
return [self gtm_descriptorWithDouble:real];
#else
return [self gtm_descriptorWithFloat:real];
#endif
}
- (double)gtm_doubleValue {
double value = NAN;
NSNumber *number = [self gtm_numberValue];
if (number) {
value = [number doubleValue];
}
return value;
}
- (float)gtm_floatValue {
float value = NAN;
NSNumber *number = [self gtm_numberValue];
if (number) {
value = [number floatValue];
}
return value;
}
- (CGFloat)gtm_cgFloatValue {
#if CGFLOAT_IS_DOUBLE
return [self gtm_doubleValue];
#else
return [self gtm_floatValue];
#endif
}
- (NSNumber*)gtm_numberValue {
typedef struct {
DescType type;
SEL selector;
} TypeSelectorMap;
TypeSelectorMap typeSelectorMap[] = {
{ typeFalse, @selector(numberWithBool:) },
{ typeTrue, @selector(numberWithBool:) },
{ typeBoolean, @selector(numberWithBool:) },
{ typeSInt16, @selector(numberWithShort:) },
{ typeSInt32, @selector(numberWithInt:) },
{ typeUInt32, @selector(numberWithUnsignedInt:) },
{ typeSInt64, @selector(numberWithLongLong:) },
{ typeIEEE32BitFloatingPoint, @selector(numberWithFloat:) },
{ typeIEEE64BitFloatingPoint, @selector(numberWithDouble:) }
};
DescType type = [self descriptorType];
SEL selector = nil;
for (size_t i = 0; i < sizeof(typeSelectorMap) / sizeof(TypeSelectorMap); ++i) {
if (type == typeSelectorMap[i].type) {
selector = typeSelectorMap[i].selector;
break;
}
}
NSAppleEventDescriptor *desc = self;
if (!selector) {
// COV_NF_START - Don't know how to force this in a unittest
_GTMDevLog(@"Didn't get a valid selector?");
desc = [self coerceToDescriptorType:typeIEEE64BitFloatingPoint];
selector = @selector(numberWithDouble:);
// COV_NF_END
}
NSData *descData = [desc data];
const void *bytes = [descData bytes];
if (!bytes) {
// COV_NF_START - Don't know how to force this in a unittest
_GTMDevLog(@"Unable to get bytes from %@", desc);
return nil;
// COV_NF_END
}
Class numberClass = [NSNumber class];
NSMethodSignature *signature = [numberClass methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
[invocation setArgument:(void*)bytes atIndex:2];
[invocation setTarget:numberClass];
[invocation invoke];
NSNumber *value = nil;
[invocation getReturnValue:&value];
return value;
}
@end
@implementation NSObject (GTMAppleEventDescriptorObjectAdditions)
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
return [NSAppleEventDescriptor descriptorWithString:[self description]];
}
@end
@implementation NSArray (GTMAppleEventDescriptorObjectAdditions)
+ (void)load {
DescType types[] = {
typeAEList,
};
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_arrayValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
[pool release];
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
NSAppleEventDescriptor *desc = [NSAppleEventDescriptor listDescriptor];
NSUInteger count = [self count];
for (NSUInteger i = 1; i <= count; ++i) {
id item = [self objectAtIndex:i-1];
NSAppleEventDescriptor *itemDesc = [item gtm_appleEventDescriptor];
if (!itemDesc) {
_GTMDevLog(@"Unable to create Apple Event Descriptor for %@", [self description]);
return nil;
}
[desc insertDescriptor:itemDesc atIndex:i];
}
return desc;
}
@end
@implementation NSDictionary (GTMAppleEventDescriptorObjectAdditions)
+ (void)load {
DescType types[] = {
typeAERecord,
};
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_dictionaryValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
[pool release];
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
NSEnumerator* keys = [self keyEnumerator];
Class keyClass = nil;
id key = nil;
while ((key = [keys nextObject])) {
if (!keyClass) {
if ([key isKindOfClass:[GTMFourCharCode class]]) {
keyClass = [GTMFourCharCode class];
} else if ([key isKindOfClass:[NSString class]]) {
keyClass = [NSString class];
} else {
_GTMDevLog(@"Keys must be of type NSString or GTMFourCharCode: %@", key);
return nil;
}
}
if (![key isKindOfClass:keyClass]) {
_GTMDevLog(@"Keys must be homogenous (first key was of type %@) "
"and of type NSString or GTMFourCharCode: %@", keyClass, key);
return nil;
}
}
NSAppleEventDescriptor *desc = [NSAppleEventDescriptor recordDescriptor];
if ([keyClass isEqual:[NSString class]]) {
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count] * 2];
keys = [self keyEnumerator];
while ((key = [keys nextObject])) {
[array addObject:key];
[array addObject:[self objectForKey:key]];
}
NSAppleEventDescriptor *userRecord = [array gtm_appleEventDescriptor];
if (!userRecord) {
return nil;
}
[desc setDescriptor:userRecord forKeyword:keyASUserRecordFields];
} else {
keys = [self keyEnumerator];
while ((key = [keys nextObject])) {
id value = [self objectForKey:key];
NSAppleEventDescriptor *valDesc = [value gtm_appleEventDescriptor];
if (!valDesc) {
return nil;
}
[desc setDescriptor:valDesc forKeyword:[key fourCharCode]];
}
}
return desc;
}
@end
@implementation NSNull (GTMAppleEventDescriptorObjectAdditions)
+ (void)load {
DescType types[] = {
typeNull
};
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_nullValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
[pool release];
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
return [NSAppleEventDescriptor nullDescriptor];
}
@end
@implementation NSString (GTMAppleEventDescriptorObjectAdditions)
+ (void)load {
DescType types[] = {
typeUTF16ExternalRepresentation,
typeUnicodeText,
typeUTF8Text,
typeCString,
typePString,
typeChar,
typeIntlText };
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(stringValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
[pool release];
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
return [NSAppleEventDescriptor descriptorWithString:self];
}
@end
@implementation NSNumber (GTMAppleEventDescriptorObjectAdditions)
+ (void)load {
DescType types[] = {
typeTrue,
typeFalse,
typeBoolean,
typeSInt16,
typeSInt32,
typeUInt32,
typeSInt64,
typeIEEE32BitFloatingPoint,
typeIEEE64BitFloatingPoint };
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_numberValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
[pool release];
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
const char *type = [self objCType];
if (!type || strlen(type) != 1) return nil;
DescType desiredType = typeNull;
NSAppleEventDescriptor *desc = nil;
switch (type[0]) {
// COV_NF_START
// I can't seem to convince objcType to return something of this type
case 'B':
desc = [NSAppleEventDescriptor descriptorWithBoolean:[self boolValue]];
break;
// COV_NF_END
case 'c':
case 'C':
case 's':
case 'S':
desiredType = typeSInt16;
break;
case 'i':
case 'l':
desiredType = typeSInt32;
break;
// COV_NF_START
// I can't seem to convince objcType to return something of this type
case 'I':
case 'L':
desiredType = typeUInt32;
break;
// COV_NF_END
case 'q':
case 'Q':
desiredType = typeSInt64;
break;
case 'f':
desiredType = typeIEEE32BitFloatingPoint;
break;
case 'd':
default:
desiredType = typeIEEE64BitFloatingPoint;
break;
}
if (!desc) {
desc = [NSAppleEventDescriptor gtm_descriptorWithDouble:[self doubleValue]];
if (desc && desiredType != typeIEEE64BitFloatingPoint) {
desc = [desc coerceToDescriptorType:desiredType];
}
}
return desc;
}
@end
@implementation NSProcessInfo (GTMAppleEventDescriptorObjectAdditions)
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
ProcessSerialNumber psn = { 0, kCurrentProcess };
return [NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber
bytes:&psn
length:sizeof(ProcessSerialNumber)];
}
@end
@implementation NSAppleEventDescriptor (GTMAppleEventDescriptorAdditions)
- (BOOL)gtm_sendEventWithMode:(AESendMode)mode
timeOut:(NSTimeInterval)timeout
reply:(NSAppleEventDescriptor**)reply {
BOOL isGood = YES;
AppleEvent replyEvent = { typeNull, NULL };
OSStatus err = AESendMessage([self aeDesc], &replyEvent, mode, timeout * 60);
if (err) {
isGood = NO;
_GTMDevLog(@"Unable to send message: %@ %d", self, err);
replyEvent.descriptorType = typeNull;
replyEvent.dataHandle = NULL;
}
NSAppleEventDescriptor *replyDesc = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&replyEvent] autorelease];
if (isGood) {
NSAppleEventDescriptor *errorDesc = [replyDesc descriptorForKeyword:keyErrorNumber];
if (errorDesc && [errorDesc int32Value]) {
isGood = NO;
}
}
if (reply) {
*reply = replyDesc;
}
return isGood;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+Foundation.m | Objective-C | bsd | 14,940 |
//
// GTMProgressMonitorInputStream.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMProgressMonitorInputStream.h"
#import "GTMDefines.h"
#import "GTMDebugSelectorValidation.h"
@implementation GTMProgressMonitorInputStream
// we'll forward all unhandled messages to the NSInputStream class
// or to the encapsulated input stream. This is needed
// for all messages sent to NSInputStream which aren't
// handled by our superclass; that includes various private run
// loop calls.
+ (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
return [NSInputStream methodSignatureForSelector:selector];
}
+ (void)forwardInvocation:(NSInvocation*)invocation {
[invocation invokeWithTarget:[NSInputStream class]];
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
return [inputStream_ methodSignatureForSelector:selector];
}
- (void)forwardInvocation:(NSInvocation*)invocation {
[invocation invokeWithTarget:inputStream_];
}
#pragma mark -
+ (id)inputStreamWithStream:(NSInputStream *)input
length:(unsigned long long)length {
return [[[self alloc] initWithStream:input
length:length] autorelease];
}
- (id)initWithStream:(NSInputStream *)input
length:(unsigned long long)length {
if ((self = [super init]) != nil) {
inputStream_ = [input retain];
dataSize_ = length;
}
return self;
}
- (id)init {
_GTMDevAssert(NO, @"should call initWithStream:length:");
return nil;
}
- (void)dealloc {
[inputStream_ release];
[super dealloc];
}
#pragma mark -
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
NSInteger numRead = [inputStream_ read:buffer maxLength:len];
if (numRead > 0) {
numBytesRead_ += numRead;
if (monitorDelegate_ && monitorSelector_) {
// call the monitor delegate with the number of bytes read and the
// total bytes read
NSMethodSignature *signature = [monitorDelegate_ methodSignatureForSelector:monitorSelector_];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:monitorSelector_];
[invocation setTarget:monitorDelegate_];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&numBytesRead_ atIndex:3];
[invocation setArgument:&dataSize_ atIndex:4];
[invocation invoke];
}
}
return numRead;
}
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len {
return [inputStream_ getBuffer:buffer length:len];
}
- (BOOL)hasBytesAvailable {
return [inputStream_ hasBytesAvailable];
}
#pragma mark Standard messages
// Pass expected messages to our encapsulated stream.
//
// We want our encapsulated NSInputStream to handle the standard messages;
// we don't want the superclass to handle them.
- (void)open {
[inputStream_ open];
}
- (void)close {
[inputStream_ close];
}
- (id)delegate {
return [inputStream_ delegate];
}
- (void)setDelegate:(id)delegate {
[inputStream_ setDelegate:delegate];
}
- (id)propertyForKey:(NSString *)key {
return [inputStream_ propertyForKey:key];
}
- (BOOL)setProperty:(id)property forKey:(NSString *)key {
return [inputStream_ setProperty:property forKey:key];
}
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode {
[inputStream_ scheduleInRunLoop:aRunLoop forMode:mode];
}
- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode {
[inputStream_ removeFromRunLoop:aRunLoop forMode:mode];
}
- (NSStreamStatus)streamStatus {
return [inputStream_ streamStatus];
}
- (NSError *)streamError {
return [inputStream_ streamError];
}
#pragma mark Setters and getters
- (void)setMonitorDelegate:(id)monitorDelegate
selector:(SEL)monitorSelector {
monitorDelegate_ = monitorDelegate; // non-retained
monitorSelector_ = monitorSelector;
GTMAssertSelectorNilOrImplementedWithArguments(monitorDelegate,
monitorSelector,
@encode(GTMProgressMonitorInputStream *),
@encode(unsigned long long),
@encode(unsigned long long),
NULL);
}
- (id)monitorDelegate {
return monitorDelegate_;
}
- (SEL)monitorSelector {
return monitorSelector_;
}
- (void)setMonitorSource:(id)source {
monitorSource_ = source; // non-retained
}
- (id)monitorSource {
return monitorSource_;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMProgressMonitorInputStream.m | Objective-C | bsd | 5,185 |
//
// GTMNSData+zlibTest.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMUnitTestDevLog.h"
#import "GTMNSData+zlib.h"
#import <stdlib.h> // for randiom/srandomdev
#import <zlib.h>
@interface GTMNSData_zlibTest : GTMTestCase
@end
static void FillWithRandom(char *data, unsigned long len) {
char *max = data + len;
for ( ; data < max ; ++data) {
*data = random() & 0xFF;
}
}
static BOOL HasGzipHeader(NSData *data) {
// very simple check
const unsigned char *bytes = [data bytes];
return ([data length] > 2) &&
((bytes[0] == 0x1f) && (bytes[1] == 0x8b));
}
@implementation GTMNSData_zlibTest
- (void)setUp {
// seed random from /dev/random
srandomdev();
}
- (void)testBoundryValues {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
STAssertNotNil(localPool, @"failed to alloc local pool");
// build some test data
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:512];
FillWithRandom([data mutableBytes], [data length]);
// bogus args to start
STAssertNil([NSData gtm_dataByDeflatingData:nil], nil);
STAssertNil([NSData gtm_dataByDeflatingBytes:nil length:666], nil);
STAssertNil([NSData gtm_dataByDeflatingBytes:[data bytes] length:0], nil);
STAssertNil([NSData gtm_dataByGzippingData:nil], nil);
STAssertNil([NSData gtm_dataByGzippingBytes:nil length:666], nil);
STAssertNil([NSData gtm_dataByGzippingBytes:[data bytes] length:0], nil);
STAssertNil([NSData gtm_dataByInflatingData:nil], nil);
STAssertNil([NSData gtm_dataByInflatingBytes:nil length:666], nil);
STAssertNil([NSData gtm_dataByInflatingBytes:[data bytes] length:0], nil);
// test deflate w/ compression levels out of range
NSData *deflated = [NSData gtm_dataByDeflatingData:data
compressionLevel:-4];
STAssertNotNil(deflated, nil);
STAssertFalse(HasGzipHeader(deflated), nil);
NSData *dataPrime = [NSData gtm_dataByInflatingData:deflated];
STAssertNotNil(dataPrime, nil);
STAssertEqualObjects(data, dataPrime, nil);
deflated = [NSData gtm_dataByDeflatingData:data
compressionLevel:20];
STAssertNotNil(deflated, nil);
STAssertFalse(HasGzipHeader(deflated), nil);
dataPrime = [NSData gtm_dataByInflatingData:deflated];
STAssertNotNil(dataPrime, nil);
STAssertEqualObjects(data, dataPrime, nil);
// test gzip w/ compression levels out of range
NSData *gzipped = [NSData gtm_dataByGzippingData:data
compressionLevel:-4];
STAssertNotNil(gzipped, nil);
STAssertTrue(HasGzipHeader(gzipped), nil);
dataPrime = [NSData gtm_dataByInflatingData:gzipped];
STAssertNotNil(dataPrime, nil);
STAssertEqualObjects(data, dataPrime, nil);
gzipped = [NSData gtm_dataByGzippingData:data
compressionLevel:20];
STAssertNotNil(gzipped, nil);
STAssertTrue(HasGzipHeader(gzipped), nil);
dataPrime = [NSData gtm_dataByInflatingData:gzipped];
STAssertNotNil(dataPrime, nil);
STAssertEqualObjects(data, dataPrime, nil);
// test non-compressed data data itself
[GTMUnitTestDevLog expectString:@"Error trying to inflate some of the "
"payload, error -3"];
STAssertNil([NSData gtm_dataByInflatingData:data], nil);
// test deflated data runs that end before they are done
[GTMUnitTestDevLog expect:[deflated length] - 1
casesOfString:@"Error trying to inflate some of the payload, "
"error -5"];
for (NSUInteger x = 1 ; x < [deflated length] ; ++x) {
STAssertNil([NSData gtm_dataByInflatingBytes:[deflated bytes]
length:x], nil);
}
// test gzipped data runs that end before they are done
[GTMUnitTestDevLog expect:[gzipped length] - 1
casesOfString:@"Error trying to inflate some of the payload, "
"error -5"];
for (NSUInteger x = 1 ; x < [gzipped length] ; ++x) {
STAssertNil([NSData gtm_dataByInflatingBytes:[gzipped bytes]
length:x], nil);
}
// test extra data before the deflated/gzipped data (just to make sure we
// don't seek to the "real" data)
NSMutableData *prefixedDeflated = [NSMutableData data];
STAssertNotNil(prefixedDeflated, @"failed to alloc data block");
[prefixedDeflated setLength:20];
FillWithRandom([prefixedDeflated mutableBytes], [prefixedDeflated length]);
[prefixedDeflated appendData:deflated];
[GTMUnitTestDevLog expectString:@"Error trying to inflate some of the "
"payload, error -3"];
STAssertNil([NSData gtm_dataByInflatingData:prefixedDeflated], nil);
[GTMUnitTestDevLog expectString:@"Error trying to inflate some of the "
"payload, error -3"];
STAssertNil([NSData gtm_dataByInflatingBytes:[prefixedDeflated bytes]
length:[prefixedDeflated length]],
nil);
NSMutableData *prefixedGzipped = [NSMutableData data];
STAssertNotNil(prefixedDeflated, @"failed to alloc data block");
[prefixedGzipped setLength:20];
FillWithRandom([prefixedGzipped mutableBytes], [prefixedGzipped length]);
[prefixedGzipped appendData:gzipped];
[GTMUnitTestDevLog expectString:@"Error trying to inflate some of the "
"payload, error -3"];
STAssertNil([NSData gtm_dataByInflatingData:prefixedGzipped], nil);
[GTMUnitTestDevLog expectString:@"Error trying to inflate some of the "
"payload, error -3"];
STAssertNil([NSData gtm_dataByInflatingBytes:[prefixedGzipped bytes]
length:[prefixedGzipped length]],
nil);
// test extra data after the deflated/gzipped data (just to make sure we
// don't ignore some of the data)
NSMutableData *suffixedDeflated = [NSMutableData data];
STAssertNotNil(suffixedDeflated, @"failed to alloc data block");
[suffixedDeflated appendData:deflated];
[suffixedDeflated appendBytes:[data bytes] length:20];
[GTMUnitTestDevLog expectString:@"thought we finished inflate w/o using "
"all input, 20 bytes left"];
STAssertNil([NSData gtm_dataByInflatingData:suffixedDeflated], nil);
[GTMUnitTestDevLog expectString:@"thought we finished inflate w/o using "
"all input, 20 bytes left"];
STAssertNil([NSData gtm_dataByInflatingBytes:[suffixedDeflated bytes]
length:[suffixedDeflated length]],
nil);
NSMutableData *suffixedGZipped = [NSMutableData data];
STAssertNotNil(suffixedGZipped, @"failed to alloc data block");
[suffixedGZipped appendData:gzipped];
[suffixedGZipped appendBytes:[data bytes] length:20];
[GTMUnitTestDevLog expectString:@"thought we finished inflate w/o using "
"all input, 20 bytes left"];
STAssertNil([NSData gtm_dataByInflatingData:suffixedGZipped], nil);
[GTMUnitTestDevLog expectString:@"thought we finished inflate w/o using "
"all input, 20 bytes left"];
STAssertNil([NSData gtm_dataByInflatingBytes:[suffixedGZipped bytes]
length:[suffixedGZipped length]],
nil);
[localPool release];
}
- (void)testInflateDeflate {
// generate a range of sizes w/ random content
for (int n = 0 ; n < 2 ; ++n) {
for (int x = 1 ; x < 128 ; ++x) {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
STAssertNotNil(localPool, @"failed to alloc local pool");
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
// first pass small blocks, second pass, larger ones, but second pass
// avoid making them multimples of 128.
[data setLength:((n*x*128) + x)];
FillWithRandom([data mutableBytes], [data length]);
// w/ *Bytes apis, default level
NSData *deflated = [NSData gtm_dataByDeflatingBytes:[data bytes]
length:[data length]];
STAssertNotNil(deflated, @"failed to deflate data block");
STAssertGreaterThan([deflated length],
(NSUInteger)0, @"failed to deflate data block");
STAssertFalse(HasGzipHeader(deflated), @"has gzip header on zlib data");
NSData *dataPrime = [NSData gtm_dataByInflatingBytes:[deflated bytes]
length:[deflated length]];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Bytes apis");
// w/ *Data apis, default level
deflated = [NSData gtm_dataByDeflatingData:data];
STAssertNotNil(deflated, @"failed to deflate data block");
STAssertGreaterThan([deflated length],
(NSUInteger)0, @"failed to deflate data block");
STAssertFalse(HasGzipHeader(deflated), @"has gzip header on zlib data");
dataPrime = [NSData gtm_dataByInflatingData:deflated];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Data apis");
// loop over the compression levels
for (int level = 1 ; level < 9 ; ++level) {
// w/ *Bytes apis, using our level
deflated = [NSData gtm_dataByDeflatingBytes:[data bytes]
length:[data length]
compressionLevel:level];
STAssertNotNil(deflated, @"failed to deflate data block");
STAssertGreaterThan([deflated length],
(NSUInteger)0, @"failed to deflate data block");
STAssertFalse(HasGzipHeader(deflated), @"has gzip header on zlib data");
dataPrime = [NSData gtm_dataByInflatingBytes:[deflated bytes]
length:[deflated length]];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Bytes apis");
// w/ *Data apis, using our level
deflated = [NSData gtm_dataByDeflatingData:data compressionLevel:level];
STAssertNotNil(deflated, @"failed to deflate data block");
STAssertGreaterThan([deflated length],
(NSUInteger)0, @"failed to deflate data block");
STAssertFalse(HasGzipHeader(deflated), @"has gzip header on zlib data");
dataPrime = [NSData gtm_dataByInflatingData:deflated];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Data apis");
}
[localPool release];
}
}
}
- (void)testInflateGzip {
// generate a range of sizes w/ random content
for (int n = 0 ; n < 2 ; ++n) {
for (int x = 1 ; x < 128 ; ++x) {
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
STAssertNotNil(localPool, @"failed to alloc local pool");
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
// first pass small blocks, second pass, larger ones, but second pass
// avoid making them multimples of 128.
[data setLength:((n*x*128) + x)];
FillWithRandom([data mutableBytes], [data length]);
// w/ *Bytes apis, default level
NSData *gzipped = [NSData gtm_dataByGzippingBytes:[data bytes]
length:[data length]];
STAssertNotNil(gzipped, @"failed to gzip data block");
STAssertGreaterThan([gzipped length],
(NSUInteger)0, @"failed to gzip data block");
STAssertTrue(HasGzipHeader(gzipped),
@"doesn't have gzip header on gzipped data");
NSData *dataPrime = [NSData gtm_dataByInflatingBytes:[gzipped bytes]
length:[gzipped length]];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Bytes apis");
// w/ *Data apis, default level
gzipped = [NSData gtm_dataByGzippingData:data];
STAssertNotNil(gzipped, @"failed to gzip data block");
STAssertGreaterThan([gzipped length],
(NSUInteger)0, @"failed to gzip data block");
STAssertTrue(HasGzipHeader(gzipped),
@"doesn't have gzip header on gzipped data");
dataPrime = [NSData gtm_dataByInflatingData:gzipped];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Data apis");
// loop over the compression levels
for (int level = 1 ; level < 9 ; ++level) {
// w/ *Bytes apis, using our level
gzipped = [NSData gtm_dataByGzippingBytes:[data bytes]
length:[data length]
compressionLevel:level];
STAssertNotNil(gzipped, @"failed to gzip data block");
STAssertGreaterThan([gzipped length],
(NSUInteger)0, @"failed to gzip data block");
STAssertTrue(HasGzipHeader(gzipped),
@"doesn't have gzip header on gzipped data");
dataPrime = [NSData gtm_dataByInflatingBytes:[gzipped bytes]
length:[gzipped length]];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Bytes apis");
// w/ *Data apis, using our level
gzipped = [NSData gtm_dataByGzippingData:data compressionLevel:level];
STAssertNotNil(gzipped, @"failed to gzip data block");
STAssertGreaterThan([gzipped length],
(NSUInteger)0, @"failed to gzip data block");
STAssertTrue(HasGzipHeader(gzipped),
@"doesn't have gzip header on gzipped data");
dataPrime = [NSData gtm_dataByInflatingData:gzipped];
STAssertNotNil(dataPrime, @"failed to inflate data block");
STAssertGreaterThan([dataPrime length],
(NSUInteger)0, @"failed to inflate data block");
STAssertEqualObjects(data,
dataPrime, @"failed to round trip via *Data apis");
}
[localPool release];
}
}
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSData+zlibTest.m | Objective-C | bsd | 16,030 |
//
// NSAppleEventDescriptor+HandlerTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <Carbon/Carbon.h>
#import "GTMSenTestCase.h"
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMNSAppleEventDescriptor+Handler.h"
#import "GTMUnitTestDevLog.h"
@interface GTMNSAppleEventDescriptor_HandlerTest : GTMTestCase
@end
@implementation GTMNSAppleEventDescriptor_HandlerTest
// Most of this gets tested by the NSAppleScript+Handler tests.
- (void)testPositionalHandlers {
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithPositionalHandler:nil
parametersArray:[NSArray array]];
STAssertNil(desc, @"got a desc?");
desc = [NSAppleEventDescriptor gtm_descriptorWithPositionalHandler:@"happy"
parametersDescriptor:nil];
STAssertNotNil(desc, @"didn't get a desc?");
desc = [NSAppleEventDescriptor gtm_descriptorWithLabeledHandler:nil
labels:nil
parameters:nil
count:0];
STAssertNil(desc, @"got a desc?");
AEKeyword keys[] = { keyASPrepositionGiven };
NSString *string = @"foo";
[GTMUnitTestDevLog expectString:@"Must pass in dictionary for "
"keyASPrepositionGiven (got foo)"];
desc = [NSAppleEventDescriptor gtm_descriptorWithLabeledHandler:@"happy"
labels:keys
parameters:&string
count:1];
STAssertNil(desc, @"got a desc?");
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"bart"
forKey:[NSNumber numberWithInt:4]];
[GTMUnitTestDevLog expectString:@"Keys must be of type NSString or "
"GTMFourCharCode: 4"];
[GTMUnitTestDevLog expectPattern:@"Dictionary for keyASPrepositionGiven must "
"be a user record field dictionary \\(got .*"];
desc = [NSAppleEventDescriptor gtm_descriptorWithLabeledHandler:@"happy"
labels:keys
parameters:&dict
count:1];
STAssertNil(desc, @"got a desc?");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+HandlerTest.m | Objective-C | bsd | 3,022 |
//
// GTMObjC2Runtime.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMObjC2Runtime.h"
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
#import <stdlib.h>
#import <string.h>
Class object_getClass(id obj) {
if (!obj) return NULL;
return obj->isa;
}
const char *class_getName(Class cls) {
if (!cls) return "nil";
return cls->name;
}
BOOL class_conformsToProtocol(Class cls, Protocol *protocol) {
// We intentionally don't check cls as it crashes on Leopard so we want
// to crash on Tiger as well.
// I logged
// Radar 5572978 class_conformsToProtocol crashes when arg1 is passed as nil
// because it seems odd that this API won't accept nil for cls considering
// all the other apis will accept nil args.
// If this does get fixed, remember to enable the unit tests.
if (!protocol) return NO;
struct objc_protocol_list *protos;
for (protos = cls->protocols; protos != NULL; protos = protos->next) {
for (long i = 0; i < protos->count; i++) {
if ([protos->list[i] conformsTo:protocol]) {
return YES;
}
}
}
return NO;
}
Class class_getSuperclass(Class cls) {
if (!cls) return NULL;
return cls->super_class;
}
Method *class_copyMethodList(Class cls, unsigned int *outCount) {
if (!cls) return NULL;
unsigned int count = 0;
void *iterator = NULL;
struct objc_method_list *mlist;
Method *methods = NULL;
if (outCount) *outCount = 0;
while ( (mlist = class_nextMethodList(cls, &iterator)) ) {
if (mlist->method_count == 0) continue;
methods = (Method *)realloc(methods,
sizeof(Method) * (count + mlist->method_count + 1));
if (!methods) {
//Memory alloc failed, so what can we do?
return NULL; // COV_NF_LINE
}
for (int i = 0; i < mlist->method_count; i++) {
methods[i + count] = &mlist->method_list[i];
}
count += mlist->method_count;
}
// List must be NULL terminated
if (methods) {
methods[count] = NULL;
}
if (outCount) *outCount = count;
return methods;
}
SEL method_getName(Method method) {
if (!method) return NULL;
return method->method_name;
}
IMP method_getImplementation(Method method) {
if (!method) return NULL;
return method->method_imp;
}
IMP method_setImplementation(Method method, IMP imp) {
// We intentionally don't test method for nil.
// Leopard fails here, so should we.
// I logged this as Radar:
// 5572981 method_setImplementation crashes if you pass nil for the
// method arg (arg 1)
// because it seems odd that this API won't accept nil for method considering
// all the other apis will accept nil args.
// If this does get fixed, remember to enable the unit tests.
IMP oldImp = method->method_imp;
method->method_imp = imp;
return oldImp;
}
void method_exchangeImplementations(Method m1, Method m2) {
if (m1 == m2) return;
if (!m1 || !m2) return;
IMP imp2 = method_getImplementation(m2);
IMP imp1 = method_setImplementation(m1, imp2);
method_setImplementation(m2, imp1);
}
struct objc_method_description protocol_getMethodDescription(Protocol *p,
SEL aSel,
BOOL isRequiredMethod,
BOOL isInstanceMethod) {
struct objc_method_description *descPtr = NULL;
// No such thing as required in ObjC1.
if (isInstanceMethod) {
descPtr = [p descriptionForInstanceMethod:aSel];
} else {
descPtr = [p descriptionForClassMethod:aSel];
}
struct objc_method_description desc;
if (descPtr) {
desc = *descPtr;
} else {
bzero(&desc, sizeof(desc));
}
return desc;
}
#endif
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMObjC2Runtime.m | Objective-C | bsd | 4,296 |
//
// GTMNSEnumerator+Filter.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
/// A generic category for methods that allow us to filter enumeratable
/// containers, inspired by C++ Standard Library's use of iterators.
/// Like in C++, these assume the underlying container is not modified during
/// the lifetime of the iterator.
///
@interface NSEnumerator (GTMEnumeratorFilterAdditions)
/// @argument predicate - the function return BOOL. will be applied to each element
/// @argument argument - optional argument to pass to predicate
/// @returns an enumerator that contains only elements where [element sel:argument] is true
- (NSEnumerator *)gtm_filteredEnumeratorByMakingEachObjectPerformSelector:(SEL)predicate
withObject:(id)argument;
/// @argument selector - the function return a transformed object. will be applied to each element
/// @argument argument - optional argument to pass to transformer
/// @returns an enumerator that contains the transformed elements
- (NSEnumerator *)gtm_enumeratorByMakingEachObjectPerformSelector:(SEL)selector
withObject:(id)argument;
/// @argument target - receiver for each method
/// @argument predicate - as in, [target predicate: [self nextObject]], return a BOOL
/// @returns an enumerator that contains only elements where [element sel:argument] is true
- (NSEnumerator *)gtm_filteredEnumeratorByTarget:(id)target
performOnEachSelector:(SEL)predicate;
/// @argument target - receiver for each method
/// @argument sel - as in, [target selector: [self nextObject]], return a transformed object
/// @returns an enumerator that contains the transformed elements
- (NSEnumerator *)gtm_enumeratorByTarget:(id)target
performOnEachSelector:(SEL)selector;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSEnumerator+Filter.h | Objective-C | bsd | 2,476 |
//
// GTMFourCharCode
// Wrapper for FourCharCodes
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
// FourCharCodes are OSTypes, ResTypes etc. This class wraps them if
// you need to store them in dictionaries etc.
@interface GTMFourCharCode : NSObject <NSCopying, NSCoding> {
FourCharCode code_;
}
// returns a string for a FourCharCode
+ (id)stringWithFourCharCode:(FourCharCode)code;
// String must be 4 chars or less, or you will get nil back.
+ (id)fourCharCodeWithString:(NSString*)string;
+ (id)fourCharCodeWithFourCharCode:(FourCharCode)code;
// String must be 4 chars or less, or you will get nil back.
- (id)initWithString:(NSString*)string;
// Designated Initializer
- (id)initWithFourCharCode:(FourCharCode)code;
// Returns 'APPL' for "APPL"
- (FourCharCode)fourCharCode;
// For FourCharCode of 'APPL' returns "APPL". For 1 returns "\0\0\0\1"
- (NSString*)stringValue;
// For FourCharCode of "APPL" returns an NSNumber with 1095782476 (0x4150504C).
// For 1 returns 1.
- (NSNumber*)numberValue;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMFourCharCode.h | Objective-C | bsd | 1,616 |
//
// GTMGeometryUtils.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMGeometryUtils.h"
/// Align rectangles
//
// Args:
// alignee - rect to be aligned
// aligner - rect to be aligned to
// alignment - alignment to be applied to alignee based on aligner
CGRect GTMCGAlignRectangles(CGRect alignee, CGRect aligner, GTMRectAlignment alignment) {
switch (alignment) {
case GTMRectAlignTop:
alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
break;
case GTMRectAlignTopLeft:
alignee.origin.x = aligner.origin.x;
alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
break;
case GTMRectAlignTopRight:
alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
alignee.origin.y = aligner.origin.y + CGRectGetHeight(aligner) - CGRectGetHeight(alignee);
break;
case GTMRectAlignLeft:
alignee.origin.x = aligner.origin.x;
alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
break;
case GTMRectAlignBottomLeft:
alignee.origin.x = aligner.origin.x;
alignee.origin.y = aligner.origin.y;
break;
case GTMRectAlignBottom:
alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
alignee.origin.y = aligner.origin.y;
break;
case GTMRectAlignBottomRight:
alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
alignee.origin.y = aligner.origin.y;
break;
case GTMRectAlignRight:
alignee.origin.x = aligner.origin.x + CGRectGetWidth(aligner) - CGRectGetWidth(alignee);
alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
break;
default:
case GTMRectAlignCenter:
alignee.origin.x = aligner.origin.x + (CGRectGetWidth(aligner) * .5f - CGRectGetWidth(alignee) * .5f);
alignee.origin.y = aligner.origin.y + (CGRectGetHeight(aligner) * .5f - CGRectGetHeight(alignee) * .5f);
break;
}
return alignee;
}
CGRect GTMCGScaleRectangleToSize(CGRect scalee, CGSize size, GTMScaling scaling) {
switch (scaling) {
case GTMScaleProportionally: {
CGFloat height = CGRectGetHeight(scalee);
CGFloat width = CGRectGetWidth(scalee);
if (isnormal(height) && isnormal(width) &&
(height > size.height || width > size.width)) {
CGFloat horiz = size.width / width;
CGFloat vert = size.height / height;
CGFloat newScale = horiz < vert ? horiz : vert;
scalee = GTMCGRectScale(scalee, newScale, newScale);
}
break;
}
case GTMScaleToFit:
scalee.size = size;
break;
case GTMScaleNone:
default:
// Do nothing
break;
}
return scalee;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMGeometryUtils.m | Objective-C | bsd | 3,650 |
//
// GTMFourCharCode.m
// Wrapper for FourCharCodes
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import "GTMFourCharCode.h"
#import "GTMGarbageCollection.h"
#import <CoreServices/CoreServices.h>
@implementation GTMFourCharCode
+ (id)stringWithFourCharCode:(FourCharCode)code {
return [GTMNSMakeCollectable(UTCreateStringForOSType(code)) autorelease];
}
+ (id)fourCharCodeWithString:(NSString*)string {
return [[[self alloc] initWithString:string] autorelease];
}
+ (id)fourCharCodeWithFourCharCode:(FourCharCode)code {
return [[[self alloc] initWithFourCharCode:code] autorelease];
}
- (id)initWithString:(NSString*)string {
NSUInteger length = [string length];
if (length == 0 || length > 4) {
[self release];
return nil;
} else {
return [self initWithFourCharCode:UTGetOSTypeFromString((CFStringRef)string)];
}
}
- (id)initWithFourCharCode:(FourCharCode)code {
if ((self = [super init])) {
code_ = code;
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super init])) {
code_ = [aDecoder decodeInt32ForKey:@"FourCharCode"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInt32:code_ forKey:@"FourCharCode"];
}
- (id)copyWithZone:(NSZone *)zone {
return [[[self class] alloc] initWithFourCharCode:code_];
}
- (BOOL)isEqual:(id)object {
return [object isKindOfClass:[self class]] && [object fourCharCode] == code_;
}
- (NSUInteger)hash {
return (NSUInteger)code_;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ - %@ (0x%X)",
[self class],
[self stringValue],
code_];
}
- (FourCharCode)fourCharCode {
return code_;
}
- (NSString*)stringValue {
return [GTMNSMakeCollectable(UTCreateStringForOSType(code_)) autorelease];
}
- (NSNumber*)numberValue {
return [NSNumber numberWithUnsignedInt:code_];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMFourCharCode.m | Objective-C | bsd | 2,469 |
//
// NSString+XMLTest.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMNSString+XML.h"
@interface GTMNSString_XMLTest : GTMTestCase
@end
@implementation GTMNSString_XMLTest
- (void)testStringBySanitizingAndEscapingForXML {
// test the substitutions cases
UniChar chars[] = {
'z', 0, 'z', 1, 'z', 4, 'z', 5, 'z', 34, 'z', 38, 'z', 39, 'z',
60, 'z', 62, 'z', ' ', 'z', 0xd800, 'z', 0xDFFF, 'z', 0xE000,
'z', 0xFFFE, 'z', 0xFFFF, 'z', '\n', 'z', '\r', 'z', '\t', 'z' };
NSString *string1 = [NSString stringWithCharacters:chars
length:sizeof(chars) / sizeof(UniChar)];
NSString *string2 =
[NSString stringWithFormat:@"zzzzz"z&z'z<z>z zzz%Czzz\nz\rz\tz",
0xE000];
STAssertEqualObjects([string1 gtm_stringBySanitizingAndEscapingForXML],
string2,
@"Sanitize and Escape for XML failed");
// force the backing store of the NSString to test extraction paths
char ascBuffer[] = "a\01bcde\nf";
NSString *ascString =
[[[NSString alloc] initWithBytesNoCopy:ascBuffer
length:sizeof(ascBuffer) / sizeof(char)
encoding:NSASCIIStringEncoding
freeWhenDone:NO] autorelease];
STAssertEqualObjects([ascString gtm_stringBySanitizingAndEscapingForXML],
@"abcde\nf",
@"Sanitize and Escape for XML from asc buffer failed");
// test empty string
STAssertEqualObjects([@"" gtm_stringBySanitizingAndEscapingForXML], @"", nil);
}
- (void)testStringBySanitizingToXMLSpec {
// test the substitutions cases
UniChar chars[] = {
'z', 0, 'z', 1, 'z', 4, 'z', 5, 'z', 34, 'z', 38, 'z', 39, 'z',
60, 'z', 62, 'z', ' ', 'z', 0xd800, 'z', 0xDFFF, 'z', 0xE000,
'z', 0xFFFE, 'z', 0xFFFF, 'z', '\n', 'z', '\r', 'z', '\t', 'z' };
NSString *string1 = [NSString stringWithCharacters:chars
length:sizeof(chars) / sizeof(UniChar)];
NSString *string2 =
[NSString stringWithFormat:@"zzzzz\"z&z'z<z>z zzz%Czzz\nz\rz\tz",
0xE000];
STAssertEqualObjects([string1 gtm_stringBySanitizingToXMLSpec],
string2,
@"Sanitize for XML failed");
// force the backing store of the NSString to test extraction paths
char ascBuffer[] = "a\01bcde\nf";
NSString *ascString =
[[[NSString alloc] initWithBytesNoCopy:ascBuffer
length:sizeof(ascBuffer) / sizeof(char)
encoding:NSASCIIStringEncoding
freeWhenDone:NO] autorelease];
STAssertEqualObjects([ascString gtm_stringBySanitizingToXMLSpec],
@"abcde\nf",
@"Sanitize and Escape for XML from asc buffer failed");
// test empty string
STAssertEqualObjects([@"" gtm_stringBySanitizingToXMLSpec], @"", nil);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+XMLTest.m | Objective-C | bsd | 3,595 |
//
// GTMNSFileManager+Path.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSFileManager+Path.h"
@implementation NSFileManager (GMFileManagerPathAdditions)
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
- (BOOL)gtm_createFullPathToDirectory:(NSString *)path
attributes:(NSDictionary *)attributes {
if (!path) return NO;
BOOL isDir;
BOOL exists = [self fileExistsAtPath:path isDirectory:&isDir];
// Quick check for the case where we have nothing to do.
if (exists && isDir)
return YES;
NSString *actualPath = @"/";
NSEnumerator *directoryEnumerator = [[path pathComponents] objectEnumerator];
NSString *directory;
while ((directory = [directoryEnumerator nextObject])) {
actualPath = [actualPath stringByAppendingPathComponent:directory];
if ([self fileExistsAtPath:actualPath isDirectory:&isDir] && isDir) {
continue;
} else if ([self createDirectoryAtPath:actualPath attributes:attributes]) {
continue;
} else {
return NO;
}
}
return YES;
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1050
- (NSArray *)gtm_filePathsWithExtension:(NSString *)extension
inDirectory:(NSString *)directoryPath {
NSArray *extensions = nil;
// Treat no extension and an empty extension as the user requesting all files
if (extension != nil && ![extension isEqualToString:@""])
extensions = [NSArray arrayWithObject:extension];
return [self gtm_filePathsWithExtensions:extensions
inDirectory:directoryPath];
}
- (NSArray *)gtm_filePathsWithExtensions:(NSArray *)extensions
inDirectory:(NSString *)directoryPath {
if (directoryPath == nil)
return nil;
// |basenames| will contain only the matching file names, not their full paths.
NSArray *basenames = [self directoryContentsAtPath:directoryPath];
// Check if dir doesn't exist or couldn't be opened.
if (basenames == nil)
return nil;
// Check if dir is empty.
if ([basenames count] == 0)
return basenames;
NSMutableArray *paths = [NSMutableArray arrayWithCapacity:[basenames count]];
NSString *basename;
NSEnumerator *basenamesEnumerator = [basenames objectEnumerator];
// Convert all the |basenames| to full paths.
while ((basename = [basenamesEnumerator nextObject])) {
NSString *fullPath = [directoryPath stringByAppendingPathComponent:basename];
[paths addObject:fullPath];
}
// Check if caller wants all files, regardless of extension.
if (extensions == nil || [extensions count] == 0)
return paths;
return [paths pathsMatchingExtensions:extensions];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSFileManager+Path.m | Objective-C | bsd | 3,261 |
//
// GTMObjC2Runtime.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <objc/objc-api.h>
#import "GTMDefines.h"
// These functions exist for code that we want to compile on both the < 10.5
// sdks and on the >= 10.5 sdks without warnings. It basically reimplements
// certain parts of the objc2 runtime in terms of the objc1 runtime. It is not
// a complete implementation as I've only implemented the routines I know we
// use. Feel free to add more as necessary.
// These functions are not documented because they conform to the documentation
// for the ObjC2 Runtime.
#if OBJC_API_VERSION >= 2 // Only have optional and req'd keywords in ObjC2.
#define AT_OPTIONAL @optional
#define AT_REQUIRED @required
#else
#define AT_OPTIONAL
#define AT_REQUIRED
#endif
// The file objc-runtime.h was moved to runtime.h and in Leopard, objc-runtime.h
// was just a wrapper around runtime.h. For the iPhone SDK, this objc-runtime.h
// is removed in the iPhoneOS2.0 SDK.
//
// The |Object| class was removed in the iPhone2.0 SDK too.
#if GTM_IPHONE_SDK
#import <objc/runtime.h>
#else
#import <objc/objc-runtime.h>
#import <objc/Object.h>
#endif
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
#import "objc/Protocol.h"
Class object_getClass(id obj);
const char *class_getName(Class cls);
BOOL class_conformsToProtocol(Class cls, Protocol *protocol);
Class class_getSuperclass(Class cls);
Method *class_copyMethodList(Class cls, unsigned int *outCount);
SEL method_getName(Method m);
void method_exchangeImplementations(Method m1, Method m2);
IMP method_getImplementation(Method method);
IMP method_setImplementation(Method method, IMP imp);
struct objc_method_description protocol_getMethodDescription(Protocol *p,
SEL aSel,
BOOL isRequiredMethod,
BOOL isInstanceMethod);
#endif // OBJC2_UNAVAILABLE
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMObjC2Runtime.h | Objective-C | bsd | 2,549 |
//
// GTMNSString+HTML.m
// Dealing with NSStrings that contain HTML
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import "GTMNSString+HTML.h"
typedef struct {
NSString *escapeSequence;
unichar uchar;
} HTMLEscapeMap;
// Taken from http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
// Ordered by uchar lowest to highest for bsearching
static HTMLEscapeMap gAsciiHTMLEscapeMap[] = {
// A.2.2. Special characters
{ @""", 34 },
{ @"&", 38 },
{ @"'", 39 },
{ @"<", 60 },
{ @">", 62 },
// A.2.1. Latin-1 characters
{ @" ", 160 },
{ @"¡", 161 },
{ @"¢", 162 },
{ @"£", 163 },
{ @"¤", 164 },
{ @"¥", 165 },
{ @"¦", 166 },
{ @"§", 167 },
{ @"¨", 168 },
{ @"©", 169 },
{ @"ª", 170 },
{ @"«", 171 },
{ @"¬", 172 },
{ @"­", 173 },
{ @"®", 174 },
{ @"¯", 175 },
{ @"°", 176 },
{ @"±", 177 },
{ @"²", 178 },
{ @"³", 179 },
{ @"´", 180 },
{ @"µ", 181 },
{ @"¶", 182 },
{ @"·", 183 },
{ @"¸", 184 },
{ @"¹", 185 },
{ @"º", 186 },
{ @"»", 187 },
{ @"¼", 188 },
{ @"½", 189 },
{ @"¾", 190 },
{ @"¿", 191 },
{ @"À", 192 },
{ @"Á", 193 },
{ @"Â", 194 },
{ @"Ã", 195 },
{ @"Ä", 196 },
{ @"Å", 197 },
{ @"Æ", 198 },
{ @"Ç", 199 },
{ @"È", 200 },
{ @"É", 201 },
{ @"Ê", 202 },
{ @"Ë", 203 },
{ @"Ì", 204 },
{ @"Í", 205 },
{ @"Î", 206 },
{ @"Ï", 207 },
{ @"Ð", 208 },
{ @"Ñ", 209 },
{ @"Ò", 210 },
{ @"Ó", 211 },
{ @"Ô", 212 },
{ @"Õ", 213 },
{ @"Ö", 214 },
{ @"×", 215 },
{ @"Ø", 216 },
{ @"Ù", 217 },
{ @"Ú", 218 },
{ @"Û", 219 },
{ @"Ü", 220 },
{ @"Ý", 221 },
{ @"Þ", 222 },
{ @"ß", 223 },
{ @"à", 224 },
{ @"á", 225 },
{ @"â", 226 },
{ @"ã", 227 },
{ @"ä", 228 },
{ @"å", 229 },
{ @"æ", 230 },
{ @"ç", 231 },
{ @"è", 232 },
{ @"é", 233 },
{ @"ê", 234 },
{ @"ë", 235 },
{ @"ì", 236 },
{ @"í", 237 },
{ @"î", 238 },
{ @"ï", 239 },
{ @"ð", 240 },
{ @"ñ", 241 },
{ @"ò", 242 },
{ @"ó", 243 },
{ @"ô", 244 },
{ @"õ", 245 },
{ @"ö", 246 },
{ @"÷", 247 },
{ @"ø", 248 },
{ @"ù", 249 },
{ @"ú", 250 },
{ @"û", 251 },
{ @"ü", 252 },
{ @"ý", 253 },
{ @"þ", 254 },
{ @"ÿ", 255 },
// A.2.2. Special characters cont'd
{ @"Œ", 338 },
{ @"œ", 339 },
{ @"Š", 352 },
{ @"š", 353 },
{ @"Ÿ", 376 },
// A.2.3. Symbols
{ @"ƒ", 402 },
// A.2.2. Special characters cont'd
{ @"ˆ", 710 },
{ @"˜", 732 },
// A.2.3. Symbols cont'd
{ @"Α", 913 },
{ @"Β", 914 },
{ @"Γ", 915 },
{ @"Δ", 916 },
{ @"Ε", 917 },
{ @"Ζ", 918 },
{ @"Η", 919 },
{ @"Θ", 920 },
{ @"Ι", 921 },
{ @"Κ", 922 },
{ @"Λ", 923 },
{ @"Μ", 924 },
{ @"Ν", 925 },
{ @"Ξ", 926 },
{ @"Ο", 927 },
{ @"Π", 928 },
{ @"Ρ", 929 },
{ @"Σ", 931 },
{ @"Τ", 932 },
{ @"Υ", 933 },
{ @"Φ", 934 },
{ @"Χ", 935 },
{ @"Ψ", 936 },
{ @"Ω", 937 },
{ @"α", 945 },
{ @"β", 946 },
{ @"γ", 947 },
{ @"δ", 948 },
{ @"ε", 949 },
{ @"ζ", 950 },
{ @"η", 951 },
{ @"θ", 952 },
{ @"ι", 953 },
{ @"κ", 954 },
{ @"λ", 955 },
{ @"μ", 956 },
{ @"ν", 957 },
{ @"ξ", 958 },
{ @"ο", 959 },
{ @"π", 960 },
{ @"ρ", 961 },
{ @"ς", 962 },
{ @"σ", 963 },
{ @"τ", 964 },
{ @"υ", 965 },
{ @"φ", 966 },
{ @"χ", 967 },
{ @"ψ", 968 },
{ @"ω", 969 },
{ @"ϑ", 977 },
{ @"ϒ", 978 },
{ @"ϖ", 982 },
// A.2.2. Special characters cont'd
{ @" ", 8194 },
{ @" ", 8195 },
{ @" ", 8201 },
{ @"‌", 8204 },
{ @"‍", 8205 },
{ @"‎", 8206 },
{ @"‏", 8207 },
{ @"–", 8211 },
{ @"—", 8212 },
{ @"‘", 8216 },
{ @"’", 8217 },
{ @"‚", 8218 },
{ @"“", 8220 },
{ @"”", 8221 },
{ @"„", 8222 },
{ @"†", 8224 },
{ @"‡", 8225 },
// A.2.3. Symbols cont'd
{ @"•", 8226 },
{ @"…", 8230 },
// A.2.2. Special characters cont'd
{ @"‰", 8240 },
// A.2.3. Symbols cont'd
{ @"′", 8242 },
{ @"″", 8243 },
// A.2.2. Special characters cont'd
{ @"‹", 8249 },
{ @"›", 8250 },
// A.2.3. Symbols cont'd
{ @"‾", 8254 },
{ @"⁄", 8260 },
// A.2.2. Special characters cont'd
{ @"€", 8364 },
// A.2.3. Symbols cont'd
{ @"ℑ", 8465 },
{ @"℘", 8472 },
{ @"ℜ", 8476 },
{ @"™", 8482 },
{ @"ℵ", 8501 },
{ @"←", 8592 },
{ @"↑", 8593 },
{ @"→", 8594 },
{ @"↓", 8595 },
{ @"↔", 8596 },
{ @"↵", 8629 },
{ @"⇐", 8656 },
{ @"⇑", 8657 },
{ @"⇒", 8658 },
{ @"⇓", 8659 },
{ @"⇔", 8660 },
{ @"∀", 8704 },
{ @"∂", 8706 },
{ @"∃", 8707 },
{ @"∅", 8709 },
{ @"∇", 8711 },
{ @"∈", 8712 },
{ @"∉", 8713 },
{ @"∋", 8715 },
{ @"∏", 8719 },
{ @"∑", 8721 },
{ @"−", 8722 },
{ @"∗", 8727 },
{ @"√", 8730 },
{ @"∝", 8733 },
{ @"∞", 8734 },
{ @"∠", 8736 },
{ @"∧", 8743 },
{ @"∨", 8744 },
{ @"∩", 8745 },
{ @"∪", 8746 },
{ @"∫", 8747 },
{ @"∴", 8756 },
{ @"∼", 8764 },
{ @"≅", 8773 },
{ @"≈", 8776 },
{ @"≠", 8800 },
{ @"≡", 8801 },
{ @"≤", 8804 },
{ @"≥", 8805 },
{ @"⊂", 8834 },
{ @"⊃", 8835 },
{ @"⊄", 8836 },
{ @"⊆", 8838 },
{ @"⊇", 8839 },
{ @"⊕", 8853 },
{ @"⊗", 8855 },
{ @"⊥", 8869 },
{ @"⋅", 8901 },
{ @"⌈", 8968 },
{ @"⌉", 8969 },
{ @"⌊", 8970 },
{ @"⌋", 8971 },
{ @"⟨", 9001 },
{ @"⟩", 9002 },
{ @"◊", 9674 },
{ @"♠", 9824 },
{ @"♣", 9827 },
{ @"♥", 9829 },
{ @"♦", 9830 }
};
// Taken from http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
// This is table A.2.2 Special Characters
static HTMLEscapeMap gUnicodeHTMLEscapeMap[] = {
// C0 Controls and Basic Latin
{ @""", 34 },
{ @"&", 38 },
{ @"'", 39 },
{ @"<", 60 },
{ @">", 62 },
// Latin Extended-A
{ @"Œ", 338 },
{ @"œ", 339 },
{ @"Š", 352 },
{ @"š", 353 },
{ @"Ÿ", 376 },
// Spacing Modifier Letters
{ @"ˆ", 710 },
{ @"˜", 732 },
// General Punctuation
{ @" ", 8194 },
{ @" ", 8195 },
{ @" ", 8201 },
{ @"‌", 8204 },
{ @"‍", 8205 },
{ @"‎", 8206 },
{ @"‏", 8207 },
{ @"–", 8211 },
{ @"—", 8212 },
{ @"‘", 8216 },
{ @"’", 8217 },
{ @"‚", 8218 },
{ @"“", 8220 },
{ @"”", 8221 },
{ @"„", 8222 },
{ @"†", 8224 },
{ @"‡", 8225 },
{ @"‰", 8240 },
{ @"‹", 8249 },
{ @"›", 8250 },
{ @"€", 8364 },
};
// Utility function for Bsearching table above
static int EscapeMapCompare(const void *ucharVoid, const void *mapVoid) {
const unichar *uchar = (const unichar*)ucharVoid;
const HTMLEscapeMap *map = (const HTMLEscapeMap*)mapVoid;
int val;
if (*uchar > map->uchar) {
val = 1;
} else if (*uchar < map->uchar) {
val = -1;
} else {
val = 0;
}
return val;
}
@implementation NSString (GTMNSStringHTMLAdditions)
- (NSString *)gtm_stringByEscapingHTMLUsingTable:(HTMLEscapeMap*)table
ofSize:(NSUInteger)size
escapingUnicode:(BOOL)escapeUnicode {
NSUInteger length = [self length];
if (!length) {
return self;
}
NSMutableString *finalString = [NSMutableString string];
NSMutableData *data2 = [NSMutableData dataWithCapacity:sizeof(unichar) * length];
// this block is common between GTMNSString+HTML and GTMNSString+XML but
// it's so short that it isn't really worth trying to share.
const unichar *buffer = CFStringGetCharactersPtr((CFStringRef)self);
if (!buffer) {
// We want this buffer to be autoreleased.
NSMutableData *data = [NSMutableData dataWithLength:length * sizeof(UniChar)];
if (!data) {
// COV_NF_START - Memory fail case
_GTMDevLog(@"couldn't alloc buffer");
return nil;
// COV_NF_END
}
[self getCharacters:[data mutableBytes]];
buffer = [data bytes];
}
if (!buffer || !data2) {
// COV_NF_START
_GTMDevLog(@"Unable to allocate buffer or data2");
return nil;
// COV_NF_END
}
unichar *buffer2 = (unichar *)[data2 mutableBytes];
NSUInteger buffer2Length = 0;
for (NSUInteger i = 0; i < length; ++i) {
HTMLEscapeMap *val = bsearch(&buffer[i], table,
size / sizeof(HTMLEscapeMap),
sizeof(HTMLEscapeMap), EscapeMapCompare);
if (val || (escapeUnicode && buffer[i] > 127)) {
if (buffer2Length) {
CFStringAppendCharacters((CFMutableStringRef)finalString,
buffer2,
buffer2Length);
buffer2Length = 0;
}
if (val) {
[finalString appendString:val->escapeSequence];
}
else {
_GTMDevAssert(escapeUnicode && buffer[i] > 127, @"Illegal Character");
[finalString appendFormat:@"&#%d;", buffer[i]];
}
} else {
buffer2[buffer2Length] = buffer[i];
buffer2Length += 1;
}
}
if (buffer2Length) {
CFStringAppendCharacters((CFMutableStringRef)finalString,
buffer2,
buffer2Length);
}
return finalString;
}
- (NSString *)gtm_stringByEscapingForHTML {
return [self gtm_stringByEscapingHTMLUsingTable:gUnicodeHTMLEscapeMap
ofSize:sizeof(gUnicodeHTMLEscapeMap)
escapingUnicode:NO];
} // gtm_stringByEscapingHTML
- (NSString *)gtm_stringByEscapingForAsciiHTML {
return [self gtm_stringByEscapingHTMLUsingTable:gAsciiHTMLEscapeMap
ofSize:sizeof(gAsciiHTMLEscapeMap)
escapingUnicode:YES];
} // gtm_stringByEscapingAsciiHTML
- (NSString *)gtm_stringByUnescapingFromHTML {
NSRange range = NSMakeRange(0, [self length]);
NSRange subrange = [self rangeOfString:@"&" options:NSBackwardsSearch range:range];
// if no ampersands, we've got a quick way out
if (subrange.length == 0) return self;
NSMutableString *finalString = [NSMutableString stringWithString:self];
do {
NSRange semiColonRange = NSMakeRange(subrange.location, NSMaxRange(range) - subrange.location);
semiColonRange = [self rangeOfString:@";" options:0 range:semiColonRange];
range = NSMakeRange(0, subrange.location);
// if we don't find a semicolon in the range, we don't have a sequence
if (semiColonRange.location == NSNotFound) {
continue;
}
NSRange escapeRange = NSMakeRange(subrange.location, semiColonRange.location - subrange.location + 1);
NSString *escapeString = [self substringWithRange:escapeRange];
NSUInteger length = [escapeString length];
// a squence must be longer than 3 (<) and less than 11 (ϑ)
if (length > 3 && length < 11) {
if ([escapeString characterAtIndex:1] == '#') {
unichar char2 = [escapeString characterAtIndex:2];
if (char2 == 'x' || char2 == 'X') {
// Hex escape squences £
NSString *hexSequence = [escapeString substringWithRange:NSMakeRange(3, length - 4)];
NSScanner *scanner = [NSScanner scannerWithString:hexSequence];
unsigned value;
if ([scanner scanHexInt:&value] &&
value < USHRT_MAX &&
value > 0
&& [scanner scanLocation] == length - 4) {
unichar uchar = value;
NSString *charString = [NSString stringWithCharacters:&uchar length:1];
[finalString replaceCharactersInRange:escapeRange withString:charString];
}
} else {
// Decimal Sequences {
NSString *numberSequence = [escapeString substringWithRange:NSMakeRange(2, length - 3)];
NSScanner *scanner = [NSScanner scannerWithString:numberSequence];
int value;
if ([scanner scanInt:&value] &&
value < USHRT_MAX &&
value > 0
&& [scanner scanLocation] == length - 3) {
unichar uchar = value;
NSString *charString = [NSString stringWithCharacters:&uchar length:1];
[finalString replaceCharactersInRange:escapeRange withString:charString];
}
}
} else {
// "standard" sequences
for (unsigned i = 0; i < sizeof(gAsciiHTMLEscapeMap) / sizeof(HTMLEscapeMap); ++i) {
if ([escapeString isEqualToString:gAsciiHTMLEscapeMap[i].escapeSequence]) {
[finalString replaceCharactersInRange:escapeRange withString:[NSString stringWithCharacters:&gAsciiHTMLEscapeMap[i].uchar length:1]];
break;
}
}
}
}
} while ((subrange = [self rangeOfString:@"&" options:NSBackwardsSearch range:range]).length != 0);
return finalString;
} // gtm_stringByUnescapingHTML
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+HTML.m | Objective-C | bsd | 14,917 |
//
// GTMLogger.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMLogger.h"
#import "GTMGarbageCollection.h"
#import <fcntl.h>
#import <unistd.h>
#import <stdlib.h>
#import <pthread.h>
// Define a trivial assertion macro to avoid dependencies
#ifdef DEBUG
#define GTMLOGGER_ASSERT(expr) assert(expr)
#else
#define GTMLOGGER_ASSERT(expr)
#endif
@interface GTMLogger (PrivateMethods)
- (void)logInternalFunc:(const char *)func
format:(NSString *)fmt
valist:(va_list)args
level:(GTMLoggerLevel)level;
@end
// Reference to the shared GTMLogger instance. This is not a singleton, it's
// just an easy reference to one shared instance.
static GTMLogger *gSharedLogger = nil;
@implementation GTMLogger
// Returns a pointer to the shared logger instance. If none exists, a standard
// logger is created and returned.
+ (id)sharedLogger {
@synchronized(self) {
if (gSharedLogger == nil) {
gSharedLogger = [[self standardLogger] retain];
}
GTMLOGGER_ASSERT(gSharedLogger != nil);
}
return [[gSharedLogger retain] autorelease];
}
+ (void)setSharedLogger:(GTMLogger *)logger {
@synchronized(self) {
[gSharedLogger autorelease];
gSharedLogger = [logger retain];
}
}
+ (id)standardLogger {
id<GTMLogWriter> writer = [NSFileHandle fileHandleWithStandardOutput];
id<GTMLogFormatter> fr = [[[GTMLogStandardFormatter alloc] init] autorelease];
id<GTMLogFilter> filter = [[[GTMLogLevelFilter alloc] init] autorelease];
return [self loggerWithWriter:writer formatter:fr filter:filter];
}
+ (id)standardLoggerWithStderr {
id me = [self standardLogger];
[me setWriter:[NSFileHandle fileHandleWithStandardError]];
return me;
}
+ (id)standardLoggerWithPath:(NSString *)path {
NSFileHandle *fh = [NSFileHandle fileHandleForLoggingAtPath:path mode:0644];
if (fh == nil) return nil;
id me = [self standardLogger];
[me setWriter:fh];
return me;
}
+ (id)loggerWithWriter:(id<GTMLogWriter>)writer
formatter:(id<GTMLogFormatter>)formatter
filter:(id<GTMLogFilter>)filter {
return [[[self alloc] initWithWriter:writer
formatter:formatter
filter:filter] autorelease];
}
+ (id)logger {
return [[[self alloc] init] autorelease];
}
- (id)init {
return [self initWithWriter:nil formatter:nil filter:nil];
}
- (id)initWithWriter:(id<GTMLogWriter>)writer
formatter:(id<GTMLogFormatter>)formatter
filter:(id<GTMLogFilter>)filter {
if ((self = [super init])) {
[self setWriter:writer];
[self setFormatter:formatter];
[self setFilter:filter];
GTMLOGGER_ASSERT(formatter_ != nil);
GTMLOGGER_ASSERT(filter_ != nil);
GTMLOGGER_ASSERT(writer_ != nil);
}
return self;
}
- (void)dealloc {
GTMLOGGER_ASSERT(writer_ != nil);
GTMLOGGER_ASSERT(formatter_ != nil);
GTMLOGGER_ASSERT(filter_ != nil);
[writer_ release];
[formatter_ release];
[filter_ release];
[super dealloc];
}
- (id<GTMLogWriter>)writer {
GTMLOGGER_ASSERT(writer_ != nil);
return [[writer_ retain] autorelease];
}
- (void)setWriter:(id<GTMLogWriter>)writer {
@synchronized(self) {
[writer_ autorelease];
if (writer == nil)
writer_ = [[NSFileHandle fileHandleWithStandardOutput] retain];
else
writer_ = [writer retain];
}
GTMLOGGER_ASSERT(writer_ != nil);
}
- (id<GTMLogFormatter>)formatter {
GTMLOGGER_ASSERT(formatter_ != nil);
return [[formatter_ retain] autorelease];
}
- (void)setFormatter:(id<GTMLogFormatter>)formatter {
@synchronized(self) {
[formatter_ autorelease];
if (formatter == nil)
formatter_ = [[GTMLogBasicFormatter alloc] init];
else
formatter_ = [formatter retain];
}
GTMLOGGER_ASSERT(formatter_ != nil);
}
- (id<GTMLogFilter>)filter {
GTMLOGGER_ASSERT(filter_ != nil);
return [[filter_ retain] autorelease];
}
- (void)setFilter:(id<GTMLogFilter>)filter {
@synchronized(self) {
[filter_ autorelease];
if (filter == nil)
filter_ = [[GTMLogNoFilter alloc] init];
else
filter_ = [filter retain];
}
GTMLOGGER_ASSERT(filter_ != nil);
}
- (void)logDebug:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelDebug];
va_end(args);
}
- (void)logInfo:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelInfo];
va_end(args);
}
- (void)logError:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelError];
va_end(args);
}
- (void)logAssert:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelAssert];
va_end(args);
}
@end // GTMLogger
@implementation GTMLogger (GTMLoggerMacroHelpers)
- (void)logFuncDebug:(const char *)func msg:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelDebug];
va_end(args);
}
- (void)logFuncInfo:(const char *)func msg:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelInfo];
va_end(args);
}
- (void)logFuncError:(const char *)func msg:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelError];
va_end(args);
}
- (void)logFuncAssert:(const char *)func msg:(NSString *)fmt, ... {
va_list args;
va_start(args, fmt);
[self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelAssert];
va_end(args);
}
@end // GTMLoggerMacroHelpers
@implementation GTMLogger (PrivateMethods)
- (void)logInternalFunc:(const char *)func
format:(NSString *)fmt
valist:(va_list)args
level:(GTMLoggerLevel)level {
GTMLOGGER_ASSERT(formatter_ != nil);
GTMLOGGER_ASSERT(filter_ != nil);
GTMLOGGER_ASSERT(writer_ != nil);
NSString *fname = func ? [NSString stringWithUTF8String:func] : nil;
NSString *msg = [formatter_ stringForFunc:fname
withFormat:fmt
valist:args
level:level];
if (msg && [filter_ filterAllowsMessage:msg level:level])
[writer_ logMessage:msg level:level];
}
@end // PrivateMethods
@implementation NSFileHandle (GTMFileHandleLogWriter)
+ (id)fileHandleForLoggingAtPath:(NSString *)path mode:(mode_t)mode {
int fd = -1;
if (path) {
int flags = O_WRONLY | O_APPEND | O_CREAT;
fd = open([path fileSystemRepresentation], flags, mode);
}
if (fd == -1) return nil;
return [[[self alloc] initWithFileDescriptor:fd
closeOnDealloc:YES] autorelease];
}
- (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level {
@synchronized(self) {
NSString *line = [NSString stringWithFormat:@"%@\n", msg];
[self writeData:[line dataUsingEncoding:NSUTF8StringEncoding]];
}
}
@end // GTMFileHandleLogWriter
@implementation NSArray (GTMArrayCompositeLogWriter)
- (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level {
@synchronized(self) {
id<GTMLogWriter> child = nil;
GTM_FOREACH_OBJECT(child, self) {
if ([child conformsToProtocol:@protocol(GTMLogWriter)])
[child logMessage:msg level:level];
}
}
}
@end // GTMArrayCompositeLogWriter
@implementation GTMLogger (GTMLoggerLogWriter)
- (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level {
switch (level) {
case kGTMLoggerLevelDebug:
[self logDebug:@"%@", msg];
break;
case kGTMLoggerLevelInfo:
[self logInfo:@"%@", msg];
break;
case kGTMLoggerLevelError:
[self logError:@"%@", msg];
break;
case kGTMLoggerLevelAssert:
[self logAssert:@"%@", msg];
break;
default:
// Ignore the message.
break;
}
}
@end // GTMLoggerLogWriter
@implementation GTMLogBasicFormatter
- (NSString *)stringForFunc:(NSString *)func
withFormat:(NSString *)fmt
valist:(va_list)args
level:(GTMLoggerLevel)level {
// Performance note: since we always have to create a new NSString from the
// returned CFStringRef, we may want to do a quick check here to see if |fmt|
// contains a '%', and if not, simply return 'fmt'.
CFStringRef cfmsg = NULL;
cfmsg = CFStringCreateWithFormatAndArguments(kCFAllocatorDefault,
NULL, // format options
(CFStringRef)fmt,
args);
return GTMCFAutorelease(cfmsg);
}
@end // GTMLogBasicFormatter
@implementation GTMLogStandardFormatter
- (id)init {
if ((self = [super init])) {
dateFormatter_ = [[NSDateFormatter alloc] init];
[dateFormatter_ setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter_ setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
pname_ = [[[NSProcessInfo processInfo] processName] copy];
pid_ = [[NSProcessInfo processInfo] processIdentifier];
}
return self;
}
- (void)dealloc {
[dateFormatter_ release];
[pname_ release];
[super dealloc];
}
- (NSString *)stringForFunc:(NSString *)func
withFormat:(NSString *)fmt
valist:(va_list)args
level:(GTMLoggerLevel)level {
GTMLOGGER_ASSERT(dateFormatter_ != nil);
NSString *tstamp = nil;
@synchronized (dateFormatter_) {
tstamp = [dateFormatter_ stringFromDate:[NSDate date]];
}
return [NSString stringWithFormat:@"%@ %@[%d/%p] [lvl=%d] %@ %@",
tstamp, pname_, pid_, pthread_self(),
level, (func ? func : @"(no func)"),
[super stringForFunc:func withFormat:fmt valist:args level:level]];
}
@end // GTMLogStandardFormatter
@implementation GTMLogLevelFilter
// Check the environment and the user preferences for the GTMVerboseLogging key
// to see if verbose logging has been enabled. The environment variable will
// override the defaults setting, so check the environment first.
// COV_NF_START
static BOOL IsVerboseLoggingEnabled(void) {
static NSString *const kVerboseLoggingKey = @"GTMVerboseLogging";
static char *env = NULL;
if (env == NULL)
env = getenv([kVerboseLoggingKey UTF8String]);
if (env && env[0]) {
return (strtol(env, NULL, 10) != 0);
}
return [[NSUserDefaults standardUserDefaults] boolForKey:kVerboseLoggingKey];
}
// COV_NF_END
// In DEBUG builds, log everything. If we're not in a debug build we'll assume
// that we're in a Release build.
- (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level {
#if DEBUG
return YES;
#endif
BOOL allow = YES;
switch (level) {
case kGTMLoggerLevelDebug:
allow = NO;
break;
case kGTMLoggerLevelInfo:
allow = (IsVerboseLoggingEnabled() == YES);
break;
case kGTMLoggerLevelError:
allow = YES;
break;
case kGTMLoggerLevelAssert:
allow = YES;
break;
default:
allow = YES;
break;
}
return allow;
}
@end // GTMLogLevelFilter
@implementation GTMLogNoFilter
- (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level {
return YES; // Allow everything through
}
@end // GTMLogNoFilter
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMLogger.m | Objective-C | bsd | 12,120 |
//
// GTMCalculatedRange.h
//
// This is a collection that allows you to calculate a value based on
// defined stops in a range.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
/// Allows you to calculate a value based on defined stops in a range.
//
/// For example if you have a range from 0.0 to 1.0 where the stop
/// located at 0.0 is red and the stop located at 1.0 is blue,
/// the value based on the position 0.5 would come out as purple assuming
/// that the valueAtPosition function calculates a purely linear mapping between
/// the stops at 0.0 and 1.0. Stops have indices and are sorted from lowest to
/// highest. The example above would have 2 stops. Stop 0 would be red and stop
/// 1 would be blue.
///
/// Subclasses of GTMCalculatedRange are expected to override the valueAtPosition:
/// method to return a value based on the position passed in, and the stops
/// that are currently set in the range. Stops do not necessarily have to
/// be the same type as the values that are calculated, but normally they are.
@interface GTMCalculatedRange : NSObject {
NSMutableArray *storage_;
}
// Adds a stop to the range at |position|. If there is already a stop
// at position |position| it is replaced.
//
// Args:
// item: the object to place at |position|.
// position: the position in the range to put |item|.
//
- (void)insertStop:(id)item atPosition:(CGFloat)position;
// Removes a stop from the range at |position|.
//
// Args:
// position: the position in the range to remove |item|.
//
// Returns:
// YES if there is a stop at |position| that has been removed
// NO if there is not a stop at the |position|
- (BOOL)removeStopAtPosition:(CGFloat)position;
// Removes stop |index| from the range. Stops are ordered
// based on position where index of x < index of y if position
// of x < position of y.
//
// Args:
// item: the object to place at |position|.
// position: the position in the range to put |item|.
//
- (void)removeStopAtIndex:(NSUInteger)index;
// Returns the number of stops in the range.
//
// Returns:
// number of stops
- (NSUInteger)stopCount;
// Returns the value at position |position|.
// This function should be overridden by subclasses to calculate a
// value for any given range.
// The default implementation returns a value if there happens to be
// a stop for the given position. Otherwise it returns nil.
//
// Args:
// position: the position to calculate a value for.
//
// Returns:
// value for position
- (id)valueAtPosition:(CGFloat)position;
// Returns the |index|'th stop and position in the set.
// Throws an exception if out of range.
//
// Args:
// index: the index of the stop
// outPosition: a pointer to a value to be filled in with a position.
// this can be NULL, in which case no position is returned.
//
// Returns:
// the stop at the index.
- (id)stopAtIndex:(NSUInteger)index position:(CGFloat*)outPosition;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMCalculatedRange.h | Objective-C | bsd | 3,609 |
//
// GTMStackTrace.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#include <CoreFoundation/CoreFoundation.h>
#import "GTMDefines.h"
#ifdef __cplusplus
extern "C" {
#endif
struct GTMAddressDescriptor {
const void *address; // address
const char *symbol; // nearest symbol to address
const char *class_name; // if it is an obj-c method, the method's class
BOOL is_class_method; // if it is an obj-c method, type of method
const char *filename; // file that the method came from.
};
// Returns a string containing a nicely formatted stack trace.
//
// This function gets the stack trace for the current thread. It will
// be from the caller of GTMStackTrace upwards to the top the calling stack.
// Typically this function will be used along with some logging,
// as in the following:
//
// MyAppLogger(@"Should never get here:\n%@", GTMStackTrace());
//
// Here is a sample stack trace returned from this function:
//
// #0 0x00002d92 D () [/Users/me/./StackLog]
// #1 0x00002e45 C () [/Users/me/./StackLog]
// #2 0x00002e53 B () [/Users/me/./StackLog]
// #3 0x00002e61 A () [/Users/me/./StackLog]
// #4 0x00002e6f main () [/Users/me/./StackLog]
// #5 0x00002692 tart () [/Users/me/./StackLog]
// #6 0x000025b9 tart () [/Users/me/./StackLog]
//
NSString *GTMStackTrace(void);
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
// Returns a string containing a nicely formatted stack trace from the
// exception. Only available on 10.5 or later, uses
// -[NSException callStackReturnAddresses].
//
NSString *GTMStackTraceFromException(NSException *e);
#endif
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Returns an array of program counters from the current thread's stack.
// *** You should probably use GTMStackTrace() instead of this function ***
// However, if you actually want all the PCs in "void *" form, then this
// funtion is more convenient. This will include PCs of GTMStaceTrace and
// its inner utility functions that you may want to strip out.
//
// You can use +[NSThread callStackReturnAddresses] in 10.5 or later.
//
// Args:
// outPcs - an array of "void *" pointers to the program counters found on the
// current thread's stack.
// count - the number of entries in the outPcs array
//
// Returns:
// The number of program counters actually added to outPcs.
//
NSUInteger GTMGetStackProgramCounters(void *outPcs[], NSUInteger count);
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Returns an array of GTMAddressDescriptors from the current thread's stack.
// *** You should probably use GTMStackTrace() instead of this function ***
// However, if you actually want all the PCs with symbols, this is the way
// to get them. There is no memory allocations done, so no clean up is required
// except for the caller to free outDescs if they allocated it themselves.
// This will include PCs of GTMStaceTrace and its inner utility functions that
// you may want to strip out.
//
// Args:
// outDescs - an array of "struct GTMAddressDescriptor" pointers corresponding
// to the program counters found on the current thread's stack.
// count - the number of entries in the outDescs array
//
// Returns:
// The number of program counters actually added to outPcs.
//
NSUInteger GTMGetStackAddressDescriptors(struct GTMAddressDescriptor outDescs[],
NSUInteger count);
#ifdef __cplusplus
}
#endif
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMStackTrace.h | Objective-C | bsd | 4,039 |
//
// GTMObjC2RuntimeTest.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMObjC2Runtime.h"
#import "GTMSenTestCase.h"
#import <string.h>
@protocol GTMObjC2Runtime_TestProtocol
@end
@protocol GTMObjC2Runtime_Test2Protocol
AT_OPTIONAL
- (NSString*)optional;
AT_REQUIRED
- (NSString*)required;
AT_OPTIONAL
+ (NSString*)class_optional;
AT_REQUIRED
+ (NSString*)class_required;
@end
@interface GTMObjC2RuntimeTest : GTMTestCase {
Class cls_;
}
@end
@interface GTMObjC2Runtime_TestClass : NSObject <GTMObjC2Runtime_TestProtocol>
- (NSString*)kwyjibo;
@end
@interface GTMObjC2Runtime_TestClass (GMObjC2Runtime_TestClassCategory)
- (NSString*)eatMyShorts;
@end
@implementation GTMObjC2Runtime_TestClass
+ (NSString*)dontHaveACow {
return @"dontHaveACow";
}
- (NSString*)kwyjibo {
return @"kwyjibo";
}
@end
@implementation GTMObjC2Runtime_TestClass (GMObjC2Runtime_TestClassCategory)
- (NSString*)eatMyShorts {
return @"eatMyShorts";
}
+ (NSString*)brokeHisBrain {
return @"brokeHisBrain";
}
@end
@interface GTMObjC2NotificationWatcher : NSObject
@end
@implementation GTMObjC2NotificationWatcher
- (void)startedTest:(NSNotification *)notification {
// Logs if we are testing on Tiger or Leopard runtime.
NSString *testName = [(SenTest*)[[notification object] test] name];
NSString *className = NSStringFromClass([GTMObjC2RuntimeTest class]);
if ([testName isEqualToString:className]) {
NSString *runtimeString;
#ifndef OBJC2_UNAVAILABLE
runtimeString = @"ObjC1";
#else
runtimeString = @"ObjC2";
#endif
NSLog(@"Running GTMObjC2RuntimeTests using %@ runtime.", runtimeString);
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self];
[self autorelease];
}
}
@end
@implementation GTMObjC2RuntimeTest
+ (void)initialize {
// This allows us to track which runtime we are actually testing.
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
// Watcher is released when it is notified.
GTMObjC2NotificationWatcher *watcher = [[GTMObjC2NotificationWatcher alloc] init];
[nc addObserver:watcher
selector:@selector(startedTest:)
name:SenTestSuiteDidStartNotification
object:nil];
}
- (void)setUp {
cls_ = [[GTMObjC2Runtime_TestClass class] retain];
}
- (void)tearDown {
[cls_ release];
}
- (void)test_object_getClass {
// Nil Checks
STAssertNil(object_getClass(nil), nil);
// Standard use check
GTMObjC2Runtime_TestClass *test = [[[cls_ alloc] init] autorelease];
Class cls = object_getClass(test);
STAssertEqualObjects(cls, cls_, nil);
}
- (void)test_class_getName {
// Nil Checks
const char *name = class_getName(nil);
STAssertEqualCStrings(name, "nil", nil);
// Standard use check
STAssertEqualCStrings(class_getName(cls_), "GTMObjC2Runtime_TestClass", nil);
}
- (void)test_class_conformsToProtocol {
// Nil Checks
STAssertFalse(class_conformsToProtocol(cls_, @protocol(NSObject)), nil);
STAssertFalse(class_conformsToProtocol(cls_, nil), nil);
// The following two tests intentionally commented out as they fail on
// Leopard with a crash, so we fail on Tiger intentionally as well.
// STAssertFalse(class_conformsToProtocol(nil, @protocol(NSObject)), nil);
// STAssertFalse(class_conformsToProtocol(nil, nil), nil);
// Standard use check
STAssertTrue(class_conformsToProtocol(cls_,
@protocol(GTMObjC2Runtime_TestProtocol)),
nil);
}
- (void)test_class_getSuperclass {
// Nil Checks
STAssertNil(class_getSuperclass(nil), nil);
// Standard use check
STAssertEqualObjects(class_getSuperclass(cls_), [NSObject class], nil);
}
- (void)test_class_copyMethodList {
// Nil Checks
Method *list = class_copyMethodList(nil, nil);
STAssertNULL(list, nil);
// Standard use check
list = class_copyMethodList(cls_, nil);
STAssertNotNULL(list, nil);
free(list);
unsigned int count = 0;
list = class_copyMethodList(cls_, &count);
STAssertNotNULL(list, nil);
STAssertEquals(count, 2U, nil);
STAssertNULL(list[count], nil);
free(list);
// Now test meta class
count = 0;
list = class_copyMethodList((Class)objc_getMetaClass(class_getName(cls_)),
&count);
STAssertNotNULL(list, nil);
STAssertEquals(count, 2U, nil);
STAssertNULL(list[count], nil);
free(list);
}
- (void)test_method_getName {
// Nil Checks
STAssertNULL(method_getName(nil), nil);
// Standard use check
Method *list = class_copyMethodList(cls_, nil);
STAssertNotNULL(list, nil);
const char* selName1 = sel_getName(method_getName(list[0]));
const char* selName2 = sel_getName(@selector(kwyjibo));
const char* selName3 = sel_getName(@selector(eatMyShorts));
BOOL isGood = ((strcmp(selName1, selName2)) == 0 || (strcmp(selName1, selName3) == 0));
STAssertTrue(isGood, nil);
free(list);
}
- (void)test_method_exchangeImplementations {
// nil checks
method_exchangeImplementations(nil, nil);
// Standard use check
GTMObjC2Runtime_TestClass *test = [[GTMObjC2Runtime_TestClass alloc] init];
STAssertNotNil(test, nil);
// Get initial values
NSString *val1 = [test kwyjibo];
STAssertNotNil(val1, nil);
NSString *val2 = [test eatMyShorts];
STAssertNotNil(val2, nil);
NSString *val3 = [GTMObjC2Runtime_TestClass dontHaveACow];
STAssertNotNil(val3, nil);
NSString *val4 = [GTMObjC2Runtime_TestClass brokeHisBrain];
STAssertNotNil(val4, nil);
// exchange the imps
Method *list = class_copyMethodList(cls_, nil);
STAssertNotNULL(list, nil);
method_exchangeImplementations(list[0], list[1]);
// test against initial values
NSString *val5 = [test kwyjibo];
STAssertNotNil(val5, nil);
NSString *val6 = [test eatMyShorts];
STAssertNotNil(val6, nil);
STAssertEqualStrings(val1, val6, nil);
STAssertEqualStrings(val2, val5, nil);
// Check that other methods not affected
STAssertEqualStrings([GTMObjC2Runtime_TestClass dontHaveACow], val3, nil);
STAssertEqualStrings([GTMObjC2Runtime_TestClass brokeHisBrain], val4, nil);
// exchange the imps back
method_exchangeImplementations(list[0], list[1]);
// and test against initial values again
NSString *val7 = [test kwyjibo];
STAssertNotNil(val7, nil);
NSString *val8 = [test eatMyShorts];
STAssertNotNil(val8, nil);
STAssertEqualStrings(val1, val7, nil);
STAssertEqualStrings(val2, val8, nil);
method_exchangeImplementations(list[0], nil);
method_exchangeImplementations(nil, list[0]);
val7 = [test kwyjibo];
STAssertNotNil(val7, nil);
val8 = [test eatMyShorts];
STAssertNotNil(val8, nil);
STAssertEqualStrings(val1, val7, nil);
STAssertEqualStrings(val2, val8, nil);
free(list);
[test release];
}
- (void)test_method_getImplementation {
// Nil Checks
STAssertNULL(method_getImplementation(nil), nil);
// Standard use check
Method *list = class_copyMethodList(cls_, nil);
STAssertNotNULL(list, nil);
STAssertNotNULL(method_getImplementation(list[0]), nil);
free(list);
}
- (void)test_method_setImplementation {
// Nil Checks
// This case intentionally not tested. Passing nil to method_setImplementation
// on Leopard crashes. It does on Tiger as well.
// STAssertNULL(method_setImplementation(nil, nil), nil);
// Standard use check
GTMObjC2Runtime_TestClass *test = [[GTMObjC2Runtime_TestClass alloc] init];
Method *list = class_copyMethodList(cls_, nil);
// Get initial value
NSString *str1 = objc_msgSend(test, method_getName(list[0]));
STAssertNotNil(str1, nil);
// set the imp to something else
IMP oldImp = method_setImplementation(list[0], method_getImplementation(list[1]));
STAssertNotNULL(oldImp, nil);
// make sure they are different
NSString *str2 = objc_msgSend(test,method_getName(list[0]));
STAssertNotNil(str2, nil);
STAssertNotEqualStrings(str1, str2, nil);
// reset the imp
IMP newImp = method_setImplementation(list[0], oldImp);
STAssertNotEquals(oldImp, newImp, nil);
// test nils
oldImp = method_setImplementation(list[0], nil);
STAssertNotNULL(oldImp, nil);
newImp = method_setImplementation(list[0], oldImp);
STAssertNULL(newImp, nil);
[test release];
free(list);
}
- (void)test_protocol_getMethodDescription {
// Check nil cases
struct objc_method_description desc = protocol_getMethodDescription(nil, nil,
YES, YES);
STAssertNULL(desc.name, nil);
desc = protocol_getMethodDescription(nil, @selector(optional), YES, YES);
STAssertNULL(desc.name, nil);
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
nil, YES, YES);
STAssertNULL(desc.name, nil);
// Instance Methods
// Check Required case. Only OBJC2 supports required.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(optional), YES, YES);
#if OBJC_API_VERSION >= 2
STAssertNULL(desc.name, nil);
#else
STAssertNotNULL(desc.name, nil);
#endif
// Check Required case. Only OBJC2 supports required.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(required), YES, YES);
STAssertNotNULL(desc.name, nil);
// Check Optional case. Only OBJC2 supports optional.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(optional), NO, YES);
STAssertNotNULL(desc.name, nil);
// Check Optional case. Only OBJC2 supports optional.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(required), NO, YES);
#if OBJC_API_VERSION >= 2
STAssertNULL(desc.name, nil);
#else
STAssertNotNULL(desc.name, nil);
#endif
// Class Methods
// Check Required case. Only OBJC2 supports required.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(class_optional), YES, NO);
#if OBJC_API_VERSION >= 2
STAssertNULL(desc.name, nil);
#else
STAssertNotNULL(desc.name, nil);
#endif
// Check Required case. Only OBJC2 supports required.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(class_required), YES, NO);
STAssertNotNULL(desc.name, nil);
// Check Optional case. Only OBJC2 supports optional.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(class_optional), NO, NO);
STAssertNotNULL(desc.name, nil);
// Check Optional case. Only OBJC2 supports optional.
desc = protocol_getMethodDescription(@protocol(GTMObjC2Runtime_Test2Protocol),
@selector(class_required), NO, NO);
#if OBJC_API_VERSION >= 2
STAssertNULL(desc.name, nil);
#else
STAssertNotNULL(desc.name, nil);
#endif
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMObjC2RuntimeTest.m | Objective-C | bsd | 11,631 |
//
// GTMNSFileManager+Path.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
/// A few useful methods for dealing with paths.
@interface NSFileManager (GMFileManagerPathAdditions)
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
/// For the Unix-y at heart, this is "mkdir -p". It tries to create
/// the directory specified by |path|, and any intervening directories that
/// are needed. Each directory that is created is created with |attributes|
/// (see other NSFileManager doco for the details on |attributes|).
///
/// If you are building for 10.5 or later, you should just use the new api:
/// createDirectoryAtPath:withIntermediateDirectories:attributes:error:
///
/// Args:
/// path - the path of the directory to create.
/// attributes - these are defined in the "Constants" section of Apple's
/// NSFileManager doco
///
/// Returns:
/// YES if |path| exists or was able to be created successfully
/// NO otherwise
///
- (BOOL)gtm_createFullPathToDirectory:(NSString *)path
attributes:(NSDictionary *)attributes;
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1050
/// Return an the paths for all resources in |directoryPath| that have the
/// |extension| file extension.
///
/// Args:
/// extension - the file extension (excluding the leading ".") to match.
/// If nil, all files are matched.
/// directoryPath - the directory to look in. NOTE: Subdirectories are NOT
/// traversed.
///
/// Returns:
/// An NSArray of absolute file paths that have |extension|. nil is returned
/// if |directoryPath| doesn't exist or can't be opened, and returns an empty
/// array if |directoryPath| is empty. ".", "..", and resource forks are never returned.
///
- (NSArray *)gtm_filePathsWithExtension:(NSString *)extension
inDirectory:(NSString *)directoryPath;
/// Same as -filePathsWithExtension:inDirectory: except |extensions| is an
/// NSArray of extensions to match.
///
- (NSArray *)gtm_filePathsWithExtensions:(NSArray *)extensions
inDirectory:(NSString *)directoryPath;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSFileManager+Path.h | Objective-C | bsd | 2,733 |
//
// GTMGarbageCollection.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// This allows us to easily move our code from GC to non GC.
// They are no-ops unless we are require Leopard or above.
// See
// http://developer.apple.com/documentation/Cocoa/Conceptual/GarbageCollection/index.html
// and
// http://developer.apple.com/documentation/Cocoa/Conceptual/GarbageCollection/Articles/gcCoreFoundation.html#//apple_ref/doc/uid/TP40006687-SW1
// for details.
#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) && !GTM_IPHONE_SDK
// General use would be to call this through GTMCFAutorelease
// but there may be a reason the you want to make something collectable
// but not autoreleased, especially in pure GC code where you don't
// want to bother with the nop autorelease. Done as a define instead of an
// inline so that tools like Clang's scan-build don't report code as leaking.
#define GTMNSMakeCollectable(cf) ((id)NSMakeCollectable(cf))
// GTMNSMakeUncollectable is for global maps, etc. that we don't
// want released ever. You should still retain these in non-gc code.
GTM_INLINE void GTMNSMakeUncollectable(id object) {
[[NSGarbageCollector defaultCollector] disableCollectorForPointer:object];
}
// Hopefully no code really needs this, but GTMIsGarbageCollectionEnabled is
// a common way to check at runtime if GC is on.
// There are some places where GC doesn't work w/ things w/in Apple's
// frameworks, so this is here so GTM unittests and detect it, and not run
// individual tests to work around bugs in Apple's frameworks.
GTM_INLINE BOOL GTMIsGarbageCollectionEnabled(void) {
return ([NSGarbageCollector defaultCollector] != nil);
}
#else
#define GTMNSMakeCollectable(cf) ((id)(cf))
GTM_INLINE void GTMNSMakeUncollectable(id object) {
}
GTM_INLINE BOOL GTMIsGarbageCollectionEnabled(void) {
return NO;
}
#endif
// GTMCFAutorelease makes a CF object collectable in GC mode, or adds it
// to the autorelease pool in non-GC mode. Either way it is taken care
// of. Done as a define instead of an inline so that tools like Clang's
// scan-build don't report code as leaking.
#define GTMCFAutorelease(cf) ([GTMNSMakeCollectable(cf) autorelease])
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMGarbageCollection.h | Objective-C | bsd | 2,815 |
//
// GTMStackTrace.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#include <stdlib.h>
#include <dlfcn.h>
#include <mach-o/nlist.h>
#include "GTMStackTrace.h"
#include "GTMObjC2Runtime.h"
struct GTMClassDescription {
const char *class_name;
Method *class_methods;
unsigned int class_method_count;
Method *instance_methods;
unsigned int instance_method_count;
};
#pragma mark Private utility functions
static struct GTMClassDescription *GTMClassDescriptions(NSUInteger *total_count) {
int class_count = objc_getClassList(nil, 0);
struct GTMClassDescription *class_descs
= calloc(class_count, sizeof(struct GTMClassDescription));
if (class_descs) {
Class *classes = calloc(class_count, sizeof(Class));
if (classes) {
objc_getClassList(classes, class_count);
for (int i = 0; i < class_count; ++i) {
class_descs[i].class_methods
= class_copyMethodList(object_getClass(classes[i]),
&class_descs[i].class_method_count);
class_descs[i].instance_methods
= class_copyMethodList(classes[i],
&class_descs[i].instance_method_count);
class_descs[i].class_name = class_getName(classes[i]);
}
free(classes);
} else {
// COV_NF_START - Don't know how to force this in a unittest
free(class_descs);
class_count = 0;
// COV_NF_END
}
}
if (total_count) {
*total_count = class_count;
}
return class_descs;
}
static void GTMFreeClassDescriptions(struct GTMClassDescription *class_descs,
NSUInteger count) {
if (!class_descs) return;
for (NSUInteger i = 0; i < count; ++i) {
if (class_descs[i].instance_methods) {
free(class_descs[i].instance_methods);
}
if (class_descs[i].class_methods) {
free(class_descs[i].class_methods);
}
}
free(class_descs);
}
static NSUInteger GTMGetStackAddressDescriptorsForAddresses(void *pcs[],
struct GTMAddressDescriptor outDescs[],
NSUInteger count) {
if (count < 1 || !pcs || !outDescs) return 0;
NSUInteger class_desc_count;
// Get our obj-c class descriptions. This is expensive, so we do it once
// at the top. We go through this because dladdr doesn't work with
// obj methods.
struct GTMClassDescription *class_descs
= GTMClassDescriptions(&class_desc_count);
// Iterate through the stack.
for (NSUInteger i = 0; i < count; ++i) {
const char *class_name = NULL;
BOOL is_class_method = NO;
size_t smallest_diff = SIZE_MAX;
struct GTMAddressDescriptor *currDesc = &outDescs[i];
currDesc->address = pcs[i];
Method best_method = NULL;
// Iterate through all the classes we know of.
for (NSUInteger j = 0; j < class_desc_count; ++j) {
// First check the class methods.
for (NSUInteger k = 0; k < class_descs[j].class_method_count; ++k) {
IMP imp = method_getImplementation(class_descs[j].class_methods[k]);
if (imp <= (IMP)currDesc->address) {
size_t diff = (size_t)currDesc->address - (size_t)imp;
if (diff < smallest_diff) {
best_method = class_descs[j].class_methods[k];
class_name = class_descs[j].class_name;
is_class_method = YES;
smallest_diff = diff;
}
}
}
// Then check the instance methods.
for (NSUInteger k = 0; k < class_descs[j].instance_method_count; ++k) {
IMP imp = method_getImplementation(class_descs[j].instance_methods[k]);
if (imp <= (IMP)currDesc->address) {
size_t diff = (size_t)currDesc->address - (size_t)imp;
if (diff < smallest_diff) {
best_method = class_descs[j].instance_methods[k];
class_name = class_descs[j].class_name;
is_class_method = NO;
smallest_diff = diff;
}
}
}
}
// If we have one, store it off.
if (best_method) {
currDesc->symbol = sel_getName(method_getName(best_method));
currDesc->is_class_method = is_class_method;
currDesc->class_name = class_name;
}
Dl_info info = { NULL, NULL, NULL, NULL };
// Check to see if the one returned by dladdr is better.
dladdr(currDesc->address, &info);
if ((size_t)currDesc->address - (size_t)info.dli_saddr < smallest_diff) {
currDesc->symbol = info.dli_sname;
currDesc->is_class_method = NO;
currDesc->class_name = NULL;
}
currDesc->filename = info.dli_fname;
}
GTMFreeClassDescriptions(class_descs, class_desc_count);
return count;
}
static NSString *GTMStackTraceFromAddressDescriptors(struct GTMAddressDescriptor descs[],
NSUInteger count) {
NSMutableString *trace = [NSMutableString string];
for (NSUInteger i = 0; i < count; i++) {
// Newline between all the lines
if (i) {
[trace appendString:@"\n"];
}
if (descs[i].class_name) {
[trace appendFormat:@"#%-2u %#08lx %s[%s %s] (%s)",
i, descs[i].address,
(descs[i].is_class_method ? "+" : "-"),
descs[i].class_name,
(descs[i].symbol ? descs[i].symbol : "??"),
(descs[i].filename ? descs[i].filename : "??")];
} else {
[trace appendFormat:@"#%-2u %#08lx %s() (%s)",
i, descs[i].address,
(descs[i].symbol ? descs[i].symbol : "??"),
(descs[i].filename ? descs[i].filename : "??")];
}
}
return trace;
}
#pragma mark Public functions
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Before 10.5, we have to do this ourselves. 10.5 adds
// +[NSThread callStackReturnAddresses].
// Structure representing a small portion of a stack, starting from the saved
// frame pointer, and continuing through the saved program counter.
struct GTMStackFrame {
void *saved_fp;
#if defined (__ppc__) || defined(__ppc64__)
void *padding;
#endif
void *saved_pc;
};
// __builtin_frame_address(0) is a gcc builtin that returns a pointer to the
// current frame pointer. We then use the frame pointer to walk the stack
// picking off program counters and other saved frame pointers. This works
// great on i386, but PPC requires a little more work because the PC (or link
// register) isn't always stored on the stack.
//
NSUInteger GTMGetStackProgramCounters(void *outPcs[], NSUInteger count) {
if (!outPcs || (count < 1)) return 0;
struct GTMStackFrame *fp;
#if defined (__ppc__) || defined(__ppc64__)
outPcs[0] = __builtin_return_address(0);
fp = (struct GTMStackFrame *)__builtin_frame_address(1);
#elif defined (__i386__) || defined(__x86_64__)
fp = (struct GTMStackFrame *)__builtin_frame_address(0);
#else
#error architecture not supported
#endif
NSUInteger level = 0;
while (level < count) {
if (fp == NULL) {
level--;
break;
}
outPcs[level] = fp->saved_pc;
level++;
fp = (struct GTMStackFrame *)fp->saved_fp;
}
return level;
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
NSUInteger GTMGetStackAddressDescriptors(struct GTMAddressDescriptor outDescs[],
NSUInteger count) {
if (count < 1 || !outDescs) return 0;
NSUInteger result = 0;
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Before 10.5, we collect the stack ourselves.
void **pcs = calloc(count, sizeof(void*));
if (!pcs) return 0;
NSUInteger newSize = GTMGetStackProgramCounters(pcs, count);
result = GTMGetStackAddressDescriptorsForAddresses(pcs, outDescs, newSize);
free(pcs);
#else // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
// Use +[NSThread callStackReturnAddresses]
NSArray *addresses = [NSThread callStackReturnAddresses];
NSUInteger addrCount = [addresses count];
if (addrCount) {
void **pcs = calloc(addrCount, sizeof(void*));
if (pcs) {
void **pcsScanner = pcs;
for (NSNumber *address in addresses) {
NSUInteger addr = [address unsignedIntegerValue];
*pcsScanner = (void *)addr;
++pcsScanner;
}
if (count < addrCount) {
addrCount = count;
}
// Fill in the desc structures
result = GTMGetStackAddressDescriptorsForAddresses(pcs, outDescs, addrCount);
}
if (pcs) free(pcs);
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
return result;
}
NSString *GTMStackTrace(void) {
// If we don't have enough frames, return an empty string
NSString *result = @"";
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
// Before 10.5, we collect the stack ourselves.
// The maximum number of stack frames that we will walk. We limit this so
// that super-duper recursive functions (or bugs) don't send us for an
// infinite loop.
struct GTMAddressDescriptor descs[100];
size_t depth = sizeof(descs) / sizeof(struct GTMAddressDescriptor);
depth = GTMGetStackAddressDescriptors(descs, depth);
// Start at the second item so that GTMStackTrace and it's utility calls (of
// which there is currently 1) is not included in the output.
const size_t kTracesToStrip = 2;
if (depth > kTracesToStrip) {
result = GTMStackTraceFromAddressDescriptors(&descs[kTracesToStrip],
(depth - kTracesToStrip));
}
#else // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
// Use +[NSThread callStackReturnAddresses]
NSArray *addresses = [NSThread callStackReturnAddresses];
NSUInteger count = [addresses count];
if (count) {
void **pcs = calloc(count, sizeof(void*));
struct GTMAddressDescriptor *descs
= calloc(count, sizeof(struct GTMAddressDescriptor));
if (pcs && descs) {
void **pcsScanner = pcs;
for (NSNumber *address in addresses) {
NSUInteger addr = [address unsignedIntegerValue];
*pcsScanner = (void *)addr;
++pcsScanner;
}
// Fill in the desc structures
count = GTMGetStackAddressDescriptorsForAddresses(pcs, descs, count);
// Build the trace
// We skip 1 frame because the +[NSThread callStackReturnAddresses] will
// start w/ this frame.
const size_t kTracesToStrip = 1;
if (count > kTracesToStrip) {
result = GTMStackTraceFromAddressDescriptors(&descs[kTracesToStrip],
(count - kTracesToStrip));
}
}
if (pcs) free(pcs);
if (descs) free(descs);
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
return result;
}
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
NSString *GTMStackTraceFromException(NSException *e) {
NSString *trace = @"";
// collect the addresses
NSArray *addresses = [e callStackReturnAddresses];
NSUInteger count = [addresses count];
if (count) {
void **pcs = calloc(count, sizeof(void*));
struct GTMAddressDescriptor *descs
= calloc(count, sizeof(struct GTMAddressDescriptor));
if (pcs && descs) {
void **pcsScanner = pcs;
for (NSNumber *address in addresses) {
NSUInteger addr = [address unsignedIntegerValue];
*pcsScanner = (void *)addr;
++pcsScanner;
}
// Fill in the desc structures
count = GTMGetStackAddressDescriptorsForAddresses(pcs, descs, count);
// Build the trace
trace = GTMStackTraceFromAddressDescriptors(descs, count);
}
if (pcs) free(pcs);
if (descs) free(descs);
}
return trace;
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMStackTrace.m | Objective-C | bsd | 12,274 |
//
// GTMBase64.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// GTMBase64
//
/// Helper for handling Base64 and WebSafeBase64 encodings
//
/// The webSafe methods use different character set and also the results aren't
/// always padded to a multiple of 4 characters. This is done so the resulting
/// data can be used in urls and url query arguments without needing any
/// encoding. You must use the webSafe* methods together, the data does not
/// interop with the RFC methods.
//
@interface GTMBase64 : NSObject
//
// Standard Base64 (RFC) handling
//
// encodeData:
//
/// Base64 encodes contents of the NSData object.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)encodeData:(NSData *)data;
// decodeData:
//
/// Base64 decodes contents of the NSData object.
//
/// Returns:
/// A new autoreleased NSData with the decoded payload. nil for any error.
//
+(NSData *)decodeData:(NSData *)data;
// encodeBytes:length:
//
/// Base64 encodes the data pointed at by |bytes|.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)encodeBytes:(const void *)bytes length:(NSUInteger)length;
// decodeBytes:length:
//
/// Base64 decodes the data pointed at by |bytes|.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)decodeBytes:(const void *)bytes length:(NSUInteger)length;
// stringByEncodingData:
//
/// Base64 encodes contents of the NSData object.
//
/// Returns:
/// A new autoreleased NSString with the encoded payload. nil for any error.
//
+(NSString *)stringByEncodingData:(NSData *)data;
// stringByEncodingBytes:length:
//
/// Base64 encodes the data pointed at by |bytes|.
//
/// Returns:
/// A new autoreleased NSString with the encoded payload. nil for any error.
//
+(NSString *)stringByEncodingBytes:(const void *)bytes length:(NSUInteger)length;
// decodeString:
//
/// Base64 decodes contents of the NSString.
//
/// Returns:
/// A new autoreleased NSData with the decoded payload. nil for any error.
//
+(NSData *)decodeString:(NSString *)string;
//
// Modified Base64 encoding so the results can go onto urls.
//
// The changes are in the characters generated and also allows the result to
// not be padded to a multiple of 4.
// Must use the matching call to encode/decode, won't interop with the
// RFC versions.
//
// webSafeEncodeData:padded:
//
/// WebSafe Base64 encodes contents of the NSData object. If |padded| is YES
/// then padding characters are added so the result length is a multiple of 4.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)webSafeEncodeData:(NSData *)data
padded:(BOOL)padded;
// webSafeDecodeData:
//
/// WebSafe Base64 decodes contents of the NSData object.
//
/// Returns:
/// A new autoreleased NSData with the decoded payload. nil for any error.
//
+(NSData *)webSafeDecodeData:(NSData *)data;
// webSafeEncodeBytes:length:padded:
//
/// WebSafe Base64 encodes the data pointed at by |bytes|. If |padded| is YES
/// then padding characters are added so the result length is a multiple of 4.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)webSafeEncodeBytes:(const void *)bytes
length:(NSUInteger)length
padded:(BOOL)padded;
// webSafeDecodeBytes:length:
//
/// WebSafe Base64 decodes the data pointed at by |bytes|.
//
/// Returns:
/// A new autoreleased NSData with the encoded payload. nil for any error.
//
+(NSData *)webSafeDecodeBytes:(const void *)bytes length:(NSUInteger)length;
// stringByWebSafeEncodingData:padded:
//
/// WebSafe Base64 encodes contents of the NSData object. If |padded| is YES
/// then padding characters are added so the result length is a multiple of 4.
//
/// Returns:
/// A new autoreleased NSString with the encoded payload. nil for any error.
//
+(NSString *)stringByWebSafeEncodingData:(NSData *)data
padded:(BOOL)padded;
// stringByWebSafeEncodingBytes:length:padded:
//
/// WebSafe Base64 encodes the data pointed at by |bytes|. If |padded| is YES
/// then padding characters are added so the result length is a multiple of 4.
//
/// Returns:
/// A new autoreleased NSString with the encoded payload. nil for any error.
//
+(NSString *)stringByWebSafeEncodingBytes:(const void *)bytes
length:(NSUInteger)length
padded:(BOOL)padded;
// webSafeDecodeString:
//
/// WebSafe Base64 decodes contents of the NSString.
//
/// Returns:
/// A new autoreleased NSData with the decoded payload. nil for any error.
//
+(NSData *)webSafeDecodeString:(NSString *)string;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMBase64.h | Objective-C | bsd | 5,498 |
//
// GTMNSEnumerator+FilterTest.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMNSEnumerator+Filter.h"
@interface GTMNSEnumerator_FilterTest : GTMTestCase
@end
@implementation GTMNSEnumerator_FilterTest
- (void)testEnumeratorByMakingEachObjectPerformSelector {
// test w/ a set of strings
NSSet *numbers = [NSSet setWithObjects: @"1", @"2", @"3", nil];
NSEnumerator *e = [[numbers objectEnumerator]
gtm_enumeratorByMakingEachObjectPerformSelector:@selector(stringByAppendingString:)
withObject:@" "];
NSMutableSet *trailingSpaces = [NSMutableSet set];
id obj;
while (nil != (obj = [e nextObject])) {
[trailingSpaces addObject:obj];
}
NSSet *trailingSpacesGood = [NSSet setWithObjects: @"1 ", @"2 ", @"3 ", nil];
STAssertEqualObjects(trailingSpaces, trailingSpacesGood, @"");
// test an empty set
NSSet *empty = [NSSet set];
e = [[empty objectEnumerator]
gtm_enumeratorByMakingEachObjectPerformSelector:@selector(stringByAppendingString:)
withObject:@" "];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
}
- (void)testFilteredEnumeratorByMakingEachObjectPerformSelector {
// test with a dict of strings
NSDictionary *testDict = [NSDictionary dictionaryWithObjectsAndKeys:
@"foo", @"1",
@"bar", @"2",
@"foobar", @"3",
nil];
// test those that have prefixes
NSEnumerator *e = [[testDict objectEnumerator]
gtm_filteredEnumeratorByMakingEachObjectPerformSelector:@selector(hasPrefix:)
withObject:@"foo"];
// since the dictionary iterates in any order, compare as sets
NSSet *filteredValues = [NSSet setWithArray:[e allObjects]];
NSSet *expectedValues = [NSSet setWithObjects:@"foo", @"foobar", nil];
STAssertEqualObjects(filteredValues, expectedValues, @"");
// test an empty set
NSSet *empty = [NSSet set];
e = [[empty objectEnumerator]
gtm_filteredEnumeratorByMakingEachObjectPerformSelector:@selector(hasPrefix:)
withObject:@"foo"];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
// test an set that will filter out
NSSet *filterAway = [NSSet setWithObjects:@"bar", @"baz", nil];
e = [[filterAway objectEnumerator]
gtm_filteredEnumeratorByMakingEachObjectPerformSelector:@selector(hasPrefix:)
withObject:@"foo"];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
}
- (void)testEnumeratorByTargetPerformOnEachSelector {
// test w/ a set of strings
NSSet *numbers = [NSSet setWithObjects: @"1", @"2", @"3", nil];
NSString *target = @"foo";
NSEnumerator *e = [[numbers objectEnumerator]
gtm_enumeratorByTarget:target
performOnEachSelector:@selector(stringByAppendingString:)];
// since the set iterates in any order, compare as sets
NSSet *collectedValues = [NSSet setWithArray:[e allObjects]];
NSSet *expectedValues = [NSSet setWithObjects:@"foo1", @"foo2", @"foo3", nil];
STAssertEqualObjects(collectedValues, expectedValues, @"");
// test an empty set
NSSet *empty = [NSSet set];
e = [[empty objectEnumerator]
gtm_enumeratorByTarget:target
performOnEachSelector:@selector(stringByAppendingString:)];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
}
- (void)testFilteredEnumeratorByTargetPerformOnEachSelector {
// test w/ a set of strings
NSSet *numbers = [NSSet setWithObjects:@"1", @"2", @"3", @"4", nil];
NSSet *target = [NSSet setWithObjects:@"2", @"4", @"6", nil];
NSEnumerator *e = [[numbers objectEnumerator]
gtm_filteredEnumeratorByTarget:target
performOnEachSelector:@selector(containsObject:)];
// since the set iterates in any order, compare as sets
NSSet *filteredValues = [NSSet setWithArray:[e allObjects]];
NSSet *expectedValues = [NSSet setWithObjects:@"2", @"4", nil];
STAssertEqualObjects(filteredValues, expectedValues, @"");
// test an empty set
NSSet *empty = [NSSet set];
e = [[empty objectEnumerator]
gtm_filteredEnumeratorByTarget:target
performOnEachSelector:@selector(containsObject:)];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
// test an set that will filter out
NSSet *filterAway = [NSSet setWithObjects:@"bar", @"baz", nil];
e = [[filterAway objectEnumerator]
gtm_filteredEnumeratorByTarget:target
performOnEachSelector:@selector(containsObject:)];
STAssertNil([e nextObject],
@"shouldn't have gotten anything from first advance of enumerator");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSEnumerator+FilterTest.m | Objective-C | bsd | 5,588 |
//
// GTMNSAppleScript+Handler.h
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// A category for calling handlers in NSAppleScript
@interface NSAppleScript(GTMAppleScriptHandlerAdditions)
// This method allows us to call a specific handler in an AppleScript.
// parameters are passed in left-right order 0-n.
//
// Args:
// handler - name of the handler to call in the Applescript
// params - the parameters to pass to the handler
// error - in non-nil returns any error that may have occurred.
//
// Returns:
// The result of the handler being called. nil on failure.
- (NSAppleEventDescriptor*)gtm_executePositionalHandler:(NSString*)handler
parameters:(NSArray*)params
error:(NSDictionary**)error;
- (NSAppleEventDescriptor*)gtm_executeLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count
error:(NSDictionary **)error;
- (NSSet*)gtm_handlers;
- (NSSet*)gtm_properties;
- (BOOL)gtm_setValue:(id)value forProperty:(NSString*)property;
- (id)gtm_valueForProperty:(NSString*)property;
@end
@interface NSAppleEventDescriptor(GTMAppleEventDescriptorScriptAdditions)
// Return an NSAppleScript for a desc of typeScript
// Returns nil on failure.
- (NSAppleScript*)gtm_scriptValue;
// Return a NSString with [eventClass][eventID] for typeEvent 'evnt'
- (NSString*)gtm_eventValue;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleScript+Handler.h | Objective-C | bsd | 2,245 |
//
// GTMNSDictionary+URLArguments.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSDictionary+URLArguments.h"
#import "GTMNSString+URLArguments.h"
#import "GTMMethodCheck.h"
@implementation NSDictionary (GTMNSDictionaryURLArgumentsAdditions)
GTM_METHOD_CHECK(NSString, gtm_stringByEscapingForURLArgument); // COV_NF_LINE
- (NSString *)gtm_httpArgumentsString {
NSMutableArray* arguments = [NSMutableArray arrayWithCapacity:[self count]];
NSEnumerator* keyEnumerator = [self keyEnumerator];
NSString* key;
while ((key = [keyEnumerator nextObject])) {
[arguments addObject:[NSString stringWithFormat:@"%@=%@",
[key gtm_stringByEscapingForURLArgument],
[[[self objectForKey:key] description] gtm_stringByEscapingForURLArgument]]];
}
return [arguments componentsJoinedByString:@"&"];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSDictionary+URLArguments.m | Objective-C | bsd | 1,440 |
//
// GTMFourCharCodeTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMFourCharCode.h"
@interface GTMFourCharCodeTest : GTMTestCase
@end
@implementation GTMFourCharCodeTest
const FourCharCode kGTMHighMacOSRomanCode = 0xA5A8A9AA; // '•®©™'
- (void)testFourCharCode {
GTMFourCharCode *fcc = [GTMFourCharCode fourCharCodeWithString:@"APPL"];
STAssertNotNil(fcc, nil);
STAssertEqualObjects([fcc stringValue], @"APPL", nil);
STAssertEqualObjects([fcc numberValue], [NSNumber numberWithUnsignedInt:'APPL'], nil);
STAssertEquals([fcc fourCharCode], (FourCharCode)'APPL', nil);
STAssertEqualObjects([fcc description], @"GTMFourCharCode - APPL (0x4150504C)", nil);
STAssertEquals([fcc hash], (NSUInteger)'APPL', nil);
GTMFourCharCode *fcc2 = [GTMFourCharCode fourCharCodeWithFourCharCode:kGTMHighMacOSRomanCode];
STAssertNotNil(fcc2, nil);
STAssertEqualObjects([fcc2 stringValue], @"•®©™", nil);
STAssertEqualObjects([fcc2 numberValue], [NSNumber numberWithUnsignedInt:kGTMHighMacOSRomanCode], nil);
STAssertEquals([fcc2 fourCharCode], (FourCharCode)kGTMHighMacOSRomanCode, nil);
STAssertNotEqualObjects(fcc, fcc2, nil);
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:fcc];
STAssertNotNil(data, nil);
fcc2 = (GTMFourCharCode*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
STAssertNotNil(fcc2, nil);
STAssertEqualObjects(fcc, fcc2, nil);
fcc = [[[GTMFourCharCode alloc] initWithFourCharCode:'\?\?\?\?'] autorelease];
STAssertNotNil(fcc, nil);
STAssertEqualObjects([fcc stringValue], @"????", nil);
STAssertEqualObjects([fcc numberValue], [NSNumber numberWithUnsignedInt:'\?\?\?\?'], nil);
STAssertEquals([fcc fourCharCode], (FourCharCode)'\?\?\?\?', nil);
fcc = [[[GTMFourCharCode alloc] initWithString:@"????"] autorelease];
STAssertNotNil(fcc, nil);
STAssertEqualObjects([fcc stringValue], @"????", nil);
STAssertEqualObjects([fcc numberValue], [NSNumber numberWithUnsignedInt:'\?\?\?\?'], nil);
STAssertEquals([fcc fourCharCode], (FourCharCode)'\?\?\?\?', nil);
fcc = [GTMFourCharCode fourCharCodeWithFourCharCode:1];
STAssertNotNil(fcc, nil);
STAssertEqualObjects([fcc stringValue], @"\0\0\0\1", nil);
STAssertEqualObjects([fcc numberValue], [NSNumber numberWithUnsignedInt:1], nil);
STAssertEquals([fcc fourCharCode], (FourCharCode)1, nil);
fcc = [GTMFourCharCode fourCharCodeWithString:@"BADDSTRING"];
STAssertNil(fcc, nil);
}
- (void)testStringWithCode {
STAssertEqualObjects([GTMFourCharCode stringWithFourCharCode:'APPL'], @"APPL", nil);
STAssertEqualObjects([GTMFourCharCode stringWithFourCharCode:1], @"\0\0\0\1", nil);
STAssertEqualObjects([GTMFourCharCode stringWithFourCharCode:kGTMHighMacOSRomanCode], @"•®©™", nil);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMFourCharCodeTest.m | Objective-C | bsd | 3,367 |
//
// GTMNSAppleEventDescriptor+FoundationTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import <Carbon/Carbon.h>
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMFourCharCode.h"
#import "GTMUnitTestDevLog.h"
@interface GTMNSAppleEventDescriptor_TestObject : NSObject
@end
@implementation GTMNSAppleEventDescriptor_TestObject
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
return nil;
}
@end
@interface GTMNSAppleEventDescriptor_FoundationTest : GTMTestCase {
BOOL gotEvent_;
}
- (void)handleEvent:(NSAppleEventDescriptor*)event
withReply:(NSAppleEventDescriptor*)reply;
- (void)handleEvent:(NSAppleEventDescriptor*)event
withError:(NSAppleEventDescriptor*)reply;
@end
@implementation GTMNSAppleEventDescriptor_FoundationTest
- (void)testRegisterSelectorForTypesCount {
// Weird edge casey stuff.
// + (void)registerSelector:(SEL)selector
// forTypes:(DescType*)types count:(int)count
// is tested heavily by the other NSAppleEventDescriptor+foo categories.
DescType type;
[NSAppleEventDescriptor gtm_registerSelector:nil
forTypes:&type count:1];
[NSAppleEventDescriptor gtm_registerSelector:@selector(retain)
forTypes:nil count:1];
[NSAppleEventDescriptor gtm_registerSelector:@selector(retain)
forTypes:&type count:0];
// Test the duplicate case
[NSAppleEventDescriptor gtm_registerSelector:@selector(retain)
forTypes:&type count:1];
[GTMUnitTestDevLog expectPattern:@"retain being replaced with retain exists "
"for type: [0-9]+"];
[NSAppleEventDescriptor gtm_registerSelector:@selector(retain)
forTypes:&type count:1];
}
- (void)testObjectValue {
// - (void)testObjectValue is tested heavily by the other
// NSAppleEventDescriptor+foo categories.
long data = 1;
// v@#f is just a bogus descriptor type that we don't recognize.
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor descriptorWithDescriptorType:'v@#f'
bytes:&data
length:sizeof(data)];
id value = [desc gtm_objectValue];
STAssertNil(value, nil);
}
- (void)testAppleEventDescriptor {
// - (NSAppleEventDescriptor*)appleEventDescriptor is tested heavily by the
// other NSAppleEventDescriptor+foo categories.
NSAppleEventDescriptor *desc = [self gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
STAssertEquals([desc descriptorType], (DescType)typeUnicodeText, nil);
}
- (void)testDescriptorWithArrayAndArrayValue {
// Test empty array
NSAppleEventDescriptor *desc = [[NSArray array] gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
STAssertEquals([desc numberOfItems], (NSInteger)0, nil);
// Complex array
NSArray *array = [NSArray arrayWithObjects:
[NSNumber numberWithInt:4],
@"foo",
[NSNumber numberWithInt:2],
@"bar",
[NSArray arrayWithObjects:
@"bam",
[NSArray arrayWithObject:[NSNumber numberWithFloat:4.2f]],
nil],
nil];
STAssertNotNil(array, nil);
desc = [array gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
NSArray *array2 = [desc gtm_objectValue];
STAssertNotNil(array2, nil);
NSArray *array3 = [desc gtm_arrayValue];
STAssertNotNil(array3, nil);
STAssertTrue([array isEqualToArray:array2],
@"array: %@\narray2: %@\ndesc: %@",
[array description], [array2 description], [desc description]);
STAssertTrue([array2 isEqualToArray:array3],
@"array: %@\narray2: %@\ndesc: %@",
[array description], [array2 description], [desc description]);
// Test a single object
array = [NSArray arrayWithObject:@"foo"];
desc = [NSAppleEventDescriptor descriptorWithString:@"foo"];
STAssertNotNil(desc, nil);
array2 = [desc gtm_arrayValue];
STAssertTrue([array isEqualToArray:array2],
@"array: %@\narray2: %@\ndesc: %@",
[array description], [array2 description], [desc description]);
// Something that doesn't know how to register itself.
GTMNSAppleEventDescriptor_TestObject *obj
= [[[GTMNSAppleEventDescriptor_TestObject alloc] init] autorelease];
[GTMUnitTestDevLog expectPattern:@"Unable to create Apple Event Descriptor for .*"];
desc = [[NSArray arrayWithObject:obj] gtm_appleEventDescriptor];
STAssertNil(desc, @"Should be nil");
// A list containing something we don't know how to deal with
desc = [NSAppleEventDescriptor listDescriptor];
NSAppleEventDescriptor *desc2
= [NSAppleEventDescriptor descriptorWithDescriptorType:'@!@#'
bytes:&desc
length:sizeof(desc)];
[GTMUnitTestDevLog expectPattern:@"Unknown type of descriptor "
"<NSAppleEventDescriptor: '@!@#'\\(\\$[0-9A-F]*\\$\\)>"];
[desc insertDescriptor:desc2 atIndex:0];
array = [desc gtm_objectValue];
STAssertEquals([array count], (NSUInteger)0, @"Should have 0 items");
}
- (void)testDescriptorWithDictionaryAndDictionaryValue {
// Test empty dictionary
NSAppleEventDescriptor *desc
= [[NSDictionary dictionary] gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
STAssertEquals([desc numberOfItems], (NSInteger)0, nil);
// Complex dictionary
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"fooobject",
@"fookey",
@"barobject",
@"barkey",
[NSDictionary dictionaryWithObjectsAndKeys:
@"january",
[GTMFourCharCode fourCharCodeWithFourCharCode:cJanuary],
@"february",
[GTMFourCharCode fourCharCodeWithFourCharCode:cFebruary],
nil],
@"dictkey",
nil];
STAssertNotNil(dictionary, nil);
desc = [dictionary gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
NSDictionary *dictionary2 = [desc gtm_objectValue];
STAssertNotNil(dictionary2, nil);
NSDictionary *dictionary3 = [desc gtm_dictionaryValue];
STAssertNotNil(dictionary3, nil);
STAssertEqualObjects(dictionary, dictionary2,
@"desc: %@", [desc description]);
STAssertEqualObjects(dictionary2, dictionary3,
@"desc: %@", [desc description]);
// Something that doesn't know how to register itself.
GTMNSAppleEventDescriptor_TestObject *obj
= [[[GTMNSAppleEventDescriptor_TestObject alloc] init] autorelease];
[GTMUnitTestDevLog expectPattern:@"Unable to create Apple Event Descriptor for .*"];
desc = [[NSDictionary dictionaryWithObject:obj
forKey:@"foo"] gtm_appleEventDescriptor];
STAssertNil(desc, @"Should be nil");
GTMFourCharCode *fcc = [GTMFourCharCode fourCharCodeWithFourCharCode:cJanuary];
desc = [[NSDictionary dictionaryWithObject:obj
forKey:fcc] gtm_appleEventDescriptor];
STAssertNil(desc, @"Should be nil");
// A list containing something we don't know how to deal with
desc = [NSAppleEventDescriptor recordDescriptor];
NSAppleEventDescriptor *desc2
= [NSAppleEventDescriptor descriptorWithDescriptorType:'@!@#'
bytes:&desc
length:sizeof(desc)];
[desc setDescriptor:desc2 forKeyword:cJanuary];
[GTMUnitTestDevLog expectPattern:@"Unknown type of descriptor "
"<NSAppleEventDescriptor: '@!@#'\\(\\$[0-9A-F]+\\$\\)>"];
dictionary = [desc gtm_objectValue];
STAssertEquals([dictionary count], (NSUInteger)0, @"Should have 0 items");
// A bad dictionary
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"foo",
[GTMFourCharCode fourCharCodeWithFourCharCode:'APPL'],
@"bam",
@"bar",
nil];
STAssertNotNil(dictionary, nil);
// I cannot use expectString here to the exact string because interestingly
// dictionaries in 64 bit enumerate in a different order from dictionaries
// on 32 bit. This is the closest pattern I can match.
[GTMUnitTestDevLog expectPattern:@"Keys must be homogenous .*"];
desc = [dictionary gtm_appleEventDescriptor];
STAssertNil(desc, nil);
// Another bad dictionary
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"foo",
[NSNumber numberWithInt:4],
@"bam",
@"bar",
nil];
STAssertNotNil(dictionary, nil);
// I cannot use expectString here to the exact string because interestingly
// dictionaries in 64 bit enumerate in a different order from dictionaries
// on 32 bit. This is the closest pattern I can match.
[GTMUnitTestDevLog expectPattern:@"Keys must be .*"];
desc = [dictionary gtm_appleEventDescriptor];
STAssertNil(desc, nil);
// A bad descriptor
desc = [NSAppleEventDescriptor recordDescriptor];
STAssertNotNil(desc, @"");
NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", @"bam", nil];
STAssertNotNil(array, @"");
NSAppleEventDescriptor *userRecord = [array gtm_appleEventDescriptor];
STAssertNotNil(userRecord, @"");
[desc setDescriptor:userRecord forKeyword:keyASUserRecordFields];
[GTMUnitTestDevLog expectPattern:@"Got a key bam with no value in <.*"];
dictionary = [desc gtm_objectValue];
STAssertNil(dictionary, @"Should be nil");
}
- (void)testDescriptorWithNull {
// Test Null
NSNull *null = [NSNull null];
NSAppleEventDescriptor *desc = [null gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
NSNull *null2 = [desc gtm_objectValue];
STAssertNotNil(null2, nil);
NSNull *null3 = [desc gtm_nullValue];
STAssertNotNil(null2, nil);
STAssertEqualObjects(null, null2,
@"null: %@\null2: %@\ndesc: %@",
[null description], [null2 description],
[desc description]);
STAssertEqualObjects(null, null3,
@"null: %@\null3: %@\ndesc: %@",
[null description], [null3 description],
[desc description]);
}
- (void)testDescriptorWithString {
// Test empty String
NSAppleEventDescriptor *desc = [[NSString string] gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
// Test String
NSString *string = @"Ratatouille!";
desc = [string gtm_appleEventDescriptor];
STAssertNotNil(desc, nil);
NSString *string2 = [desc gtm_objectValue];
STAssertNotNil(string2, nil);
STAssertEqualObjects(string, string2,
@"string: %@\nstring: %@\ndesc: %@",
[string description], [string2 description], [desc description]);
}
- (void)testDescriptorWithNumberAndNumberValue {
// There's really no good way to make this into a loop sadly due
// to me having to pass a pointer of bytes to NSInvocation as an argument.
// I want the compiler to convert my int to the appropriate type.
NSNumber *original = [NSNumber numberWithBool:YES];
STAssertNotNil(original, @"Value: YES");
NSAppleEventDescriptor *desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: YES");
id returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: YES");
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: YES");
STAssertEqualObjects(original, returned, @"Value: YES");
desc = [desc coerceToDescriptorType:typeBoolean];
NSNumber *number = [desc gtm_numberValue];
STAssertEqualObjects(number, original, @"Value: YES");
original = [NSNumber numberWithBool:NO];
STAssertNotNil(original, @"Value: NO");
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: NO");
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: NO");
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: NO");
STAssertEqualObjects(original, returned, @"Value: NO");
sranddev();
double value = rand();
original = [NSNumber numberWithChar:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithUnsignedChar:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithShort:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithUnsignedShort:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithInt:(int)value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithUnsignedInt:(unsigned int)value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithLong:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithUnsignedLong:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithLongLong:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithUnsignedLongLong:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
float floatA = rand();
float floatB = rand();
value = floatA / floatB;
original = [NSNumber numberWithFloat:(float)value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
double doubleA = rand();
double doubleB = rand();
value = doubleA / doubleB;
original = [NSNumber numberWithDouble:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = rand();
original = [NSNumber numberWithBool:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = NAN;
original = [NSNumber numberWithDouble:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = INFINITY;
original = [NSNumber numberWithDouble:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = -0.0;
original = [NSNumber numberWithDouble:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
value = -INFINITY;
original = [NSNumber numberWithDouble:value];
STAssertNotNil(original, @"Value: %g", value);
desc = [original gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Value: %g", value);
returned = [desc gtm_objectValue];
STAssertNotNil(returned, @"Value: %g", value);
STAssertTrue([returned isKindOfClass:[NSNumber class]], @"Value: %g", value);
STAssertEqualObjects(original, returned, @"Value: %g", value);
}
- (void)testDescriptorWithDoubleAndDoubleValue {
sranddev();
for (int i = 0; i < 1000; ++i) {
double value1 = rand();
double value2 = rand();
double value = value1 / value2;
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithDouble:value];
STAssertNotNil(desc, @"Value: %g", value);
double returnedValue = [desc gtm_doubleValue];
STAssertEquals(value, returnedValue, @"Value: %g", value);
}
double specialCases[] = { 0.0f, __DBL_MIN__, __DBL_EPSILON__, INFINITY, NAN };
for (size_t i = 0; i < sizeof(specialCases) / sizeof(double); ++i) {
double value = specialCases[i];
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithDouble:value];
STAssertNotNil(desc, @"Value: %g", value);
double returnedValue = [desc gtm_doubleValue];
STAssertEquals(value, returnedValue, @"Value: %g", value);
}
}
- (void)testDescriptorWithFloatAndFloatValue {
sranddev();
for (int i = 0; i < 1000; ++i) {
float value1 = rand();
float value2 = rand();
float value = value1 / value2;
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithFloat:value];
STAssertNotNil(desc, @"Value: %f", value);
float returnedValue = [desc gtm_floatValue];
STAssertEquals(value, returnedValue, @"Value: %f", value);
}
float specialCases[] = { 0.0f, FLT_MIN, FLT_MAX, FLT_EPSILON, INFINITY, NAN };
for (size_t i = 0; i < sizeof(specialCases) / sizeof(float); ++i) {
float value = specialCases[i];
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithFloat:value];
STAssertNotNil(desc, @"Value: %f", value);
float returnedValue = [desc gtm_floatValue];
STAssertEquals(value, returnedValue, @"Value: %f", value);
}
}
- (void)testDescriptorWithCGFloatAndCGFloatValue {
sranddev();
for (int i = 0; i < 1000; ++i) {
CGFloat value1 = rand();
CGFloat value2 = rand();
CGFloat value = value1 / value2;
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithCGFloat:value];
STAssertNotNil(desc, @"Value: %g", (double)value);
CGFloat returnedValue = [desc gtm_cgFloatValue];
STAssertEquals(value, returnedValue, @"Value: %g", (double)value);
}
CGFloat specialCases[] = { 0.0f, CGFLOAT_MIN, CGFLOAT_MAX, NAN };
for (size_t i = 0; i < sizeof(specialCases) / sizeof(CGFloat); ++i) {
CGFloat value = specialCases[i];
NSAppleEventDescriptor *desc
= [NSAppleEventDescriptor gtm_descriptorWithCGFloat:value];
STAssertNotNil(desc, @"Value: %g", (double)value);
CGFloat returnedValue = [desc gtm_cgFloatValue];
STAssertEquals(value, returnedValue, @"Value: %g", (double)value);
}
}
- (void)handleEvent:(NSAppleEventDescriptor*)event
withReply:(NSAppleEventDescriptor*)reply {
gotEvent_ = YES;
NSAppleEventDescriptor *answer = [NSAppleEventDescriptor descriptorWithInt32:1];
[reply setDescriptor:answer forKeyword:keyDirectObject];
}
- (void)handleEvent:(NSAppleEventDescriptor*)event
withError:(NSAppleEventDescriptor*)error {
gotEvent_ = YES;
NSAppleEventDescriptor *answer = [NSAppleEventDescriptor descriptorWithInt32:1];
[error setDescriptor:answer forKeyword:keyErrorNumber];
}
- (void)testSend {
const AEEventClass eventClass = 'Fooz';
const AEEventID eventID = 'Ball';
NSAppleEventManager *mgr = [NSAppleEventManager sharedAppleEventManager];
[mgr setEventHandler:self
andSelector:@selector(handleEvent:withReply:)
forEventClass:eventClass
andEventID:'Ball'];
NSAppleEventDescriptor *currentProcess
= [[NSProcessInfo processInfo] gtm_appleEventDescriptor];
NSAppleEventDescriptor *event
= [NSAppleEventDescriptor appleEventWithEventClass:eventClass
eventID:eventID
targetDescriptor:currentProcess
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID];
gotEvent_ = NO;
NSAppleEventDescriptor *reply;
BOOL goodEvent = [event gtm_sendEventWithMode:kAEWaitReply timeOut:60 reply:&reply];
[mgr removeEventHandlerForEventClass:eventClass andEventID:eventID];
STAssertTrue(goodEvent, @"bad event?");
STAssertTrue(gotEvent_, @"Handler not called");
NSAppleEventDescriptor *value = [reply descriptorForKeyword:keyDirectObject];
STAssertEquals([value int32Value], (SInt32)1, @"didn't get reply");
gotEvent_ = NO;
[GTMUnitTestDevLog expectString:@"Unable to send message: "
"<NSAppleEventDescriptor: 'Fooz'\\'Ball'{ }> -1708"];
goodEvent = [event gtm_sendEventWithMode:kAEWaitReply timeOut:60 reply:&reply];
STAssertFalse(goodEvent, @"good event?");
STAssertFalse(gotEvent_, @"Handler called?");
[mgr setEventHandler:self
andSelector:@selector(handleEvent:withError:)
forEventClass:eventClass
andEventID:eventID];
gotEvent_ = NO;
goodEvent = [event gtm_sendEventWithMode:kAEWaitReply timeOut:60 reply:&reply];
STAssertFalse(goodEvent, @"good event?");
STAssertTrue(gotEvent_, @"Handler not called?");
[mgr removeEventHandlerForEventClass:eventClass andEventID:eventID];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+FoundationTest.m | Objective-C | bsd | 25,499 |
//
// GTMCalculatedRangeTest.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMCalculatedRange.h"
#import "GTMSenTestCase.h"
@interface GTMCalculatedRangeTest : GTMTestCase {
GTMCalculatedRange *range_;
}
@end
@implementation GTMCalculatedRangeTest
NSString *kStrings[] = { @"Fee", @"Fi", @"Fo", @"Fum" };
const NSUInteger kStringCount = sizeof(kStrings) / sizeof(NSString*);
const CGFloat kOddPosition = 0.14159265f;
const CGFloat kExistingPosition = 0.5f;
const NSUInteger kExisitingIndex = 2;
- (void)setUp {
range_ = [[GTMCalculatedRange alloc] init];
for(NSUInteger i = kStringCount; i > 0; --i) {
[range_ insertStop:kStrings[kStringCount - i] atPosition: 1.0f / i];
}
}
- (void)tearDown {
[range_ release];
}
- (void)testInsertStop {
// new position
NSString *theString = @"I smell the blood of an Englishman!";
[range_ insertStop:theString atPosition:kOddPosition];
STAssertEquals([range_ stopCount], kStringCount + 1, @"Stop count was bad");
NSString *getString = [range_ valueAtPosition:kOddPosition];
STAssertNotNil(getString, @"String was bad");
STAssertEquals(theString, getString, @"Stops weren't equal");
// existing position
NSString *theStringTake2 = @"I smell the blood of an Englishman! Take 2";
[range_ insertStop:theStringTake2 atPosition:kOddPosition];
STAssertEquals([range_ stopCount], kStringCount + 1, @"Stop count was bad");
getString = [range_ valueAtPosition:kOddPosition];
STAssertNotNil(getString, @"String was bad");
STAssertEquals(theStringTake2, getString, @"Stops weren't equal");
STAssertNotEquals(theString, getString, @"Should be the new value");
STAssertNotEqualObjects(theString, getString, @"Should be the new value");
}
- (void)testRemoveStopAtPosition {
STAssertFalse([range_ removeStopAtPosition: kOddPosition], @"Was able to remove non-existant stop");
STAssertTrue([range_ removeStopAtPosition: kExistingPosition], @"Was unable to remove good stop");
STAssertEquals([range_ stopCount], kStringCount - 1, @"Removing stop should adjust stop count");
}
- (void)testRemoveStopAtIndex {
STAssertThrows([range_ removeStopAtIndex: kStringCount], @"Was able to remove non-existant stop");
STAssertNoThrow([range_ removeStopAtIndex: kStringCount - 1], @"Was unable to remove good stop");
STAssertEquals([range_ stopCount], kStringCount - 1, @"Removing stop should adjust stop count");
}
- (void)testStopCount {
STAssertEquals([range_ stopCount], kStringCount, @"Bad stop count");
}
- (void)testValueAtPosition {
STAssertEqualObjects([range_ valueAtPosition: kExistingPosition], kStrings[kExisitingIndex], nil);
STAssertNotEqualObjects([range_ valueAtPosition: kExistingPosition], kStrings[kStringCount - 1], nil);
STAssertNil([range_ valueAtPosition: kOddPosition], nil);
}
- (void)testStopAtIndex {
CGFloat thePosition;
STAssertEqualObjects([range_ stopAtIndex:kStringCount - 1 position:nil], kStrings[kStringCount - 1], nil);
STAssertEqualObjects([range_ stopAtIndex:kExisitingIndex position:&thePosition], kStrings[kExisitingIndex], nil);
STAssertEquals(thePosition, kExistingPosition, nil);
STAssertNotEqualObjects([range_ stopAtIndex:kStringCount - 1 position:nil], kStrings[2], nil);
STAssertThrows([range_ stopAtIndex:kStringCount position:nil], nil);
}
- (void)testDescription {
// we expect a description of atleast a few chars
STAssertGreaterThan([[range_ description] length], (NSUInteger)10, nil);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMCalculatedRangeTest.m | Objective-C | bsd | 4,027 |
//
// GTMNSObject+KeyValueObserving.h
//
// Copyright 2009 Google Inc.
//
// 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.
//
//
// MAKVONotificationCenter.h
// MAKVONotificationCenter
//
// Created by Michael Ash on 10/15/08.
//
// This code is based on code by Michael Ash.
// Please see his excellent writeup at
// http://www.mikeash.com/?page=pyblog/key-value-observing-done-right.html
// You may also be interested in this writeup:
// http://www.dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage/
// and the discussion on cocoa-dev that is linked to at the end of it.
#import <Foundation/Foundation.h>
// If you read the articles above you will see that doing KVO correctly
// is actually pretty tricky, and that Apple's documentation may not be
// completely clear as to how things should be used. Use the methods below
// to make things a little easier instead of the stock addObserver,
// removeObserver methods.
// Selector should have the following signature:
// - (void)observeNotification:(GTMKeyValueChangeNotification *)notification
@interface NSObject (GTMKeyValueObservingAdditions)
// Use this instead of [NSObject addObserver:forKeyPath:options:context:]
- (void)gtm_addObserver:(id)observer
forKeyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options;
// Use this instead of [NSObject removeObserver:forKeyPath:]
- (void)gtm_removeObserver:(id)observer
forKeyPath:(NSString *)keyPath
selector:(SEL)selector;
@end
// This is the class that is sent to your notification selector as an
// argument.
@interface GTMKeyValueChangeNotification : NSObject <NSCopying> {
@private
NSString *keyPath_;
id object_;
id userInfo_;
NSDictionary *change_;
}
- (NSString *)keyPath;
- (id)object;
- (id)userInfo;
- (NSDictionary *)change;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSObject+KeyValueObserving.h | Objective-C | bsd | 2,450 |
//
// GTMNSString+HTMLTest.m
//
// Copyright 2005-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMNSString+HTML.h"
@interface GTMNSString_HTMLTest : GTMTestCase
@end
@implementation GTMNSString_HTMLTest
- (void)testStringByEscapingHTML {
unichar chars[] =
{ 34, 38, 39, 60, 62, 338, 339, 352, 353, 376, 710, 732,
8194, 8195, 8201, 8204, 8205, 8206, 8207, 8211, 8212, 8216, 8217, 8218,
8220, 8221, 8222, 8224, 8225, 8240, 8249, 8250, 8364, };
NSString *string1 = [NSString stringWithCharacters:chars
length:sizeof(chars) / sizeof(unichar)];
NSString *string2 =
@""&'<>ŒœŠšŸ"
"ˆ˜   ‌‍‎‏–"
"—‘’‚“”„†‡"
"‰‹›€";
STAssertEqualObjects([string1 gtm_stringByEscapingForHTML],
string2,
@"HTML escaping failed");
STAssertEqualObjects([@"<this & that>" gtm_stringByEscapingForHTML],
@"<this & that>",
@"HTML escaping failed");
NSString *string = [NSString stringWithUTF8String:"パン・&ド・カンパーニュ"];
NSString *escapeStr = [NSString stringWithUTF8String:"パン・&ド・カンパーニュ"];
STAssertEqualObjects([string gtm_stringByEscapingForHTML],
escapeStr,
@"HTML escaping failed");
string = [NSString stringWithUTF8String:"abcا1ب<تdef&"];
STAssertEqualObjects([string gtm_stringByEscapingForHTML],
[NSString stringWithUTF8String:"abcا1ب<تdef&"],
@"HTML escaping failed");
// test empty string
STAssertEqualObjects([@"" gtm_stringByEscapingForHTML], @"", nil);
} // testStringByEscapingHTML
- (void)testStringByEscapingAsciiHTML {
unichar chars[] =
{ 34, 38, 39, 60, 62, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185,
186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200,
201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 338, 339, 352, 353, 376,
402, 710, 732, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924,
925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 945, 946, 947,
948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962,
963, 964, 965, 966, 967, 968, 969, 977, 978, 982, 8194, 8195, 8201, 8204,
8205, 8206, 8207, 8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8224, 8225,
8226, 8230, 8240, 8242, 8243, 8249, 8250, 8254, 8260, 8364, 8472, 8465, 8476,
8482, 8501, 8592, 8593, 8594, 8595, 8596, 8629, 8656, 8657, 8658, 8659, 8660,
8704, 8706, 8707, 8709, 8711, 8712, 8713, 8715, 8719, 8721, 8722, 8727, 8730,
8733, 8734, 8736, 8743, 8744, 8745, 8746, 8747, 8756, 8764, 8773, 8776, 8800,
8801, 8804, 8805, 8834, 8835, 8836, 8838, 8839, 8853, 8855, 8869, 8901, 8968,
8969, 8970, 8971, 9001, 9002, 9674, 9824, 9827, 9829, 9830 };
NSString *string1 = [NSString stringWithCharacters:chars
length:sizeof(chars) / sizeof(unichar)];
NSString *string2 =
@""&'<> ¡¢£¤¥"
"¦§¨©ª«¬­®¯°"
"±²³´µ¶·¸¹"
"º»¼½¾¿ÀÁ"
"ÂÃÄÅÆÇÈÉ"
"ÊËÌÍÎÏÐÑÒ"
"ÓÔÕÖרÙÚ"
"ÛÜÝÞßàáâã"
"äåæçèéêëì"
"íîïðñòóôõ"
"ö÷øùúûüýþ"
"ÿŒœŠšŸƒˆ˜"
"ΑΒΓΔΕΖΗΘΙ"
"ΚΛΜΝΞΟΠΡΣΤ"
"ΥΦΧΨΩαβγδ"
"εζηθικλμνξ"
"οπρςστυφχψ"
"ωϑϒϖ   ‌‍"
"‎‏–—‘’‚“”"
"„†‡•…‰′″"
"‹›‾⁄€℘ℑℜ™"
"ℵ←↑→↓↔↵⇐⇑⇒"
"⇓⇔∀∂∃∅∇∈∉∋"
"∏∑−∗√∝∞∠∧∨"
"∩∪∫∴∼≅≈≠≡≤≥"
"⊂⊃⊄⊆⊇⊕⊗⊥⋅⌈"
"⌉⌊⌋⟨⟩◊♠♣♥"
"♦";
STAssertEqualObjects([string1 gtm_stringByEscapingForAsciiHTML],
string2,
@"HTML escaping failed");
STAssertEqualObjects([@"<this & that>" gtm_stringByEscapingForAsciiHTML],
@"<this & that>",
@"HTML escaping failed");
NSString *string = [NSString stringWithUTF8String:"パン・ド・カンパーニュ"];
STAssertEqualObjects([string gtm_stringByEscapingForAsciiHTML],
@"パン・ド・カ"
"ンパーニュ",
@"HTML escaping failed");
// Mix in some right - to left
string = [NSString stringWithUTF8String:"abcا1ب<تdef&"];
STAssertEqualObjects([string gtm_stringByEscapingForAsciiHTML],
@"abcا1ب<تdef&",
@"HTML escaping failed");
} // stringByEscapingAsciiHTML
- (void)testStringByUnescapingHTML {
NSString *string1 =
@""&'<> ¡¢£¤¥"
"¦§¨©ª«¬­®¯°"
"±²³´µ¶·¸¹"
"º»¼½¾¿ÀÁ"
"ÂÃÄÅÆÇÈÉ"
"ÊËÌÍÎÏÐÑÒ"
"ÓÔÕÖרÙÚ"
"ÛÜÝÞßàáâã"
"äåæçèéêëì"
"íîïðñòóôõ"
"ö÷øùúûüýþ"
"ÿŒœŠšŸƒˆ˜"
"ΑΒΓΔΕΖΗΘΙ"
"ΚΛΜΝΞΟΠΡΣΤ"
"ΥΦΧΨΩαβγδ"
"εζηθικλμνξ"
"οπρςστυφχψ"
"ωϑϒϖ   ‌‍"
"‎‏–—‘’‚“”"
"„†‡•…‰′″"
"‹›‾⁄€℘ℑℜ™"
"ℵ←↑→↓↔↵⇐⇑⇒"
"⇓⇔∀∂∃∅∇∈∉∋"
"∏∑−∗√∝∞∠∧∨"
"∩∪∫∴∼≅≈≠≡≤≥"
"⊂⊃⊄⊆⊇⊕⊗⊥⋅⌈"
"⌉⌊⌋⟨⟩◊♠♣♥"
"♦";
unichar chars[] =
{ 34, 38, 39, 60, 62, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185,
186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200,
201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 338, 339, 352, 353, 376,
402, 710, 732, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924,
925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 945, 946, 947,
948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962,
963, 964, 965, 966, 967, 968, 969, 977, 978, 982, 8194, 8195, 8201, 8204,
8205, 8206, 8207, 8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8224, 8225,
8226, 8230, 8240, 8242, 8243, 8249, 8250, 8254, 8260, 8364, 8472, 8465, 8476,
8482, 8501, 8592, 8593, 8594, 8595, 8596, 8629, 8656, 8657, 8658, 8659, 8660,
8704, 8706, 8707, 8709, 8711, 8712, 8713, 8715, 8719, 8721, 8722, 8727, 8730,
8733, 8734, 8736, 8743, 8744, 8745, 8746, 8747, 8756, 8764, 8773, 8776, 8800,
8801, 8804, 8805, 8834, 8835, 8836, 8838, 8839, 8853, 8855, 8869, 8901, 8968,
8969, 8970, 8971, 9001, 9002, 9674, 9824, 9827, 9829, 9830 };
NSString *string2 = [NSString stringWithCharacters:chars
length:sizeof(chars) / sizeof(unichar)];
STAssertEqualObjects([string1 gtm_stringByUnescapingFromHTML],
string2,
@"HTML unescaping failed");
STAssertEqualObjects([@"ABC" gtm_stringByUnescapingFromHTML],
@"ABC", @"HTML unescaping failed");
STAssertEqualObjects([@"" gtm_stringByUnescapingFromHTML],
@"", @"HTML unescaping failed");
STAssertEqualObjects([@"A&Bang;C" gtm_stringByUnescapingFromHTML],
@"A&Bang;C", @"HTML unescaping failed");
STAssertEqualObjects([@"A&Bang;C" gtm_stringByUnescapingFromHTML],
@"A&Bang;C", @"HTML unescaping failed");
STAssertEqualObjects([@"A&Bang;C" gtm_stringByUnescapingFromHTML],
@"A&Bang;C", @"HTML unescaping failed");
STAssertEqualObjects([@"AA;" gtm_stringByUnescapingFromHTML],
@"AA;", @"HTML unescaping failed");
STAssertEqualObjects([@"&" gtm_stringByUnescapingFromHTML],
@"&", @"HTML unescaping failed");
STAssertEqualObjects([@"&;" gtm_stringByUnescapingFromHTML],
@"&;", @"HTML unescaping failed");
STAssertEqualObjects([@"&x;" gtm_stringByUnescapingFromHTML],
@"&x;", @"HTML unescaping failed");
STAssertEqualObjects([@"&X;" gtm_stringByUnescapingFromHTML],
@"&X;", @"HTML unescaping failed");
STAssertEqualObjects([@";" gtm_stringByUnescapingFromHTML],
@";", @"HTML unescaping failed");
STAssertEqualObjects([@"<this & that>" gtm_stringByUnescapingFromHTML],
@"<this & that>", @"HTML unescaping failed");
} // testStringByUnescapingHTML
- (void)testStringRoundtrippingEscapedHTML {
NSString *string = [NSString stringWithUTF8String:"This test ©™®๒०᠐٧"];
STAssertEqualObjects(string,
[[string gtm_stringByEscapingForHTML] gtm_stringByUnescapingFromHTML],
@"HTML Roundtripping failed");
string = [NSString stringWithUTF8String:"This test ©™®๒०᠐٧"];
STAssertEqualObjects(string,
[[string gtm_stringByEscapingForAsciiHTML] gtm_stringByUnescapingFromHTML],
@"HTML Roundtripping failed");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+HTMLTest.m | Objective-C | bsd | 12,888 |
//
// GTMNSObject+KeyValueObserving.h
//
// Copyright 2009 Google Inc.
//
// 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.
//
//
// MAKVONotificationCenter.m
// MAKVONotificationCenter
//
// Created by Michael Ash on 10/15/08.
//
// This code is based on code by Michael Ash.
// See comment in header.
#import "GTMNSObject+KeyValueObserving.h"
#import <libkern/OSAtomic.h>
#import "GTMDefines.h"
#import "GTMDebugSelectorValidation.h"
#import "GTMObjC2Runtime.h"
// A singleton that works as a dispatch center for KVO
// -[NSObject observeValueForKeyPath:ofObject:change:context:] and turns them
// into selector dispatches. It stores a collection of
// GTMKeyValueObservingHelpers, and keys them via the key generated by
// -dictionaryKeyForObserver:ofObject:forKeyPath:selector.
@interface GTMKeyValueObservingCenter : NSObject {
@private
NSMutableDictionary *observerHelpers_;
}
+ (id)defaultCenter;
- (void)addObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options;
- (void)removeObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector;
- (id)dictionaryKeyForObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector;
@end
@interface GTMKeyValueObservingHelper : NSObject {
@private
__weak id observer_;
SEL selector_;
id userInfo_;
id target_;
NSString* keyPath_;
}
- (id)initWithObserver:(id)observer
object:(id)target
keyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options;
- (void)deregister;
@end
@interface GTMKeyValueChangeNotification ()
- (id)initWithKeyPath:(NSString *)keyPath ofObject:(id)object
userInfo:(id)userInfo change:(NSDictionary *)change;
@end
@implementation GTMKeyValueObservingHelper
// For info how and why we use these statics:
// http://lists.apple.com/archives/cocoa-dev/2006/Jul/msg01038.html
static char GTMKeyValueObservingHelperContextData;
static char* GTMKeyValueObservingHelperContext
= >MKeyValueObservingHelperContextData;
- (id)initWithObserver:(id)observer
object:(id)target
keyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options {
if((self = [super init])) {
observer_ = observer;
selector_ = selector;
userInfo_ = [userInfo retain];
target_ = target;
keyPath_ = [keyPath retain];
[target addObserver:self
forKeyPath:keyPath
options:options
context:GTMKeyValueObservingHelperContext];
}
return self;
}
- (void)dealloc {
[userInfo_ release];
[keyPath_ release];
[super dealloc];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if(context == GTMKeyValueObservingHelperContext) {
GTMKeyValueChangeNotification *notification
= [[GTMKeyValueChangeNotification alloc] initWithKeyPath:keyPath
ofObject:object
userInfo:userInfo_
change:change];
[observer_ performSelector:selector_ withObject:notification];
[notification release];
} else {
// COV_NF_START
// There's no way this should ever be called.
// If it is, the call will go up to NSObject which will assert.
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
// COV_NF_END
}
}
- (void)deregister {
[target_ removeObserver:self forKeyPath:keyPath_];
}
@end
@implementation GTMKeyValueObservingCenter
+ (id)defaultCenter {
static GTMKeyValueObservingCenter *center = nil;
if(!center) {
// do a bit of clever atomic setting to make this thread safe
// if two threads try to set simultaneously, one will fail
// and the other will set things up so that the failing thread
// gets the shared center
GTMKeyValueObservingCenter *newCenter = [[self alloc] init];
if(!objc_atomicCompareAndSwapGlobalBarrier(nil,
newCenter,
(void *)¢er)) {
[newCenter release]; // COV_NF_LINE no guarantee we'll hit this line
}
}
return center;
}
- (id)init {
if((self = [super init])) {
observerHelpers_ = [[NSMutableDictionary alloc] init];
}
return self;
}
// COV_NF_START
// Singletons don't get deallocated
- (void)dealloc {
[observerHelpers_ release];
[super dealloc];
}
// COV_NF_END
- (id)dictionaryKeyForObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector {
NSString *key = [NSString stringWithFormat:@"%p:%p:%@:%p",
observer, target, keyPath, selector];
return key;
}
- (void)addObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options {
GTMKeyValueObservingHelper *helper
= [[GTMKeyValueObservingHelper alloc] initWithObserver:observer
object:target
keyPath:keyPath
selector:selector
userInfo:userInfo
options:options];
id key = [self dictionaryKeyForObserver:observer
ofObject:target
forKeyPath:keyPath
selector:selector];
@synchronized(self) {
#if DEBUG
GTMKeyValueObservingHelper *oldHelper = [observerHelpers_ objectForKey:key];
if (oldHelper) {
_GTMDevLog(@"%@ already observing %@ forKeyPath %@",
observer, target, keyPath);
}
#endif // DEBUG
[observerHelpers_ setObject:helper forKey:key];
}
[helper release];
}
- (void)removeObserver:(id)observer
ofObject:(id)target
forKeyPath:(NSString *)keyPath
selector:(SEL)selector {
id key = [self dictionaryKeyForObserver:observer
ofObject:target
forKeyPath:keyPath
selector:selector];
GTMKeyValueObservingHelper *helper = nil;
@synchronized(self) {
helper = [[observerHelpers_ objectForKey:key] retain];
#if DEBUG
if (!helper) {
_GTMDevLog(@"%@ was not observing %@ with keypath %@",
observer, target, keyPath);
}
#endif // DEBUG
[observerHelpers_ removeObjectForKey:key];
}
[helper deregister];
[helper release];
}
@end
@implementation NSObject (GTMKeyValueObservingAdditions)
- (void)gtm_addObserver:(id)observer
forKeyPath:(NSString *)keyPath
selector:(SEL)selector
userInfo:(id)userInfo
options:(NSKeyValueObservingOptions)options {
_GTMDevAssert(observer && [keyPath length] && selector,
@"Missing observer, keyPath, or selector");
GTMKeyValueObservingCenter *center
= [GTMKeyValueObservingCenter defaultCenter];
GTMAssertSelectorNilOrImplementedWithArguments(observer,
selector,
@encode(GTMKeyValueChangeNotification *),
NULL);
[center addObserver:observer
ofObject:self
forKeyPath:keyPath
selector:selector
userInfo:userInfo
options:options];
}
- (void)gtm_removeObserver:(id)observer
forKeyPath:(NSString *)keyPath
selector:(SEL)selector {
_GTMDevAssert(observer && [keyPath length] && selector,
@"Missing observer, keyPath, or selector");
GTMKeyValueObservingCenter *center
= [GTMKeyValueObservingCenter defaultCenter];
GTMAssertSelectorNilOrImplementedWithArguments(observer,
selector,
@encode(GTMKeyValueChangeNotification *),
NULL);
[center removeObserver:observer
ofObject:self
forKeyPath:keyPath
selector:selector];
}
@end
@implementation GTMKeyValueChangeNotification
- (id)initWithKeyPath:(NSString *)keyPath ofObject:(id)object
userInfo:(id)userInfo change:(NSDictionary *)change {
if ((self = [super init])) {
keyPath_ = [keyPath copy];
object_ = [object retain];
userInfo_ = [userInfo retain];
change_ = [change retain];
}
return self;
}
- (void)dealloc {
[keyPath_ release];
[object_ release];
[userInfo_ release];
[change_ release];
[super dealloc];
}
- (id)copyWithZone:(NSZone *)zone {
return [[[self class] allocWithZone:zone] initWithKeyPath:keyPath_
ofObject:object_
userInfo:userInfo_
change:change_];
}
- (BOOL)isEqual:(id)object {
return ([keyPath_ isEqualToString:[object keyPath]]
&& [object_ isEqual:[object object]]
&& [userInfo_ isEqual:[object userInfo]]
&& [change_ isEqual:[object change]]);
}
- (NSUInteger)hash {
return [keyPath_ hash] + [object_ hash] + [userInfo_ hash] + [change_ hash];
}
- (NSString *)keyPath {
return keyPath_;
}
- (id)object {
return object_;
}
- (id)userInfo {
return userInfo_;
}
- (NSDictionary *)change {
return change_;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSObject+KeyValueObserving.m | Objective-C | bsd | 11,022 |
//
// GTMHTTPServer.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
// Based a little on HTTPServer, part of the CocoaHTTPServer sample code
// http://developer.apple.com/samplecode/CocoaHTTPServer/index.html
//
#import <netinet/in.h>
#import <sys/socket.h>
#import <unistd.h>
#define GTMHTTPSERVER_DEFINE_GLOBALS
#import "GTMHTTPServer.h"
#import "GTMDebugSelectorValidation.h"
#import "GTMGarbageCollection.h"
#import "GTMDefines.h"
@interface GTMHTTPServer (PrivateMethods)
- (void)acceptedConnectionNotification:(NSNotification *)notification;
- (NSMutableDictionary *)newConnectionWithFileHandle:(NSFileHandle *)fileHandle;
- (void)dataAvailableNotification:(NSNotification *)notification;
- (NSMutableDictionary *)lookupConnection:(NSFileHandle *)fileHandle;
- (void)closeConnection:(NSMutableDictionary *)connDict;
- (void)sendResponseOnNewThread:(NSMutableDictionary *)connDict;
- (void)sentResponse:(NSMutableDictionary *)connDict;
@end
// keys for our connection dictionaries
static NSString *kFileHandle = @"FileHandle";
static NSString *kRequest = @"Request";
static NSString *kResponse = @"Response";
@interface GTMHTTPRequestMessage (PrivateHelpers)
- (BOOL)isHeaderComplete;
- (BOOL)appendData:(NSData *)data;
- (NSString *)headerFieldValueForKey:(NSString *)key;
- (UInt32)contentLength;
- (void)setBody:(NSData *)body;
@end
@interface GTMHTTPResponseMessage (PrivateMethods)
- (id)initWithBody:(NSData *)body
contentType:(NSString *)contentType
statusCode:(int)statusCode;
- (NSData*)serializedData;
@end
@implementation GTMHTTPServer
- (id)init {
return [self initWithDelegate:nil];
}
- (id)initWithDelegate:(id)delegate {
self = [super init];
if (self) {
if (!delegate) {
_GTMDevLog(@"missing delegate");
[self release];
return nil;
}
delegate_ = delegate;
GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(delegate_,
@selector(httpServer:handleRequest:),
// return type
@encode(GTMHTTPResponseMessage *),
// args
@encode(GTMHTTPServer *),
@encode(GTMHTTPRequestMessage *),
NULL);
localhostOnly_ = YES;
connections_ = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
[self stop];
[super dealloc];
}
- (void)finalize {
[self stop];
[super finalize];
}
- (id)delegate {
return delegate_;
}
- (uint16_t)port {
return port_;
}
- (void)setPort:(uint16_t)port {
port_ = port;
}
- (BOOL)localhostOnly {
return localhostOnly_;
}
- (void)setLocalhostOnly:(BOOL)yesno {
localhostOnly_ = yesno;
}
- (BOOL)start:(NSError **)error {
_GTMDevAssert(listenHandle_ == nil,
@"start called when we already have a listenHandle_");
if (error) *error = NULL;
NSInteger startFailureCode = 0;
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd <= 0) {
// COV_NF_START - we'd need to use up *all* sockets to test this?
startFailureCode = kGTMHTTPServerSocketCreateFailedError;
goto startFailed;
// COV_NF_END
}
// enable address reuse quicker after we are done w/ our socket
int yes = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
(void *)&yes, (socklen_t)sizeof(yes)) != 0) {
_GTMDevLog(@"failed to mark the socket as reusable"); // COV_NF_LINE
}
// bind
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port_);
if (localhostOnly_) {
addr.sin_addr.s_addr = htonl(0x7F000001);
} else {
// COV_NF_START - testing this could cause a leopard firewall prompt during tests.
addr.sin_addr.s_addr = htonl(INADDR_ANY);
// COV_NF_END
}
if (bind(fd, (struct sockaddr*)(&addr), (socklen_t)sizeof(addr)) != 0) {
startFailureCode = kGTMHTTPServerBindFailedError;
goto startFailed;
}
// collect the port back out
if (port_ == 0) {
socklen_t len = (socklen_t)sizeof(addr);
if (getsockname(fd, (struct sockaddr*)(&addr), &len) == 0) {
port_ = ntohs(addr.sin_port);
}
}
// tell it to listen for connections
if (listen(fd, 5) != 0) {
// COV_NF_START
startFailureCode = kGTMHTTPServerListenFailedError;
goto startFailed;
// COV_NF_END
}
// now use a filehandle to accept connections
listenHandle_ =
[[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES];
if (listenHandle_ == nil) {
// COV_NF_START - we'd need to run out of memory to test this?
startFailureCode = kGTMHTTPServerHandleCreateFailedError;
goto startFailed;
// COV_NF_END
}
// setup notifications for connects
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(acceptedConnectionNotification:)
name:NSFileHandleConnectionAcceptedNotification
object:listenHandle_];
[listenHandle_ acceptConnectionInBackgroundAndNotify];
// TODO: maybe hit the delegate incase it wants to register w/ NSNetService,
// or just know we're up and running?
return YES;
startFailed:
if (error) {
*error = [[[NSError alloc] initWithDomain:kGTMHTTPServerErrorDomain
code:startFailureCode
userInfo:nil] autorelease];
}
if (fd > 0) {
close(fd);
}
return NO;
}
- (void)stop {
if (listenHandle_) {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self
name:NSFileHandleConnectionAcceptedNotification
object:listenHandle_];
[listenHandle_ release];
listenHandle_ = nil;
// TODO: maybe hit the delegate in case it wants to unregister w/
// NSNetService, or just know we've stopped running?
}
[connections_ removeAllObjects];
}
- (NSUInteger)activeRequestCount {
return [connections_ count];
}
- (NSString *)description {
NSString *result =
[NSString stringWithFormat:@"%@<%p>{ port=%d localHostOnly=%@ status=%@ }",
[self class], self, port_, (localhostOnly_ ? @"YES" : @"NO"),
(listenHandle_ != nil ? @"Started" : @"Stopped") ];
return result;
}
@end
@implementation GTMHTTPServer (PrivateMethods)
- (void)acceptedConnectionNotification:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
NSFileHandle *newConnection =
[userInfo objectForKey:NSFileHandleNotificationFileHandleItem];
_GTMDevAssert(newConnection != nil,
@"failed to get the connection in the notification: %@",
notification);
// make sure we accept more...
[listenHandle_ acceptConnectionInBackgroundAndNotify];
// TODO: could let the delegate look at the address, before we start working
// on it.
NSMutableDictionary *connDict =
[self newConnectionWithFileHandle:newConnection];
[connections_ addObject:connDict];
}
- (NSMutableDictionary *)newConnectionWithFileHandle:(NSFileHandle *)fileHandle {
NSMutableDictionary *result = [NSMutableDictionary dictionary];
[result setObject:fileHandle forKey:kFileHandle];
GTMHTTPRequestMessage *request =
[[[GTMHTTPRequestMessage alloc] init] autorelease];
[result setObject:request forKey:kRequest];
// setup for data notifications
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(dataAvailableNotification:)
name:NSFileHandleReadCompletionNotification
object:fileHandle];
[fileHandle readInBackgroundAndNotify];
return result;
}
- (void)dataAvailableNotification:(NSNotification *)notification {
NSFileHandle *connectionHandle = [notification object];
NSMutableDictionary *connDict = [self lookupConnection:connectionHandle];
if (connDict == nil) return; // we are no longer tracking this one
NSDictionary *userInfo = [notification userInfo];
NSData *readData = [userInfo objectForKey:NSFileHandleNotificationDataItem];
if ([readData length] == 0) {
// remote side closed
[self closeConnection:connDict];
return;
}
// Like Apple's sample, we just keep adding data until we get a full header
// and any referenced body.
GTMHTTPRequestMessage *request = [connDict objectForKey:kRequest];
[request appendData:readData];
// Is the header complete yet?
if (![request isHeaderComplete]) {
// more data...
[connectionHandle readInBackgroundAndNotify];
return;
}
// Do we have all the body?
UInt32 contentLength = [request contentLength];
NSData *body = [request body];
NSUInteger bodyLength = [body length];
if (contentLength > bodyLength) {
// need more data...
[connectionHandle readInBackgroundAndNotify];
return;
}
if (contentLength < bodyLength) {
// We got extra (probably someone trying to pipeline on us), trim
// and let the extra data go...
NSData *newBody = [NSData dataWithBytes:[body bytes]
length:contentLength];
[request setBody:newBody];
_GTMDevLog(@"Got %lu extra bytes on http request, ignoring them",
(unsigned long)(bodyLength - contentLength));
}
GTMHTTPResponseMessage *response = nil;
@try {
// Off to the delegate
response = [delegate_ httpServer:self handleRequest:request];
} @catch (NSException *e) {
_GTMDevLog(@"Exception trying to handle http request: %@", e);
}
if (!response) {
[self closeConnection:connDict];
return;
}
// We don't support connection reuse, so we add (force) the header to close
// every connection.
[response setValue:@"close" forHeaderField:@"Connection"];
// spawn thread to send reply (since we do a blocking send)
[connDict setObject:response forKey:kResponse];
[NSThread detachNewThreadSelector:@selector(sendResponseOnNewThread:)
toTarget:self
withObject:connDict];
}
- (NSMutableDictionary *)lookupConnection:(NSFileHandle *)fileHandle {
NSUInteger max = [connections_ count];
for (NSUInteger x = 0; x < max; ++x) {
NSMutableDictionary *connDict = [connections_ objectAtIndex:x];
if (fileHandle == [connDict objectForKey:kFileHandle]) {
return connDict;
}
}
return nil;
}
- (void)closeConnection:(NSMutableDictionary *)connDict {
// remove the notification
NSFileHandle *connectionHandle = [connDict objectForKey:kFileHandle];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self
name:NSFileHandleReadCompletionNotification
object:connectionHandle];
// remove it from the list
[connections_ removeObject:connDict];
}
- (void)sendResponseOnNewThread:(NSMutableDictionary *)connDict {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@try {
GTMHTTPResponseMessage *response = [connDict objectForKey:kResponse];
NSFileHandle *connectionHandle = [connDict objectForKey:kFileHandle];
NSData *serialized = [response serializedData];
[connectionHandle writeData:serialized];
} @catch (NSException *e) {
// TODO: let the delegate know about the exception (but do it on the main
// thread)
_GTMDevLog(@"exception while sending reply: %@", e);
}
// back to the main thread to close things down
[self performSelectorOnMainThread:@selector(sentResponse:)
withObject:connDict
waitUntilDone:NO];
[pool release];
}
- (void)sentResponse:(NSMutableDictionary *)connDict {
// make sure we're still tracking this connection (in case server was stopped)
NSFileHandle *connection = [connDict objectForKey:kFileHandle];
NSMutableDictionary *connDict2 = [self lookupConnection:connection];
if (connDict != connDict2) return;
// TODO: message the delegate that it was sent
// close it down
[self closeConnection:connDict];
}
@end
#pragma mark -
@implementation GTMHTTPRequestMessage
- (id)init {
self = [super init];
if (self) {
message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, YES);
}
return self;
}
- (void)dealloc {
CFRelease(message_);
[super dealloc];
}
- (NSString *)version {
return [GTMNSMakeCollectable(CFHTTPMessageCopyVersion(message_)) autorelease];
}
- (NSURL *)URL {
return [GTMNSMakeCollectable(CFHTTPMessageCopyRequestURL(message_)) autorelease];
}
- (NSString *)method {
return [GTMNSMakeCollectable(CFHTTPMessageCopyRequestMethod(message_)) autorelease];
}
- (NSData *)body {
return [GTMNSMakeCollectable(CFHTTPMessageCopyBody(message_)) autorelease];
}
- (NSDictionary *)allHeaderFieldValues {
return GTMNSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message_));
}
- (NSString *)description {
CFStringRef desc = CFCopyDescription(message_);
NSString *result =
[NSString stringWithFormat:@"%@<%p>{ message=%@ }", [self class], self, desc];
CFRelease(desc);
return result;
}
@end
@implementation GTMHTTPRequestMessage (PrivateHelpers)
- (BOOL)isHeaderComplete {
return CFHTTPMessageIsHeaderComplete(message_) ? YES : NO;
}
- (BOOL)appendData:(NSData *)data {
return CFHTTPMessageAppendBytes(message_,
[data bytes], [data length]) ? YES : NO;
}
- (NSString *)headerFieldValueForKey:(NSString *)key {
CFStringRef value = NULL;
if (key) {
value = CFHTTPMessageCopyHeaderFieldValue(message_, (CFStringRef)key);
}
return [GTMNSMakeCollectable(value) autorelease];
}
- (UInt32)contentLength {
return [[self headerFieldValueForKey:@"Content-Length"] intValue];
}
- (void)setBody:(NSData *)body {
if (!body) {
body = [NSData data]; // COV_NF_LINE - can only happen in we fail to make the new data object
}
CFHTTPMessageSetBody(message_, (CFDataRef)body);
}
@end
#pragma mark -
@implementation GTMHTTPResponseMessage
- (id)init {
return [self initWithBody:nil contentType:nil statusCode:0];
}
- (void)dealloc {
if (message_) {
CFRelease(message_);
}
[super dealloc];
}
+ (id)responseWithHTMLString:(NSString *)htmlString {
return [self responseWithBody:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
contentType:@"text/html; charset=UTF-8"
statusCode:200];
}
+ (id)responseWithBody:(NSData *)body
contentType:(NSString *)contentType
statusCode:(int)statusCode {
return [[[[self class] alloc] initWithBody:body
contentType:contentType
statusCode:statusCode] autorelease];
}
+ (id)emptyResponseWithCode:(int)statusCode {
return [[[[self class] alloc] initWithBody:nil
contentType:nil
statusCode:statusCode] autorelease];
}
- (void)setValue:(NSString*)value forHeaderField:(NSString*)headerField {
if ([headerField length] == 0) return;
if (value == nil) {
value = @"";
}
CFHTTPMessageSetHeaderFieldValue(message_,
(CFStringRef)headerField, (CFStringRef)value);
}
- (NSString *)description {
CFStringRef desc = CFCopyDescription(message_);
NSString *result =
[NSString stringWithFormat:@"%@<%p>{ message=%@ }", [self class], self, desc];
CFRelease(desc);
return result;
}
@end
@implementation GTMHTTPResponseMessage (PrivateMethods)
- (id)initWithBody:(NSData *)body
contentType:(NSString *)contentType
statusCode:(int)statusCode {
self = [super init];
if (self) {
if ((statusCode < 100) || (statusCode > 599)) {
[self release];
return nil;
}
message_ = CFHTTPMessageCreateResponse(kCFAllocatorDefault,
statusCode, NULL,
kCFHTTPVersion1_0);
if (!message_) {
// COV_NF_START
[self release];
return nil;
// COV_NF_END
}
NSUInteger bodyLength = 0;
if (body) {
bodyLength = [body length];
CFHTTPMessageSetBody(message_, (CFDataRef)body);
}
if ([contentType length] == 0) {
contentType = @"text/html";
}
NSString *bodyLenStr =
[NSString stringWithFormat:@"%lu", (unsigned long)bodyLength];
[self setValue:bodyLenStr forHeaderField:@"Content-Length"];
[self setValue:contentType forHeaderField:@"Content-Type"];
}
return self;
}
- (NSData *)serializedData {
return [GTMNSMakeCollectable(CFHTTPMessageCopySerializedMessage(message_)) autorelease];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPServer.m | Objective-C | bsd | 17,570 |
//
// GTMLogger+ASL.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMLogger+ASL.h"
#import "GTMDefines.h"
@implementation GTMLogger (GTMLoggerASLAdditions)
+ (id)standardLoggerWithASL {
id me = [self standardLogger];
[me setWriter:[[[GTMLogASLWriter alloc] init] autorelease]];
[me setFormatter:[[[GTMLogBasicFormatter alloc] init] autorelease]];
return me;
}
@end
@implementation GTMLogASLWriter
+ (id)aslWriter {
return [[[self alloc] init] autorelease];
}
- (id)init {
return [self initWithClientClass:nil];
}
- (id)initWithClientClass:(Class)clientClass {
if ((self = [super init])) {
aslClientClass_ = clientClass;
if (aslClientClass_ == nil) {
aslClientClass_ = [GTMLoggerASLClient class];
}
}
return self;
}
- (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level {
static NSString *const kASLClientKey = @"GTMLoggerASLClientKey";
// Lookup the ASL client in the thread-local storage dictionary
NSMutableDictionary *tls = [[NSThread currentThread] threadDictionary];
GTMLoggerASLClient *client = [tls objectForKey:kASLClientKey];
// If the ASL client wasn't found (e.g., the first call from this thread),
// then create it and store it in the thread-local storage dictionary
if (client == nil) {
client = [[[aslClientClass_ alloc] init] autorelease];
[tls setObject:client forKey:kASLClientKey];
}
// Map the GTMLoggerLevel level to an ASL level.
int aslLevel = ASL_LEVEL_INFO;
switch (level) {
case kGTMLoggerLevelUnknown:
case kGTMLoggerLevelDebug:
case kGTMLoggerLevelInfo:
aslLevel = ASL_LEVEL_NOTICE;
break;
case kGTMLoggerLevelError:
aslLevel = ASL_LEVEL_ERR;
break;
case kGTMLoggerLevelAssert:
aslLevel = ASL_LEVEL_ALERT;
break;
}
[client log:msg level:aslLevel];
}
@end // GTMLogASLWriter
@implementation GTMLoggerASLClient
- (id)init {
if ((self = [super init])) {
client_ = asl_open(NULL, NULL, 0);
if (client_ == nil) {
// COV_NF_START - no real way to test this
[self release];
return nil;
// COV_NF_END
}
}
return self;
}
- (void)dealloc {
if (client_) asl_close(client_);
[super dealloc];
}
#if GTM_SUPPORT_GC
- (void)finalize {
if (client_) asl_close(client_);
[super finalize];
}
#endif
// We don't test this one line because we don't want to pollute actual system
// logs with test messages.
// COV_NF_START
- (void)log:(NSString *)msg level:(int)level {
asl_log(client_, NULL, level, "%s", [msg UTF8String]);
}
// COV_NF_END
@end // GTMLoggerASLClient
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMLogger+ASL.m | Objective-C | bsd | 3,171 |
//
// GTMSystemVersion.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// A class for getting information about what system we are running on
@interface GTMSystemVersion : NSObject
// Returns the current system version major.minor.bugFix
+ (void)getMajor:(SInt32*)major minor:(SInt32*)minor bugFix:(SInt32*)bugFix;
// Returns the build number of the OS. Useful when looking for bug fixes
// in new OSes which all have a set system version.
// eg 10.5.5's build number is 9F33. Easy way to check the build number
// is to choose "About this Mac" from the Apple menu and click on the version
// number.
+ (NSString*)build;
+ (BOOL)isBuildLessThan:(NSString*)build;
+ (BOOL)isBuildLessThanOrEqualTo:(NSString*)build;
+ (BOOL)isBuildGreaterThan:(NSString*)build;
+ (BOOL)isBuildGreaterThanOrEqualTo:(NSString*)build;
+ (BOOL)isBuildEqualTo:(NSString *)build;
#if GTM_MACOS_SDK
// Returns YES if running on 10.3, NO otherwise.
+ (BOOL)isPanther;
// Returns YES if running on 10.4, NO otherwise.
+ (BOOL)isTiger;
// Returns YES if running on 10.5, NO otherwise.
+ (BOOL)isLeopard;
// Returns YES if running on 10.6, NO otherwise.
+ (BOOL)isSnowLeopard;
// Returns a YES/NO if the system is 10.3 or better
+ (BOOL)isPantherOrGreater;
// Returns a YES/NO if the system is 10.4 or better
+ (BOOL)isTigerOrGreater;
// Returns a YES/NO if the system is 10.5 or better
+ (BOOL)isLeopardOrGreater;
// Returns a YES/NO if the system is 10.6 or better
+ (BOOL)isSnowLeopardOrGreater;
#endif // GTM_MACOS_SDK
// Returns one of the achitecture strings below. Note that this is the
// architecture that we are currently running as, not the hardware architecture.
+ (NSString *)runtimeArchitecture;
@end
// Architecture Strings
// TODO: Should probably break iPhone up into iPhone_ARM and iPhone_Simulator
// but haven't found a need yet.
GTM_EXTERN NSString *const kGTMArch_iPhone;
GTM_EXTERN NSString *const kGTMArch_ppc;
GTM_EXTERN NSString *const kGTMArch_ppc64;
GTM_EXTERN NSString *const kGTMArch_x86_64;
GTM_EXTERN NSString *const kGTMArch_i386;
// System Build Number constants
GTM_EXTERN NSString *const kGTMSystemBuild10_5_5;
GTM_EXTERN NSString *const kGTMSystemBuild10_6_0_WWDC;
GTM_EXTERN NSString *const kGTMSystemBuild10_6_0_10A190;
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMSystemVersion.h | Objective-C | bsd | 2,875 |
//
// GTMNSString+FindFolder.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
@interface NSString (GTMStringFindFolderAdditions)
// Create a path to a folder located with FindFolder
//
// Args:
// theFolderType: one of the folder types in Folders.h
// (kPreferencesFolderType, etc)
// theDomain: one of the domains in Folders.h (kLocalDomain, kUserDomain, etc)
// doCreate: create the folder if it does not already exist
//
// Returns:
// full path to folder, or nil if the folder doesn't exist or can't be created
//
+ (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
inDomain:(short)theDomain
doCreate:(BOOL)doCreate;
// Create a path to a folder inside a folder located with FindFolder
//
// Args:
// theFolderType: one of the folder types in Folders.h
// (kPreferencesFolderType, etc)
// subfolderName: name of directory inside the Apple folder to be located or created
// theDomain: one of the domains in Folders.h (kLocalDomain, kUserDomain, etc)
// doCreate: create the folder if it does not already exist
//
// Returns:
// full path to subdirectory, or nil if the folder doesn't exist or can't be created
//
+ (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
subfolderName:(NSString *)subfolderName
inDomain:(short)theDomain
doCreate:(BOOL)doCreate;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+FindFolder.h | Objective-C | bsd | 2,110 |
//
// GTMSystemVersion.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMSystemVersion.h"
#import "GTMGarbageCollection.h"
#if GTM_MACOS_SDK
#import <CoreServices/CoreServices.h>
#endif
static SInt32 sGTMSystemVersionMajor = 0;
static SInt32 sGTMSystemVersionMinor = 0;
static SInt32 sGTMSystemVersionBugFix = 0;
static NSString *sBuild = nil;
NSString *const kGTMArch_iPhone = @"iPhone";
NSString *const kGTMArch_ppc = @"ppc";
NSString *const kGTMArch_ppc64 = @"ppc64";
NSString *const kGTMArch_x86_64 = @"x86_64";
NSString *const kGTMArch_i386 = @"i386";
static NSString *const kSystemVersionPlistPath = @"/System/Library/CoreServices/SystemVersion.plist";
NSString *const kGTMSystemBuild10_5_5 = @"9F33";
NSString *const kGTMSystemBuild10_6_0_WWDC = @"10A96";
NSString *const kGTMSystemBuild10_6_0_10A190 = @"10A190";
@implementation GTMSystemVersion
+ (void)initialize {
if (self == [GTMSystemVersion class]) {
// Gestalt is the recommended way of getting the OS version (despite a
// comment to the contrary in the 10.4 headers and docs; see
// <http://lists.apple.com/archives/carbon-dev/2007/Aug/msg00089.html>).
// The iPhone doesn't have Gestalt though, so use the plist there.
#if GTM_MACOS_SDK
require_noerr(Gestalt(gestaltSystemVersionMajor, &sGTMSystemVersionMajor), failedGestalt);
require_noerr(Gestalt(gestaltSystemVersionMinor, &sGTMSystemVersionMinor), failedGestalt);
require_noerr(Gestalt(gestaltSystemVersionBugFix, &sGTMSystemVersionBugFix), failedGestalt);
return;
failedGestalt:
;
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_3
// gestaltSystemVersionMajor et al are only on 10.4 and above, so they
// could fail when running on 10.3.
SInt32 binaryCodedDec;
OSStatus err = err = Gestalt(gestaltSystemVersion, &binaryCodedDec);
_GTMDevAssert(!err, @"Unable to get version from Gestalt");
// Note that this code will return x.9.9 for any system rev parts that are
// greater than 9 (i.e., 10.10.10 will be 10.9.9). This shouldn't ever be a
// problem as the code above takes care of 10.4+.
SInt32 msb = (binaryCodedDec & 0x0000F000L) >> 12;
msb *= 10;
SInt32 lsb = (binaryCodedDec & 0x00000F00L) >> 8;
sGTMSystemVersionMajor = msb + lsb;
sGTMSystemVersionMinor = (binaryCodedDec & 0x000000F0L) >> 4;
sGTMSystemVersionBugFix = (binaryCodedDec & 0x0000000FL);
#endif // MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_3
#else // GTM_MACOS_SDK
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *systemVersionPlist
= [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath];
NSString *version = [systemVersionPlist objectForKey:@"ProductVersion"];
_GTMDevAssert(version, @"Unable to get version");
NSArray *versionInfo = [version componentsSeparatedByString:@"."];
NSUInteger length = [versionInfo count];
_GTMDevAssert(length > 1 && length < 4,
@"Unparseable version %@", version);
sGTMSystemVersionMajor = [[versionInfo objectAtIndex:0] intValue];
_GTMDevAssert(sGTMSystemVersionMajor != 0,
@"Unknown version for %@", version);
sGTMSystemVersionMinor = [[versionInfo objectAtIndex:1] intValue];
if (length == 3) {
sGTMSystemVersionBugFix = [[versionInfo objectAtIndex:2] intValue];
}
[pool release];
#endif // GTM_MACOS_SDK
}
}
+ (void)getMajor:(SInt32*)major minor:(SInt32*)minor bugFix:(SInt32*)bugFix {
if (major) {
*major = sGTMSystemVersionMajor;
}
if (minor) {
*minor = sGTMSystemVersionMinor;
}
if (bugFix) {
*bugFix = sGTMSystemVersionBugFix;
}
}
+ (NSString*)build {
@synchronized(self) {
// Not cached at initialization time because we don't expect "real"
// software to want this, and it costs a bit to get at startup.
// This will mainly be for unit test cases.
if (!sBuild) {
NSDictionary *systemVersionPlist
= [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath];
sBuild = [[systemVersionPlist objectForKey:@"ProductBuildVersion"] retain];
GTMNSMakeUncollectable(sBuild);
_GTMDevAssert(sBuild, @"Unable to get build version");
}
}
return sBuild;
}
+ (BOOL)isBuildLessThan:(NSString*)build {
NSComparisonResult result
= [[self build] compare:build
options:NSNumericSearch | NSCaseInsensitiveSearch];
return result == NSOrderedAscending;
}
+ (BOOL)isBuildLessThanOrEqualTo:(NSString*)build {
NSComparisonResult result
= [[self build] compare:build
options:NSNumericSearch | NSCaseInsensitiveSearch];
return result != NSOrderedDescending;
}
+ (BOOL)isBuildGreaterThan:(NSString*)build {
NSComparisonResult result
= [[self build] compare:build
options:NSNumericSearch | NSCaseInsensitiveSearch];
return result == NSOrderedDescending;
}
+ (BOOL)isBuildGreaterThanOrEqualTo:(NSString*)build {
NSComparisonResult result
= [[self build] compare:build
options:NSNumericSearch | NSCaseInsensitiveSearch];
return result != NSOrderedAscending;
}
+ (BOOL)isBuildEqualTo:(NSString *)build {
NSComparisonResult result
= [[self build] compare:build
options:NSNumericSearch | NSCaseInsensitiveSearch];
return result == NSOrderedSame;
}
#if GTM_MACOS_SDK
+ (BOOL)isPanther {
return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 3;
}
+ (BOOL)isTiger {
return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 4;
}
+ (BOOL)isLeopard {
return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 5;
}
+ (BOOL)isSnowLeopard {
return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 6;
}
+ (BOOL)isPantherOrGreater {
return (sGTMSystemVersionMajor > 10) ||
(sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 3);
}
+ (BOOL)isTigerOrGreater {
return (sGTMSystemVersionMajor > 10) ||
(sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 4);
}
+ (BOOL)isLeopardOrGreater {
return (sGTMSystemVersionMajor > 10) ||
(sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 5);
}
+ (BOOL)isSnowLeopardOrGreater {
return (sGTMSystemVersionMajor > 10) ||
(sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 6);
}
#endif // GTM_MACOS_SDK
+ (NSString *)runtimeArchitecture {
NSString *architecture = nil;
#if GTM_IPHONE_SDK
architecture = kGTMArch_iPhone;
#else // !GTM_IPHONE_SDK
// In reading arch(3) you'd thing this would work:
//
// const NXArchInfo *localInfo = NXGetLocalArchInfo();
// _GTMDevAssert(localInfo && localInfo->name, @"Couldn't get NXArchInfo");
// const NXArchInfo *genericInfo = NXGetArchInfoFromCpuType(localInfo->cputype, 0);
// _GTMDevAssert(genericInfo && genericInfo->name, @"Couldn't get generic NXArchInfo");
// extensions[0] = [NSString stringWithFormat:@".%s", genericInfo->name];
//
// but on 64bit it returns the same things as on 32bit, so...
#if __POWERPC__
#if __LP64__
architecture = kGTMArch_ppc64;
#else // !__LP64__
architecture = kGTMArch_ppc;
#endif // __LP64__
#else // !__POWERPC__
#if __LP64__
architecture = kGTMArch_x86_64;
#else // !__LP64__
architecture = kGTMArch_i386;
#endif // __LP64__
#endif // !__POWERPC__
#endif // GTM_IPHONE_SDK
return architecture;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMSystemVersion.m | Objective-C | bsd | 7,976 |
//
// GTMProgressMonitorInputStream.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
// The monitored input stream calls back into the monitor delegate
// with the number of bytes and total size
//
// - (void)inputStream:(GTMProgressMonitorInputStream *)stream
// hasDeliveredByteCount:(unsigned long long)numberOfBytesRead
// ofTotalByteCount:(unsigned long long)dataLength;
@interface GTMProgressMonitorInputStream : NSInputStream {
NSInputStream *inputStream_; // encapsulated stream that does the work
unsigned long long dataSize_; // size of data in the source
unsigned long long numBytesRead_; // bytes read from the input stream so far
__weak id monitorDelegate_; // WEAK, not retained
SEL monitorSelector_;
__weak id monitorSource_; // WEAK, not retained
}
// Length is passed to the progress callback; it may be zero if the progress
// callback can handle that (mainly meant so the monitor delegate can update the
// bounds/position for a progress indicator.
+ (id)inputStreamWithStream:(NSInputStream *)input
length:(unsigned long long)length;
- (id)initWithStream:(NSInputStream *)input
length:(unsigned long long)length;
// The monitor is called when bytes have been read
//
// monitorDelegate should respond to a selector with a signature matching:
//
// - (void)inputStream:(GTMProgressMonitorInputStream *)stream
// hasDeliveredBytes:(unsigned long long)numReadSoFar
// ofTotalBytes:(unsigned long long)total
//
// |total| will be the length passed when this GTMProgressMonitorInputStream was
// created.
- (void)setMonitorDelegate:(id)monitorDelegate // not retained
selector:(SEL)monitorSelector;
- (id)monitorDelegate;
- (SEL)monitorSelector;
// The source argument lets the delegate know the source of this input stream.
// this class does nothing w/ this, it's just here to provide context to your
// monitorDelegate.
- (void)setMonitorSource:(id)source; // not retained
- (id)monitorSource;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMProgressMonitorInputStream.h | Objective-C | bsd | 2,638 |
//
// GTMRegex.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#define GTMREGEX_DEFINE_GLOBALS 1
#import "GTMRegex.h"
#import "GTMDefines.h"
// This is the pattern to use for walking replacement text when doing
// substitutions.
//
// This pattern may look over-escaped, but remember the compiler will consume
// one layer of slashes, and then we have to escape the slashes for them to be
// seen as we want in the pattern.
static NSString *const kReplacementPattern =
@"((^|[^\\\\])(\\\\\\\\)*)(\\\\([0-9]+))";
#define kReplacementPatternLeadingTextIndex 1
#define kReplacementPatternSubpatternNumberIndex 5
@interface GTMRegex (PrivateMethods)
- (NSString *)errorMessage:(int)errCode;
- (BOOL)runRegexOnUTF8:(const char*)utf8Str
nmatch:(size_t)nmatch
pmatch:(regmatch_t *)pmatch
flags:(int)flags;
@end
// private enumerator as impl detail
@interface GTMRegexEnumerator : NSEnumerator {
@private
GTMRegex *regex_;
NSData *utf8StrBuf_;
BOOL allSegments_;
BOOL treatStartOfNewSegmentAsBeginningOfString_;
regoff_t curParseIndex_;
__strong regmatch_t *savedRegMatches_;
}
- (id)initWithRegex:(GTMRegex *)regex
processString:(NSString *)str
allSegments:(BOOL)allSegments;
- (void)treatStartOfNewSegmentAsBeginningOfString:(BOOL)yesNo;
@end
@interface GTMRegexStringSegment (PrivateMethods)
- (id)initWithUTF8StrBuf:(NSData *)utf8StrBuf
regMatches:(regmatch_t *)regMatches
numRegMatches:(NSUInteger)numRegMatches
isMatch:(BOOL)isMatch;
@end
@implementation GTMRegex
+ (id)regexWithPattern:(NSString *)pattern {
return [[[self alloc] initWithPattern:pattern] autorelease];
}
+ (id)regexWithPattern:(NSString *)pattern options:(GTMRegexOptions)options {
return [[[self alloc] initWithPattern:pattern
options:options] autorelease];
}
+ (id)regexWithPattern:(NSString *)pattern
options:(GTMRegexOptions)options
withError:(NSError **)outErrorOrNULL {
return [[[self alloc] initWithPattern:pattern
options:options
withError:outErrorOrNULL] autorelease];
}
+ (NSString *)escapedPatternForString:(NSString *)str {
if (str == nil)
return nil;
// NOTE: this could be done more efficiently by fetching the whole string into
// a unichar buffer and scanning that, along w/ pushing the data over in
// chunks (when possible).
NSUInteger len = [str length];
NSMutableString *result = [NSMutableString stringWithCapacity:len];
for (NSUInteger x = 0; x < len; ++x) {
unichar ch = [str characterAtIndex:x];
switch (ch) {
case '^':
case '.':
case '[':
case '$':
case '(':
case ')':
case '|':
case '*':
case '+':
case '?':
case '{':
case '\\':
[result appendFormat:@"\\%C", ch];
break;
default:
[result appendFormat:@"%C", ch];
break;
}
}
return result;
}
- (id)init {
return [self initWithPattern:nil];
}
- (id)initWithPattern:(NSString *)pattern {
return [self initWithPattern:pattern options:0];
}
- (id)initWithPattern:(NSString *)pattern options:(GTMRegexOptions)options {
return [self initWithPattern:pattern options:options withError:nil];
}
- (id)initWithPattern:(NSString *)pattern
options:(GTMRegexOptions)options
withError:(NSError **)outErrorOrNULL {
self = [super init];
if (!self) return nil;
if (outErrorOrNULL) *outErrorOrNULL = nil;
if ([pattern length] == 0) {
[self release];
return nil;
}
// figure out the flags
options_ = options;
int flags = REG_EXTENDED;
if (options_ & kGTMRegexOptionIgnoreCase)
flags |= REG_ICASE;
if ((options_ & kGTMRegexOptionSupressNewlineSupport) == 0)
flags |= REG_NEWLINE;
// even if regcomp failes we need a flags that we did call regcomp so we'll
// call regfree (because the structure can get filled in some to allow better
// error info). we use pattern_ as this flag.
pattern_ = [pattern copy];
if (!pattern_) {
// COV_NF_START - no real way to force this in a unittest
[self release];
return nil;
// COV_NF_END
}
// compile it
int compResult = regcomp(®exData_, [pattern_ UTF8String], flags);
if (compResult != 0) {
NSString *errorStr = [self errorMessage:compResult];
if (outErrorOrNULL) {
// include the pattern and patternError message in the userInfo.
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
pattern_, kGTMRegexPatternErrorPattern,
errorStr, kGTMRegexPatternErrorErrorString,
nil];
*outErrorOrNULL = [NSError errorWithDomain:kGTMRegexErrorDomain
code:kGTMRegexPatternParseFailedError
userInfo:userInfo];
} else {
// if caller didn't get us an NSError to fill in, we log the error to help
// debugging.
_GTMDevLog(@"Invalid pattern \"%@\", error: \"%@\"",
pattern_, errorStr);
}
[self release];
return nil;
}
return self;
}
- (void)finalize {
// we used pattern_ as our flag that we initialized the regex_t
if (pattern_) {
regfree(®exData_);
[pattern_ release];
// play it safe and clear it since we use it as a flag for regexData_
pattern_ = nil;
}
[super finalize];
}
- (void)dealloc {
// we used pattern_ as our flag that we initialized the regex_t
if (pattern_) {
regfree(®exData_);
[pattern_ release];
// play it safe and clear it since we use it as a flag for regexData_
pattern_ = nil;
}
[super dealloc];
}
- (NSUInteger)subPatternCount {
return regexData_.re_nsub;
}
- (BOOL)matchesString:(NSString *)str {
regmatch_t regMatch;
if (![self runRegexOnUTF8:[str UTF8String]
nmatch:1
pmatch:®Match
flags:0]) {
// no match
return NO;
}
// make sure the match is the full string
return (regMatch.rm_so == 0) &&
(regMatch.rm_eo == (regoff_t)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
}
- (NSArray *)subPatternsOfString:(NSString *)str {
NSArray *result = nil;
NSUInteger count = regexData_.re_nsub + 1;
regmatch_t *regMatches = malloc(sizeof(regmatch_t) * count);
if (!regMatches)
return nil; // COV_NF_LINE - no real way to force this in a unittest
// wrap it all in a try so we don't leak the malloc
@try {
const char *utf8Str = [str UTF8String];
if (![self runRegexOnUTF8:utf8Str
nmatch:count
pmatch:regMatches
flags:0]) {
// no match
return nil;
}
// make sure the match is the full string
if ((regMatches[0].rm_so != 0) ||
(regMatches[0].rm_eo != (regoff_t)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding])) {
// only matched a sub part of the string
return nil;
}
NSMutableArray *buildResult = [NSMutableArray arrayWithCapacity:count];
for (NSUInteger x = 0 ; x < count ; ++x) {
if ((regMatches[x].rm_so == -1) && (regMatches[x].rm_eo == -1)) {
// add NSNull since it wasn't used
[buildResult addObject:[NSNull null]];
} else {
// fetch the string
const char *base = utf8Str + regMatches[x].rm_so;
regoff_t len = regMatches[x].rm_eo - regMatches[x].rm_so;
NSString *sub =
[[[NSString alloc] initWithBytes:base
length:(NSUInteger)len
encoding:NSUTF8StringEncoding] autorelease];
[buildResult addObject:sub];
}
}
result = buildResult;
} // COV_NF_LINE - radar 5851992 not all brackets reachable w/ obj-c exceptions and coverage
@finally {
free(regMatches);
}
return result;
}
- (NSString *)firstSubStringMatchedInString:(NSString *)str {
NSString *result = nil;
regmatch_t regMatch;
const char *utf8Str = [str UTF8String];
if ([self runRegexOnUTF8:utf8Str
nmatch:1
pmatch:®Match
flags:0]) {
// fetch the string
const char *base = utf8Str + regMatch.rm_so;
regoff_t len = regMatch.rm_eo - regMatch.rm_so;
result =
[[[NSString alloc] initWithBytes:base
length:(NSUInteger)len
encoding:NSUTF8StringEncoding] autorelease];
}
return result;
}
- (BOOL)matchesSubStringInString:(NSString *)str {
regmatch_t regMatch;
if ([self runRegexOnUTF8:[str UTF8String]
nmatch:1
pmatch:®Match
flags:0]) {
// don't really care what matched, just report the match
return YES;
}
return NO;
}
- (NSEnumerator *)segmentEnumeratorForString:(NSString *)str {
return [[[GTMRegexEnumerator alloc] initWithRegex:self
processString:str
allSegments:YES] autorelease];
}
- (NSEnumerator *)matchSegmentEnumeratorForString:(NSString *)str {
return [[[GTMRegexEnumerator alloc] initWithRegex:self
processString:str
allSegments:NO] autorelease];
}
- (NSString *)stringByReplacingMatchesInString:(NSString *)str
withReplacement:(NSString *)replacementPattern {
if (!str)
return nil;
// if we have a replacement, we go ahead and crack it now. if the replacement
// is just an empty string (or nil), just use the nil marker.
NSArray *replacements = nil;
if ([replacementPattern length]) {
// don't need newline support, just match the start of the pattern for '^'
GTMRegex *replacementRegex =
[GTMRegex regexWithPattern:kReplacementPattern
options:kGTMRegexOptionSupressNewlineSupport];
#ifdef DEBUG
if (!replacementRegex) {
_GTMDevLog(@"failed to parse out replacement regex!!!"); // COV_NF_LINE
}
#endif
GTMRegexEnumerator *relacementEnumerator =
[[[GTMRegexEnumerator alloc] initWithRegex:replacementRegex
processString:replacementPattern
allSegments:YES] autorelease];
// We turn on treatStartOfNewSegmentAsBeginningOfLine for this enumerator.
// As complex as kReplacementPattern is, it can't completely do what we want
// with the normal string walk. The problem is this, backreferences are a
// slash follow by a number ("\0"), but the replacement pattern might
// actually need to use backslashes (they have to be escaped). So if a
// replacement were "\\0", then there is no backreference, instead the
// replacement is a backslash and a zero. Generically this means an even
// number of backslashes are all escapes, and an odd are some number of
// literal backslashes followed by our backreference. Think of it as a "an
// odd number of slashes that comes after a non-backslash character." There
// is no way to rexpress this in re_format(7) extended expressions. Instead
// we look for a non-blackslash or string start followed by an optional even
// number of slashes followed by the backreference; and use the special
// flag; so after each match, we restart claiming it's the start of the
// string. (the problem match w/o this flag is a substition of "\2\1")
[relacementEnumerator treatStartOfNewSegmentAsBeginningOfString:YES];
// pull them all into an array so we can walk this as many times as needed.
replacements = [relacementEnumerator allObjects];
if (!replacements) {
// COV_NF_START - no real way to force this in a unittest
_GTMDevLog(@"failed to create the replacements for substitutions");
return nil;
// COV_NF_END
}
}
NSMutableString *result = [NSMutableString stringWithCapacity:[str length]];
NSEnumerator *enumerator = [self segmentEnumeratorForString:str];
GTMRegexStringSegment *segment = nil;
while ((segment = [enumerator nextObject]) != nil) {
if (![segment isMatch]) {
// not a match, just move this chunk over
[result appendString:[segment string]];
} else {
// match...
if (!replacements) {
// no replacements, they want to eat matches, nothing to do
} else {
// spin over the split up replacement
NSEnumerator *replacementEnumerator = [replacements objectEnumerator];
GTMRegexStringSegment *replacementSegment = nil;
while ((replacementSegment = [replacementEnumerator nextObject]) != nil) {
if (![replacementSegment isMatch]) {
// not a match, raw text to put in
[result appendString:[replacementSegment string]];
} else {
// match...
// first goes any leading text
NSString *leading =
[replacementSegment subPatternString:kReplacementPatternLeadingTextIndex];
if (leading)
[result appendString:leading];
// then use the subpattern number to find what goes in from the
// original string match.
int subPatternNum =
[[replacementSegment subPatternString:kReplacementPatternSubpatternNumberIndex] intValue];
NSString *matchSubPatStr = [segment subPatternString:subPatternNum];
// handle an unused subpattern (ie-nil result)
if (matchSubPatStr)
[result appendString:matchSubPatStr];
}
}
}
}
}
return result;
}
- (NSString *)description {
NSMutableString *result =
[NSMutableString stringWithFormat:@"%@<%p> { pattern=\"%@\", rawNumSubPatterns=%z, options=(",
[self class], self, pattern_, regexData_.re_nsub];
if (options_) {
if (options_ & kGTMRegexOptionIgnoreCase)
[result appendString:@" IgnoreCase"];
if ((options_ & kGTMRegexOptionSupressNewlineSupport) == kGTMRegexOptionSupressNewlineSupport)
[result appendString:@" NoNewlineSupport"];
} else {
[result appendString:@" None(Default)"];
}
[result appendString:@" ) }"];
return result;
}
@end
@implementation GTMRegex (PrivateMethods)
- (NSString *)errorMessage:(int)errCode {
NSString *result = @"internal error";
// size the buffer we need
size_t len = regerror(errCode, ®exData_, nil, 0);
char buffer[len];
// fetch the error
if (len == regerror(errCode, ®exData_, buffer, len)) {
NSString *generatedError = [NSString stringWithUTF8String:buffer];
if (generatedError)
result = generatedError;
}
return result;
}
// private helper to run the regex on a block
- (BOOL)runRegexOnUTF8:(const char*)utf8Str
nmatch:(size_t)nmatch
pmatch:(regmatch_t *)pmatch
flags:(int)flags {
if (!utf8Str)
return NO;
int execResult = regexec(®exData_, utf8Str, nmatch, pmatch, flags);
if (execResult != 0) {
#ifdef DEBUG
if (execResult != REG_NOMATCH) {
// COV_NF_START - no real way to force this in a unittest
NSString *errorStr = [self errorMessage:execResult];
_GTMDevLog(@"%@: matching string \"%.20s...\", had error: \"%@\"",
self, utf8Str, errorStr);
// COV_NF_END
}
#endif
return NO;
}
return YES;
}
@end
@implementation GTMRegexEnumerator
// we don't block init because the class isn't exported, so no one can
// create one, or if they do, they get whatever happens...
- (id)initWithRegex:(GTMRegex *)regex
processString:(NSString *)str
allSegments:(BOOL)allSegments {
self = [super init];
if (!self) return nil;
// collect args
regex_ = [regex retain];
utf8StrBuf_ = [[str dataUsingEncoding:NSUTF8StringEncoding] retain];
allSegments_ = allSegments;
// arg check
if (!regex_ || !utf8StrBuf_) {
[self release];
return nil;
}
// parsing state initialized to zero for us by object creation
return self;
}
// Don't need a finalize because savedRegMatches_ is marked __strong
- (void)dealloc {
if (savedRegMatches_) {
free(savedRegMatches_);
savedRegMatches_ = nil;
}
[regex_ release];
[utf8StrBuf_ release];
[super dealloc];
}
- (void)treatStartOfNewSegmentAsBeginningOfString:(BOOL)yesNo {
// The way regexec works, it assumes the first char it's looking at to the
// start of the string. In normal use, this makes sense; but in this case,
// we're going to walk the entry string splitting it up by our pattern. That
// means for the first call, it is the string start, but for all future calls,
// it is NOT the string start, so we will pass regexec the flag to let it
// know. However, (you knew that was coming), there are some cases where you
// actually want the each pass to be considered as the start of the string
// (usually the cases are where a pattern can't express what's needed w/o
// this). There is no really good way to explain this behavior w/o all this
// text and lot of examples, so for now this is not in the public api, and
// just here. (Hint: see what w/in this file uses this for why we have it)
treatStartOfNewSegmentAsBeginningOfString_ = yesNo;
}
- (id)nextObject {
GTMRegexStringSegment *result = nil;
regmatch_t *nextMatches = nil;
BOOL isMatch = NO;
// we do all this w/in a try, so if something throws, the memory we malloced
// will still get cleaned up
@try {
// if we have a saved match, use that...
if (savedRegMatches_) {
nextMatches = savedRegMatches_;
savedRegMatches_ = nil;
isMatch = YES; // if we have something saved, it was a pattern match
}
// have we reached the end?
else if (curParseIndex_ >= (regoff_t)[utf8StrBuf_ length]) {
// done, do nothing, we'll return nil
}
// do the search.
else {
// alloc the match structure (extra space for the zero (full) match)
size_t matchBufSize = ([regex_ subPatternCount] + 1) * sizeof(regmatch_t);
nextMatches = malloc(matchBufSize);
if (!nextMatches)
return nil; // COV_NF_LINE - no real way to force this in a unittest
// setup our range to work on
nextMatches[0].rm_so = curParseIndex_;
nextMatches[0].rm_eo = [utf8StrBuf_ length];
// figure out our flags
int flags = REG_STARTEND;
if ((!treatStartOfNewSegmentAsBeginningOfString_) &&
(curParseIndex_ != 0)) {
// see -treatStartOfNewSegmentAsBeginningOfString: for why we have
// this check here.
flags |= REG_NOTBOL;
}
// call for the match
if ([regex_ runRegexOnUTF8:[utf8StrBuf_ bytes]
nmatch:([regex_ subPatternCount] + 1)
pmatch:nextMatches
flags:flags]) {
// match
if (allSegments_ &&
(nextMatches[0].rm_so != curParseIndex_)) {
// we should return all segments (not just matches), and there was
// something before this match. So safe off this match for later
// and create a range for this.
savedRegMatches_ = nextMatches;
nextMatches = malloc(matchBufSize);
if (!nextMatches)
return nil; // COV_NF_LINE - no real way to force this in a unittest
isMatch = NO;
// mark everything but the zero slot w/ not used
for (NSUInteger x = [regex_ subPatternCount]; x > 0; --x) {
nextMatches[x].rm_so = nextMatches[x].rm_eo = -1;
}
nextMatches[0].rm_so = curParseIndex_;
nextMatches[0].rm_eo = savedRegMatches_[0].rm_so;
// advance our marker
curParseIndex_ = savedRegMatches_[0].rm_eo;
} else {
// we only return matches or are pointed at a match
// no real work to do, just fall through to return to return the
// current match.
isMatch = YES;
// advance our marker
curParseIndex_ = nextMatches[0].rm_eo;
}
} else {
// no match
// should we return the last non matching segment?
if (allSegments_) {
isMatch = NO;
// mark everything but the zero slot w/ not used
for (NSUInteger x = [regex_ subPatternCount]; x > 0; --x) {
nextMatches[x].rm_so = nextMatches[x].rm_eo = -1;
}
nextMatches[0].rm_so = curParseIndex_;
nextMatches[0].rm_eo = [utf8StrBuf_ length];
} else {
// drop match set, we don't want it
free(nextMatches);
nextMatches = nil;
}
// advance our marker since we're done
curParseIndex_ = [utf8StrBuf_ length];
}
}
// create the segment to return
if (nextMatches) {
result =
[[[GTMRegexStringSegment alloc] initWithUTF8StrBuf:utf8StrBuf_
regMatches:nextMatches
numRegMatches:[regex_ subPatternCount]
isMatch:isMatch] autorelease];
nextMatches = nil;
}
} // COV_NF_START - no real way to force this in a test
@catch (id e) {
_GTMDevLog(@"Exceptions while trying to advance enumeration (%@)", e);
// if we still have something in our temp, free it
if (nextMatches)
free(nextMatches);
} // COV_NF_END
return result;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@<%p> { regex=\"%@\", allSegments=%s, string=\"%.20s...\" }",
[self class], self,
regex_,
(allSegments_ ? "YES" : "NO"),
[utf8StrBuf_ bytes]];
}
@end
@implementation GTMRegexStringSegment
- (id)init {
// make sure init is never called, the class in in the header so someone
// could try to create it by mistake.
[self doesNotRecognizeSelector:_cmd];
return nil; // COV_NF_LINE - return is just here to keep gcc happy
}
- (void)dealloc {
if (regMatches_) {
free(regMatches_);
regMatches_ = nil;
}
[utf8StrBuf_ release];
[super dealloc];
}
- (BOOL)isMatch {
return isMatch_;
}
- (NSString *)string {
// fetch match zero
return [self subPatternString:0];
}
- (NSString *)subPatternString:(NSUInteger)patternIndex {
if (patternIndex > numRegMatches_)
return nil;
// pick off when it wasn't found
if ((regMatches_[patternIndex].rm_so == -1) &&
(regMatches_[patternIndex].rm_eo == -1))
return nil;
// fetch the string
const char *base = (const char*)[utf8StrBuf_ bytes]
+ regMatches_[patternIndex].rm_so;
regoff_t len = regMatches_[patternIndex].rm_eo
- regMatches_[patternIndex].rm_so;
return [[[NSString alloc] initWithBytes:base
length:(NSUInteger)len
encoding:NSUTF8StringEncoding] autorelease];
}
- (NSString *)description {
NSMutableString *result =
[NSMutableString stringWithFormat:@"%@<%p> { isMatch=\"%s\", subPatterns=(",
[self class], self, (isMatch_ ? "YES" : "NO")];
for (NSUInteger x = 0; x <= numRegMatches_; ++x) {
NSString *format = @", \"%.*s\"";
if (x == 0)
format = @" \"%.*s\"";
[result appendFormat:format,
(int)(regMatches_[x].rm_eo - regMatches_[x].rm_so),
(((const char*)[utf8StrBuf_ bytes]) + regMatches_[x].rm_so)];
}
[result appendString:@" ) }"];
return result;
}
@end
@implementation GTMRegexStringSegment (PrivateMethods)
- (id)initWithUTF8StrBuf:(NSData *)utf8StrBuf
regMatches:(regmatch_t *)regMatches
numRegMatches:(NSUInteger)numRegMatches
isMatch:(BOOL)isMatch {
self = [super init];
if (!self) return nil;
utf8StrBuf_ = [utf8StrBuf retain];
regMatches_ = regMatches;
numRegMatches_ = numRegMatches;
isMatch_ = isMatch;
// check the args
if (!utf8StrBuf_ || !regMatches_) {
// COV_NF_START
// this could only happen something messed w/ our internal state.
[self release];
return nil;
// COV_NF_END
}
return self;
}
@end
@implementation NSString (GTMRegexAdditions)
- (BOOL)gtm_matchesPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex matchesString:self];
}
- (NSArray *)gtm_subPatternsOfPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex subPatternsOfString:self];
}
- (NSString *)gtm_firstSubStringMatchedByPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex firstSubStringMatchedInString:self];
}
- (BOOL)gtm_subStringMatchesPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex matchesSubStringInString:self];
}
- (NSArray *)gtm_allSubstringsMatchedByPattern:(NSString *)pattern {
NSEnumerator *enumerator = [self gtm_matchSegmentEnumeratorForPattern:pattern];
NSArray *allSegments = [enumerator allObjects];
return [allSegments valueForKey:@"string"];
}
- (NSEnumerator *)gtm_segmentEnumeratorForPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex segmentEnumeratorForString:self];
}
- (NSEnumerator *)gtm_matchSegmentEnumeratorForPattern:(NSString *)pattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex matchSegmentEnumeratorForString:self];
}
- (NSString *)gtm_stringByReplacingMatchesOfPattern:(NSString *)pattern
withReplacement:(NSString *)replacementPattern {
GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
return [regex stringByReplacingMatchesInString:self
withReplacement:replacementPattern];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMRegex.m | Objective-C | bsd | 26,533 |
//
// NSAppleScript+HandlerTest.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import <Carbon/Carbon.h>
#import "GTMNSAppleScript+Handler.h"
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMUnitTestDevLog.h"
@interface GTMNSAppleScript_HandlerTest : GTMTestCase {
NSAppleScript *script_;
}
@end
@implementation GTMNSAppleScript_HandlerTest
- (void)setUp {
NSBundle *bundle = [NSBundle bundleForClass:[GTMNSAppleScript_HandlerTest class]];
STAssertNotNil(bundle, nil);
NSString *path = [bundle pathForResource:@"GTMNSAppleEvent+HandlerTest"
ofType:@"scpt"
inDirectory:@"Scripts"];
STAssertNotNil(path, [bundle description]);
NSDictionary *error = nil;
script_ = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]
error:&error];
STAssertNotNil(script_, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
}
- (void)tearDown {
[script_ release];
script_ = nil;
}
- (void)testHandlerNoParamsNoReturn {
NSDictionary *error = nil;
NSAppleEventDescriptor *desc = [script_ gtm_executePositionalHandler:@"test"
parameters:nil
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeNull, nil);
desc = [script_ gtm_executePositionalHandler:@"test"
parameters:[NSArray array]
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeNull, nil);
//Applescript doesn't appear to get upset about extra params
desc = [script_ gtm_executePositionalHandler:@"test"
parameters:[NSArray arrayWithObject:@"foo"]
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeNull, nil);
}
- (void)testHandlerNoParamsWithReturn {
NSDictionary *error = nil;
NSAppleEventDescriptor *desc = [script_ gtm_executePositionalHandler:@"testReturnOne"
parameters:nil
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)1, nil);
desc = [script_ gtm_executePositionalHandler:@"testReturnOne"
parameters:[NSArray array]
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)1, nil);
//Applescript doesn't appear to get upset about extra params
desc = [script_ gtm_executePositionalHandler:@"testReturnOne"
parameters:[NSArray arrayWithObject:@"foo"]
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)1, nil);
}
- (void)testHandlerOneParamWithReturn {
NSDictionary *error = nil;
// Note case change in executeHandler call
NSAppleEventDescriptor *desc = [script_ gtm_executePositionalHandler:@"testreturnParam"
parameters:nil
error:&error];
STAssertNil(desc, @"Desc should by nil %@", desc);
STAssertNotNil(error, nil);
error = nil;
desc = [script_ gtm_executePositionalHandler:@"testReturnParam"
parameters:[NSArray array]
error:&error];
STAssertNil(desc, @"Desc should by nil %@", desc);
STAssertNotNil(error, nil);
error = nil;
desc = [script_ gtm_executePositionalHandler:@"testReturnParam"
parameters:[NSArray arrayWithObject:@"foo"]
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeUnicodeText, nil);
STAssertEqualObjects([desc gtm_objectValue], @"foo", nil);
}
- (void)testHandlerTwoParamsWithReturn {
NSDictionary *error = nil;
// Note case change in executeHandler call
// Test case and empty params
NSAppleEventDescriptor *desc = [script_ gtm_executePositionalHandler:@"testADDPArams"
parameters:nil
error:&error];
STAssertNil(desc, @"Desc should by nil %@", desc);
STAssertNotNil(error, nil);
// Test empty params
error = nil;
desc = [script_ gtm_executePositionalHandler:@"testAddParams"
parameters:[NSArray array]
error:&error];
STAssertNil(desc, @"Desc should by nil %@", desc);
STAssertNotNil(error, nil);
error = nil;
NSArray *args = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
nil];
desc = [script_ gtm_executePositionalHandler:@"testAddParams"
parameters:args
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)3, nil);
// Test bad params
error = nil;
args = [NSArray arrayWithObjects:
@"foo",
@"bar",
nil];
desc = [script_ gtm_executePositionalHandler:@"testAddParams"
parameters:args
error:&error];
STAssertNil(desc, @"Desc should by nil %@", desc);
STAssertNotNil(error, nil);
// Test too many params. Currently Applescript allows this so it should pass
error = nil;
args = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
nil];
desc = [script_ gtm_executePositionalHandler:@"testAddParams"
parameters:args
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)3, nil);}
- (void)testLabeledHandler {
NSDictionary *error = nil;
AEKeyword labels[] = { keyDirectObject,
keyASPrepositionOnto,
keyASPrepositionGiven };
id params[3];
params[0] = [NSNumber numberWithInt:1];
params[1] = [NSNumber numberWithInt:3];
params[2] = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:4]
forKey:@"othervalue"];
NSAppleEventDescriptor *desc = [script_ gtm_executeLabeledHandler:@"testAdd"
labels:labels
parameters:params
count:sizeof(params) / sizeof(id)
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)8, nil);
// Test too many params. Currently Applescript allows this so it should pass
AEKeyword labels2[] = { keyDirectObject,
keyASPrepositionOnto,
keyASPrepositionBetween,
keyASPrepositionGiven };
id params2[4];
params2[0] = [NSNumber numberWithInt:1];
params2[1] = [NSNumber numberWithInt:3];
params2[2] = [NSNumber numberWithInt:5];
params2[3] = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:4]
forKey:@"othervalue"];
error = nil;
desc = [script_ gtm_executeLabeledHandler:@"testAdd"
labels:labels2
parameters:params2
count:sizeof(params2) / sizeof(id)
error:&error];
STAssertNotNil(desc, [error description]);
STAssertNil(error, @"Error should be nil. Error = %@", [error description]);
STAssertEquals([desc descriptorType], (DescType)typeSInt32, nil);
STAssertEquals([desc int32Value], (SInt32)8, nil);}
- (void)testHandlers {
NSSet *handlers = [script_ gtm_handlers];
NSSet *expected = [NSSet setWithObjects:
@"aevtodoc",
@"test",
@"testreturnone",
@"testreturnparam",
@"testaddparams",
@"testadd",
nil];
STAssertEqualObjects(handlers, expected, @"Unexpected handlers?");
}
- (void)testProperties {
NSSet *properties = [script_ gtm_properties];
NSSet *expected = [NSSet setWithObjects:
@"foo",
@"asdscriptuniqueidentifier",
nil];
STAssertEqualObjects(properties, expected, @"Unexpected properties?");
id value = [script_ gtm_valueForProperty:@"foo"];
STAssertEqualObjects(value, [NSNumber numberWithInt:1], @"bad property?");
BOOL goodSet = [script_ gtm_setValue:@"bar" forProperty:@"foo"];
STAssertTrue(goodSet, @"Couldn't set property");
value = [script_ gtm_valueForProperty:@"foo"];
STAssertEqualObjects(value, @"bar", @"bad property?");
[GTMUnitTestDevLog expectPattern:@"Unable to setValue:bar forProperty:"
"\\(null\\) from <NSAppleScript: 0x[0-9a-f]+> \\(-50\\)"];
goodSet = [script_ gtm_setValue:@"bar" forProperty:nil];
STAssertFalse(goodSet, @"Set property?");
[GTMUnitTestDevLog expectPattern:@"Unable to get valueForProperty:gargle "
"from <NSAppleScript: 0x[0-9a-f]+> \\(-1753\\)"];
value = [script_ gtm_valueForProperty:@"gargle"];
STAssertNil(value, @"Property named gargle?");
}
- (void)testFailures {
NSDictionary *error = nil;
NSAppleEventDescriptor *desc = [script_ gtm_executePositionalHandler:@"noSuchTest"
parameters:nil
error:&error];
STAssertNil(desc, nil);
STAssertNotNil(error, nil);
// Test with empty handler name
error = nil;
desc = [script_ gtm_executePositionalHandler:@""
parameters:[NSArray array]
error:&error];
STAssertNil(desc, nil);
STAssertNotNil(error, nil);
// Test with nil handler
error = nil;
desc = [script_ gtm_executePositionalHandler:nil
parameters:[NSArray array]
error:&error];
STAssertNil(desc, nil);
STAssertNotNil(error, nil);
// Test with nil handler and nil error
desc = [script_ gtm_executePositionalHandler:nil
parameters:nil
error:nil];
STAssertNil(desc, nil);
// Test with a bad script
NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:@"david hasselhoff"] autorelease];
[GTMUnitTestDevLog expectPattern:@"Unable to compile script: .*"];
[GTMUnitTestDevLog expectPattern:@"Error getting handlers: -[0-9]+"];
NSSet *handlers = [script gtm_handlers];
STAssertEquals([handlers count], (NSUInteger)0, @"Should have no handlers");
[GTMUnitTestDevLog expectPattern:@"Unable to compile script: .*"];
[GTMUnitTestDevLog expectPattern:@"Error getting properties: -[0-9]+"];
NSSet *properties = [script gtm_properties];
STAssertEquals([properties count], (NSUInteger)0, @"Should have no properties");
}
- (void)testScriptDescriptors {
NSAppleEventDescriptor *desc = [script_ gtm_appleEventDescriptor];
STAssertNotNil(desc, @"Couldn't make a script desc");
NSAppleScript *script = [desc gtm_objectValue];
STAssertNotNil(script, @"Couldn't get a script back");
NSSet *handlers = [script gtm_handlers];
STAssertNotNil(handlers, @"Couldn't get handlers");
}
@protocol ScriptInterface
- (id)test;
- (id)testReturnParam:(id)param;
- (id)testAddParams:(id)param1 :(id)param2;
@end
- (void)testForwarding {
id<ScriptInterface> foo = (id<ScriptInterface>)script_;
[foo test];
NSNumber *val = [foo testReturnParam:[NSNumber numberWithInt:2]];
STAssertEquals([val intValue], 2, @"should be 2");
val = [foo testAddParams:[NSNumber numberWithInt:2] :[NSNumber numberWithInt:3]];
STAssertEquals([val intValue], 5, @"should be 5");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleScript+HandlerTest.m | Objective-C | bsd | 14,471 |
//
// GTMNSAppleEventDescriptor+Handler.h
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
@interface NSAppleEventDescriptor (GTMAppleEventDescriptorHandlerAdditions)
+ (id)gtm_descriptorWithPositionalHandler:(NSString*)handler
parametersArray:(NSArray*)params;
+ (id)gtm_descriptorWithPositionalHandler:(NSString*)handler
parametersDescriptor:(NSAppleEventDescriptor*)params;
+ (id)gtm_descriptorWithLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count;
- (id)gtm_initWithPositionalHandler:(NSString*)handler
parametersArray:(NSArray*)params;
- (id)gtm_initWithPositionalHandler:(NSString*)handler
parametersDescriptor:(NSAppleEventDescriptor*)params;
- (id)gtm_initWithLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+Handler.h | Objective-C | bsd | 1,709 |
--
-- Copyright 2008 Google Inc.
--
-- 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.
--
property foo : 1
on test()
end test
on testReturnOne()
return 1
end testReturnOne
on testReturnParam(param)
return param
end testReturnParam
on testAddParams(param1, param2)
return param1 + param2
end testAddParams
on testAdd of a onto b given otherValue:d
return a + b + d
end testAdd
on open
end open
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEvent+HandlerTest.applescript | AppleScript | bsd | 918 |
//
// GTMNSString+URLArgumentsTest.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMNSString+URLArguments.h"
@interface GTMNSString_URLArgumentsTest : GTMTestCase
@end
@implementation GTMNSString_URLArgumentsTest
- (void)testEscaping {
// should be done already by the basic code
STAssertEqualObjects([@"this that" gtm_stringByEscapingForURLArgument], @"this%20that", @"- space should be escaped");
STAssertEqualObjects([@"this\"that" gtm_stringByEscapingForURLArgument], @"this%22that", @"- double quote should be escaped");
// make sure our additions are handled
STAssertEqualObjects([@"this!that" gtm_stringByEscapingForURLArgument], @"this%21that", @"- exclamation mark should be escaped");
STAssertEqualObjects([@"this*that" gtm_stringByEscapingForURLArgument], @"this%2Athat", @"- asterisk should be escaped");
STAssertEqualObjects([@"this'that" gtm_stringByEscapingForURLArgument], @"this%27that", @"- single quote should be escaped");
STAssertEqualObjects([@"this(that" gtm_stringByEscapingForURLArgument], @"this%28that", @"- left paren should be escaped");
STAssertEqualObjects([@"this)that" gtm_stringByEscapingForURLArgument], @"this%29that", @"- right paren should be escaped");
STAssertEqualObjects([@"this;that" gtm_stringByEscapingForURLArgument], @"this%3Bthat", @"- semi-colon should be escaped");
STAssertEqualObjects([@"this:that" gtm_stringByEscapingForURLArgument], @"this%3Athat", @"- colon should be escaped");
STAssertEqualObjects([@"this@that" gtm_stringByEscapingForURLArgument], @"this%40that", @"- at sign should be escaped");
STAssertEqualObjects([@"this&that" gtm_stringByEscapingForURLArgument], @"this%26that", @"- ampersand should be escaped");
STAssertEqualObjects([@"this=that" gtm_stringByEscapingForURLArgument], @"this%3Dthat", @"- equals should be escaped");
STAssertEqualObjects([@"this+that" gtm_stringByEscapingForURLArgument], @"this%2Bthat", @"- plus should be escaped");
STAssertEqualObjects([@"this$that" gtm_stringByEscapingForURLArgument], @"this%24that", @"- dollar-sign should be escaped");
STAssertEqualObjects([@"this,that" gtm_stringByEscapingForURLArgument], @"this%2Cthat", @"- comma should be escaped");
STAssertEqualObjects([@"this/that" gtm_stringByEscapingForURLArgument], @"this%2Fthat", @"- slash should be escaped");
STAssertEqualObjects([@"this?that" gtm_stringByEscapingForURLArgument], @"this%3Fthat", @"- question mark should be escaped");
STAssertEqualObjects([@"this%that" gtm_stringByEscapingForURLArgument], @"this%25that", @"- percent should be escaped");
STAssertEqualObjects([@"this#that" gtm_stringByEscapingForURLArgument], @"this%23that", @"- pound should be escaped");
STAssertEqualObjects([@"this[that" gtm_stringByEscapingForURLArgument], @"this%5Bthat", @"- left bracket should be escaped");
STAssertEqualObjects([@"this]that" gtm_stringByEscapingForURLArgument], @"this%5Dthat", @"- right bracket should be escaped");
// make sure plus and space are handled in the right order
STAssertEqualObjects([@"this that+the other" gtm_stringByEscapingForURLArgument], @"this%20that%2Bthe%20other", @"- pluses and spaces should be different");
// high char test
NSString *tester = [NSString stringWithUTF8String:"caf\xC3\xA9"];
STAssertNotNil(tester, @"failed to create from utf8 run");
STAssertEqualObjects([tester gtm_stringByEscapingForURLArgument], @"caf%C3%A9", @"- high chars should work");
}
- (void)testUnescaping {
// should be done already by the basic code
STAssertEqualObjects([@"this%20that" gtm_stringByUnescapingFromURLArgument], @"this that", @"- space should be unescaped");
STAssertEqualObjects([@"this%22that" gtm_stringByUnescapingFromURLArgument], @"this\"that", @"- double quote should be unescaped");
// make sure our additions are handled
STAssertEqualObjects([@"this%21that" gtm_stringByUnescapingFromURLArgument], @"this!that", @"- exclamation mark should be unescaped");
STAssertEqualObjects([@"this%2Athat" gtm_stringByUnescapingFromURLArgument], @"this*that", @"- asterisk should be unescaped");
STAssertEqualObjects([@"this%27that" gtm_stringByUnescapingFromURLArgument], @"this'that", @"- single quote should be unescaped");
STAssertEqualObjects([@"this%28that" gtm_stringByUnescapingFromURLArgument], @"this(that", @"- left paren should be unescaped");
STAssertEqualObjects([@"this%29that" gtm_stringByUnescapingFromURLArgument], @"this)that", @"- right paren should be unescaped");
STAssertEqualObjects([@"this%3Bthat" gtm_stringByUnescapingFromURLArgument], @"this;that", @"- semi-colon should be unescaped");
STAssertEqualObjects([@"this%3Athat" gtm_stringByUnescapingFromURLArgument], @"this:that", @"- colon should be unescaped");
STAssertEqualObjects([@"this%40that" gtm_stringByUnescapingFromURLArgument], @"this@that", @"- at sign should be unescaped");
STAssertEqualObjects([@"this%26that" gtm_stringByUnescapingFromURLArgument], @"this&that", @"- ampersand should be unescaped");
STAssertEqualObjects([@"this%3Dthat" gtm_stringByUnescapingFromURLArgument], @"this=that", @"- equals should be unescaped");
STAssertEqualObjects([@"this%2Bthat" gtm_stringByUnescapingFromURLArgument], @"this+that", @"- plus should be unescaped");
STAssertEqualObjects([@"this%24that" gtm_stringByUnescapingFromURLArgument], @"this$that", @"- dollar-sign should be unescaped");
STAssertEqualObjects([@"this%2Cthat" gtm_stringByUnescapingFromURLArgument], @"this,that", @"- comma should be unescaped");
STAssertEqualObjects([@"this%2Fthat" gtm_stringByUnescapingFromURLArgument], @"this/that", @"- slash should be unescaped");
STAssertEqualObjects([@"this%3Fthat" gtm_stringByUnescapingFromURLArgument], @"this?that", @"- question mark should be unescaped");
STAssertEqualObjects([@"this%25that" gtm_stringByUnescapingFromURLArgument], @"this%that", @"- percent should be unescaped");
STAssertEqualObjects([@"this%23that" gtm_stringByUnescapingFromURLArgument], @"this#that", @"- pound should be unescaped");
STAssertEqualObjects([@"this%5Bthat" gtm_stringByUnescapingFromURLArgument], @"this[that", @"- left bracket should be unescaped");
STAssertEqualObjects([@"this%5Dthat" gtm_stringByUnescapingFromURLArgument], @"this]that", @"- right bracket should be unescaped");
// make sure a plus come back out as a space
STAssertEqualObjects([[NSString stringWithString:@"this+that"] gtm_stringByUnescapingFromURLArgument], @"this that", @"- plus should be unescaped");
// make sure plus and %2B are handled in the right order
STAssertEqualObjects([@"this+that%2Bthe%20other" gtm_stringByUnescapingFromURLArgument], @"this that+the other", @"- pluses and spaces should be different");
// high char test
NSString *tester = [NSString stringWithUTF8String:"caf\xC3\xA9"];
STAssertNotNil(tester, @"failed to create from utf8 run");
STAssertEqualObjects([[NSString stringWithString:@"caf%C3%A9"] gtm_stringByUnescapingFromURLArgument], tester, @"- high chars should work");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+URLArgumentsTest.m | Objective-C | bsd | 7,594 |
//
// GTMNSString+URLArguments.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
/// Utilities for encoding and decoding URL arguments.
@interface NSString (GTMNSStringURLArgumentsAdditions)
/// Returns a string that is escaped properly to be a URL argument.
//
/// This differs from stringByAddingPercentEscapesUsingEncoding: in that it
/// will escape all the reserved characters (per RFC 3986
/// <http://www.ietf.org/rfc/rfc3986.txt>) which
/// stringByAddingPercentEscapesUsingEncoding would leave.
///
/// This will also escape '%', so this should not be used on a string that has
/// already been escaped unless double-escaping is the desired result.
- (NSString*)gtm_stringByEscapingForURLArgument;
/// Returns the unescaped version of a URL argument
//
/// This has the same behavior as stringByReplacingPercentEscapesUsingEncoding:,
/// except that it will also convert '+' to space.
- (NSString*)gtm_stringByUnescapingFromURLArgument;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.h | Objective-C | bsd | 1,552 |
//
// GTMObjectSingleton.h
// Macro to implement methods for a singleton
//
// Copyright 2005-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
/// This macro implements the various methods needed to make a safe singleton.
//
/// This Singleton pattern was taken from:
/// http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
///
/// Sample usage:
///
/// GTMOBJECT_SINGLETON_BOILERPLATE(SomeUsefulManager, sharedSomeUsefulManager)
/// (with no trailing semicolon)
///
#define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_, _shared_obj_name_) \
static _object_name_ *z##_shared_obj_name_ = nil; \
+ (_object_name_ *)_shared_obj_name_ { \
@synchronized(self) { \
if (z##_shared_obj_name_ == nil) { \
/* Note that 'self' may not be the same as _object_name_ */ \
/* first assignment done in allocWithZone but we must reassign in case init fails */ \
z##_shared_obj_name_ = [[self alloc] init]; \
_GTMDevAssert((z##_shared_obj_name_ != nil), @"didn't catch singleton allocation"); \
} \
} \
return z##_shared_obj_name_; \
} \
+ (id)allocWithZone:(NSZone *)zone { \
@synchronized(self) { \
if (z##_shared_obj_name_ == nil) { \
z##_shared_obj_name_ = [super allocWithZone:zone]; \
return z##_shared_obj_name_; \
} \
} \
\
/* We can't return the shared instance, because it's been init'd */ \
_GTMDevAssert(NO, @"use the singleton API, not alloc+init"); \
return nil; \
} \
- (id)retain { \
return self; \
} \
- (NSUInteger)retainCount { \
return NSUIntegerMax; \
} \
- (void)release { \
} \
- (id)autorelease { \
return self; \
} \
- (id)copyWithZone:(NSZone *)zone { \
return self; \
} \
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMObjectSingleton.h | Objective-C | bsd | 3,411 |
//
// GTMNSDictionary+URLArguments.h
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
/// Utility for building a URL or POST argument string.
@interface NSDictionary (GTMNSDictionaryURLArgumentsAdditions)
/// Gets a string representation of the dictionary in the form
/// key1=value1&key2&value2&...&keyN=valueN, suitable for use as either
/// URL arguments (after a '?') or POST body. Keys and values will be escaped
/// automatically, so should be unescaped in the dictionary.
- (NSString *)gtm_httpArgumentsString;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSDictionary+URLArguments.h | Objective-C | bsd | 1,122 |
//
// GTMLogger+ASL.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import <asl.h>
#import "GTMLogger.h"
// GTMLogger (GTMLoggerASLAdditions)
//
// Adds a convenience creation method that allows you to get a standard
// GTMLogger object that is configured to write to ASL (Apple System Log) using
// the GTMLogASLWriter (declared below).
//
@interface GTMLogger (GTMLoggerASLAdditions)
// Returns a new autoreleased GTMLogger instance that will log to ASL, using
// the GTMLogStandardFormatter, and the GTMLogLevelFilter filter.
+ (id)standardLoggerWithASL;
@end
@class GTMLoggerASLClient;
// GTMLogASLWriter
//
// A GTMLogWriter implementation that will send log messages to ASL (Apple
// System Log facility). To use with GTMLogger simply set the "writer" for a
// GTMLogger to be an instance of this class. The following example sets the
// shared system logger to lot to ASL.
//
// [[GTMLogger sharedLogger] setWriter:[GTMLogASLWriter aslWriter]];
// GTMLoggerInfo(@"Hi"); // This is sent to ASL
//
// See GTMLogger.h for more details and a higher-level view.
//
@interface GTMLogASLWriter : NSObject <GTMLogWriter> {
@private
__weak Class aslClientClass_;
}
// Returns an autoreleased GTMLogASLWriter instance that uses an instance of
// GTMLoggerASLClient.
+ (id)aslWriter;
// Designated initializer. Uses instances of the specified |clientClass| to talk
// to the ASL system. This method is typically only useful for testing. Users
// should generally NOT use this method to get an instance. Instead, simply use
// the +aslWriter method to obtain an instance.
- (id)initWithClientClass:(Class)clientClass;
@end // GTMLogASLWriter
// Helper class used by GTMLogASLWriter to create an ASL client and write to the
// ASL log. This class is need to make management/cleanup of the aslclient work
// in a multithreaded environment. You'll need one of these GTMLoggerASLClient
// per thread (this is automatically handled by GTMLogASLWriter).
//
// This class should rarely (if EVER) be used directly. It's designed to be used
// internally by GTMLogASLWriter, and by some unit tests. It should not be
// used externally.
@interface GTMLoggerASLClient : NSObject {
@private
aslclient client_;
}
// Sends the given string to ASL at the specified ASL log |level|.
- (void)log:(NSString *)msg level:(int)level;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMLogger+ASL.h | Objective-C | bsd | 2,947 |
//
// GTMGeometryUtils.h
//
// Utilities for geometrical utilities such as conversions
// between different types.
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
enum {
GTMScaleProportionally = 0, // Fit proportionally
GTMScaleToFit, // Forced fit (distort if necessary)
GTMScaleNone // Don't scale (clip)
};
typedef NSUInteger GTMScaling;
enum {
GTMRectAlignCenter = 0,
GTMRectAlignTop,
GTMRectAlignTopLeft,
GTMRectAlignTopRight,
GTMRectAlignLeft,
GTMRectAlignBottom,
GTMRectAlignBottomLeft,
GTMRectAlignBottomRight,
GTMRectAlignRight
};
typedef NSUInteger GTMRectAlignment;
#pragma mark -
#pragma mark CG - Point On Rect
/// Return middle of min X side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of min X side of rect
CG_INLINE CGPoint GTMCGMidMinX(CGRect rect) {
return CGPointMake(CGRectGetMinX(rect), CGRectGetMidY(rect));
}
/// Return middle of max X side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of max X side of rect
CG_INLINE CGPoint GTMCGMidMaxX(CGRect rect) {
return CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect));
}
/// Return middle of max Y side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of max Y side of rect
CG_INLINE CGPoint GTMCGMidMaxY(CGRect rect) {
return CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
}
/// Return middle of min Y side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of min Y side of rect
CG_INLINE CGPoint GTMCGMidMinY(CGRect rect) {
return CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
}
/// Return center of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the center of rect
CG_INLINE CGPoint GTMCGCenter(CGRect rect) {
return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}
#pragma mark -
#pragma mark CG - Rect-Size Conversion
/// Return size of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// size of rectangle
CG_INLINE CGSize GTMCGRectSize(CGRect rect) {
return CGSizeMake(CGRectGetWidth(rect), CGRectGetHeight(rect));
}
/// Return rectangle of size
//
// Args:
// size - size
//
// Returns:
// rectangle of size (origin 0,0)
CG_INLINE CGRect GTMCGRectOfSize(CGSize size) {
return CGRectMake(0.0f, 0.0f, size.width, size.height);
}
#pragma mark -
#pragma mark CG - Rect Scaling and Alignment
/// Scales an CGRect
//
// Args:
// inRect: Rect to scale
// xScale: fraction to scale (1.0 is 100%)
// yScale: fraction to scale (1.0 is 100%)
//
// Returns:
// Converted Rect
CG_INLINE CGRect GTMCGRectScale(CGRect inRect, CGFloat xScale, CGFloat yScale) {
return CGRectMake(inRect.origin.x, inRect.origin.y,
inRect.size.width * xScale, inRect.size.height * yScale);
}
/// Align rectangles
//
// Args:
// alignee - rect to be aligned
// aligner - rect to be aligned from
// alignment - way to align the rectangles
CGRect GTMCGAlignRectangles(CGRect alignee, CGRect aligner,
GTMRectAlignment alignment);
/// Scale rectangle
//
// Args:
// scalee - rect to be scaled
// size - size to scale to
// scaling - way to scale the rectangle
CGRect GTMCGScaleRectangleToSize(CGRect scalee, CGSize size,
GTMScaling scaling);
#pragma mark -
#pragma mark CG - Miscellaneous
/// Calculate the distance between two points.
//
// Args:
// pt1 first point
// pt2 second point
//
// Returns:
// Distance
CG_INLINE CGFloat GTMCGDistanceBetweenPoints(CGPoint pt1, CGPoint pt2) {
CGFloat dX = pt1.x - pt2.x;
CGFloat dY = pt1.y - pt2.y;
#if CGFLOAT_IS_DOUBLE
return sqrt(dX * dX + dY * dY);
#else
return sqrtf(dX * dX + dY * dY);
#endif
}
#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
// iPhone does not have NSTypes defined, only CGTypes. So no NSRect, NSPoint etc.
#pragma mark -
// All of the conversion routines below are basically copied from the
// NSGeometry header in the 10.5 sdk.
#pragma mark NS <-> CG Point Conversion
/// Quickly convert from a CGPoint to a NSPoint.
//
/// CGPoints are relative to 0,0 in lower left;
/// NSPoints are relative to 0,0 in lower left
//
// Args:
// inPoint: CGPoint to convert
//
// Returns:
// Converted NSPoint
CG_INLINE NSPoint GTMCGPointToNSPoint(CGPoint inPoint) {
_GTMCompileAssert(sizeof(NSPoint) == sizeof(CGPoint), NSPoint_and_CGPoint_must_be_the_same_size);
union convertUnion {NSPoint ns; CGPoint cg;};
return ((union convertUnion *)&inPoint)->ns;
}
/// Quickly convert from a NSPoint to a CGPoint.
//
/// CGPoints are relative to 0,0 in lower left;
/// NSPoints are relative to 0,0 in lower left
//
// Args:
// inPoint: NSPoint to convert
//
// Returns:
// Converted CGPoint
CG_INLINE CGPoint GTMNSPointToCGPoint(NSPoint inPoint) {
_GTMCompileAssert(sizeof(NSPoint) == sizeof(CGPoint), NSPoint_and_CGPoint_must_be_the_same_size);
union convertUnion {NSPoint ns; CGPoint cg;};
return ((union convertUnion *)&inPoint)->cg;
}
#pragma mark -
#pragma mark NS <-> CG Rect Conversion
/// Convert from a CGRect to a NSRect.
//
/// NSRect are relative to 0,0 in lower left;
/// CGRect are relative to 0,0 in lower left
//
// Args:
// inRect: CGRect to convert
//
// Returns:
// Converted NSRect
CG_INLINE NSRect GTMCGRectToNSRect(CGRect inRect) {
_GTMCompileAssert(sizeof(NSRect) == sizeof(CGRect), NSRect_and_CGRect_must_be_the_same_size);
union convertUnion {NSRect ns; CGRect cg;};
return ((union convertUnion *)&inRect)->ns;
}
/// Convert from a NSRect to a CGRect.
//
/// NSRect are relative to 0,0 in lower left;
/// CGRect are relative to 0,0 in lower left
//
// Args:
// inRect: NSRect to convert
//
// Returns:
// Converted CGRect
CG_INLINE CGRect GTMNSRectToCGRect(NSRect inRect) {
_GTMCompileAssert(sizeof(NSRect) == sizeof(CGRect), NSRect_and_CGRect_must_be_the_same_size);
union convertUnion {NSRect ns; CGRect cg;};
return ((union convertUnion *)&inRect)->cg;
}
#pragma mark -
#pragma mark NS <-> CG Size Conversion
/// Convert from a CGSize to an NSSize.
//
// Args:
// inSize: CGSize to convert
//
// Returns:
// Converted NSSize
CG_INLINE NSSize GTMCGSizeToNSSize(CGSize inSize) {
_GTMCompileAssert(sizeof(NSSize) == sizeof(CGSize), NSSize_and_CGSize_must_be_the_same_size);
union convertUnion {NSSize ns; CGSize cg;};
return ((union convertUnion *)&inSize)->ns;
}
/// Convert from a NSSize to a CGSize.
//
// Args:
// inSize: NSSize to convert
//
// Returns:
// Converted CGSize
CG_INLINE CGSize GTMNSSizeToCGSize(NSSize inSize) {
_GTMCompileAssert(sizeof(NSSize) == sizeof(CGSize), NSSize_and_CGSize_must_be_the_same_size);
union convertUnion {NSSize ns; CGSize cg;};
return ((union convertUnion *)&inSize)->cg;
}
#pragma mark -
#pragma mark NS - Point On Rect
/// Return middle of min X side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of min X side of rect
CG_INLINE NSPoint GTMNSMidMinX(NSRect rect) {
return NSMakePoint(NSMinX(rect), NSMidY(rect));
}
/// Return middle of max X side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of max X side of rect
CG_INLINE NSPoint GTMNSMidMaxX(NSRect rect) {
return NSMakePoint(NSMaxX(rect), NSMidY(rect));
}
/// Return middle of max Y side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of max Y side of rect
CG_INLINE NSPoint GTMNSMidMaxY(NSRect rect) {
return NSMakePoint(NSMidX(rect), NSMaxY(rect));
}
/// Return middle of min Y side of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the middle of min Y side of rect
CG_INLINE NSPoint GTMNSMidMinY(NSRect rect) {
return NSMakePoint(NSMidX(rect), NSMinY(rect));
}
/// Return center of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// point located in the center of rect
CG_INLINE NSPoint GTMNSCenter(NSRect rect) {
return NSMakePoint(NSMidX(rect), NSMidY(rect));
}
#pragma mark -
#pragma mark NS - Rect-Size Conversion
/// Return size of rectangle
//
// Args:
// rect - rectangle
//
// Returns:
// size of rectangle
CG_INLINE NSSize GTMNSRectSize(NSRect rect) {
return NSMakeSize(NSWidth(rect), NSHeight(rect));
}
/// Return rectangle of size
//
// Args:
// size - size
//
// Returns:
// rectangle of size (origin 0,0)
CG_INLINE NSRect GTMNSRectOfSize(NSSize size) {
return NSMakeRect(0.0f, 0.0f, size.width, size.height);
}
#pragma mark -
#pragma mark NS - Rect Scaling and Alignment
/// Scales an NSRect
//
// Args:
// inRect: Rect to scale
// xScale: fraction to scale (1.0 is 100%)
// yScale: fraction to scale (1.0 is 100%)
//
// Returns:
// Converted Rect
CG_INLINE NSRect GTMNSRectScale(NSRect inRect, CGFloat xScale, CGFloat yScale) {
return NSMakeRect(inRect.origin.x, inRect.origin.y,
inRect.size.width * xScale, inRect.size.height * yScale);
}
/// Align rectangles
//
// Args:
// alignee - rect to be aligned
// aligner - rect to be aligned from
CG_INLINE NSRect GTMNSAlignRectangles(NSRect alignee, NSRect aligner,
GTMRectAlignment alignment) {
return GTMCGRectToNSRect(GTMCGAlignRectangles(GTMNSRectToCGRect(alignee),
GTMNSRectToCGRect(aligner),
alignment));
}
/// Scale rectangle
//
// Args:
// scalee - rect to be scaled
// size - size to scale to
// scaling - way to scale the rectangle
CG_INLINE NSRect GTMNSScaleRectangleToSize(NSRect scalee, NSSize size,
GTMScaling scaling) {
return GTMCGRectToNSRect(GTMCGScaleRectangleToSize(GTMNSRectToCGRect(scalee),
GTMNSSizeToCGSize(size),
scaling));
}
#pragma mark -
#pragma mark NS - Miscellaneous
/// Calculate the distance between two points.
//
// Args:
// pt1 first point
// pt2 second point
//
// Returns:
// Distance
CG_INLINE CGFloat GTMNSDistanceBetweenPoints(NSPoint pt1, NSPoint pt2) {
return GTMCGDistanceBetweenPoints(GTMNSPointToCGPoint(pt1),
GTMNSPointToCGPoint(pt2));
}
#endif // (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMGeometryUtils.h | Objective-C | bsd | 11,298 |
//
// GTMGeometryUtilsTest.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMSenTestCase.h"
#import "GTMGeometryUtils.h"
@interface GTMGeometryUtilsTest : GTMTestCase
@end
@implementation GTMGeometryUtilsTest
#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
- (void)testGTMCGPointToNSPoint {
CGPoint cgPoint = CGPointMake(15.1,6.2);
NSPoint nsPoint = GTMCGPointToNSPoint(cgPoint);
STAssertTrue(CGPointEqualToPoint(*(CGPoint*)&nsPoint, cgPoint), nil);
}
- (void)testGTMNSPointToCGPoint {
NSPoint nsPoint = NSMakePoint(10.2,1.5);
CGPoint cgPoint = GTMNSPointToCGPoint(nsPoint);
STAssertTrue(CGPointEqualToPoint(cgPoint, *(CGPoint*)&nsPoint), nil);
}
- (void)testGTMCGRectToNSRect {
CGRect cgRect = CGRectMake(1.5,2.4,10.6,11.7);
NSRect nsRect = GTMCGRectToNSRect(cgRect);
STAssertTrue(CGRectEqualToRect(cgRect, *(CGRect*)&nsRect), nil);
}
- (void)testGTMNSRectToCGRect {
NSRect nsRect = NSMakeRect(4.6,3.2,22.1,45.0);
CGRect cgRect = GTMNSRectToCGRect(nsRect);
STAssertTrue(CGRectEqualToRect(cgRect, *(CGRect*)&nsRect), nil);
}
- (void)testGTMCGSizeToNSSize {
CGSize cgSize = {5,6};
NSSize nsSize = GTMCGSizeToNSSize(cgSize);
STAssertTrue(CGSizeEqualToSize(cgSize, *(CGSize*)&nsSize), nil);
}
- (void)testGTMNSSizeToCGSize {
NSSize nsSize = {22,15};
CGSize cgSize = GTMNSSizeToCGSize(nsSize);
STAssertTrue(CGSizeEqualToSize(cgSize, *(CGSize*)&nsSize), nil);
}
- (void)testGTMNSPointsOnRect {
NSRect rect = NSMakeRect(0, 0, 2, 2);
NSPoint point = GTMNSMidMinX(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)1.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)0.0, (CGFloat)0.01, nil);
point = GTMNSMidMaxX(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)1.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)2.0, (CGFloat)0.01, nil);
point = GTMNSMidMaxY(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)2.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)1.0, (CGFloat)0.01, nil);
point = GTMNSMidMinY(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)0.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)1.0, (CGFloat)0.01, nil);
}
- (void)testGTMNSRectScaling {
NSRect rect = NSMakeRect(1.0f, 2.0f, 5.0f, 10.0f);
NSRect rect2 = NSMakeRect((CGFloat)1.0, (CGFloat)2.0, (CGFloat)1.0, (CGFloat)12.0);
STAssertEquals(GTMNSRectScale(rect, (CGFloat)0.2, (CGFloat)1.2),
rect2, nil);
}
#endif // #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
- (void)testGTMDistanceBetweenPoints {
CGPoint pt1 = CGPointMake(0, 0);
CGPoint pt2 = CGPointMake(3, 4);
STAssertEquals(GTMCGDistanceBetweenPoints(pt1, pt2), (CGFloat)5.0, nil);
STAssertEquals(GTMCGDistanceBetweenPoints(pt2, pt1), (CGFloat)5.0, nil);
pt1 = CGPointMake(1, 1);
pt2 = CGPointMake(1, 1);
STAssertEquals(GTMCGDistanceBetweenPoints(pt1, pt2), (CGFloat)0.0, nil);
}
- (void)testGTMAlignRectangles {
typedef struct {
CGPoint expectedOrigin;
GTMRectAlignment alignment;
} TestData;
TestData data[] = {
{ {1,2}, GTMRectAlignTop },
{ {0,2}, GTMRectAlignTopLeft },
{ {2,2}, GTMRectAlignTopRight },
{ {0,1}, GTMRectAlignLeft },
{ {1,0}, GTMRectAlignBottom },
{ {0,0}, GTMRectAlignBottomLeft },
{ {2,0}, GTMRectAlignBottomRight },
{ {2,1}, GTMRectAlignRight },
{ {1,1}, GTMRectAlignCenter },
};
CGRect rect1 = CGRectMake(0, 0, 4, 4);
CGRect rect2 = CGRectMake(0, 0, 2, 2);
CGRect expectedRect;
expectedRect.size = CGSizeMake(2, 2);
for (size_t i = 0; i < sizeof(data) / sizeof(TestData); i++) {
expectedRect.origin = data[i].expectedOrigin;
CGRect outRect = GTMCGAlignRectangles(rect2, rect1, data[i].alignment);
STAssertEquals(outRect, expectedRect, nil);
}
}
- (void)testGTMCGPointsOnRect {
CGRect rect = CGRectMake(0, 0, 2, 2);
CGPoint point = GTMCGMidMinX(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)1.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)0.0, (CGFloat)0.01, nil);
point = GTMCGMidMaxX(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)1.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)2.0, (CGFloat)0.01, nil);
point = GTMCGMidMaxY(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)2.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)1.0, (CGFloat)0.01, nil);
point = GTMCGMidMinY(rect);
STAssertEqualsWithAccuracy(point.y, (CGFloat)0.0, (CGFloat)0.01, nil);
STAssertEqualsWithAccuracy(point.x, (CGFloat)1.0, (CGFloat)0.01, nil);
}
- (void)testGTMCGRectScaling {
CGRect rect = CGRectMake(1.0f, 2.0f, 5.0f, 10.0f);
CGRect rect2 = CGRectMake((CGFloat)1.0, (CGFloat)2.0, (CGFloat)1.0, (CGFloat)12.0);
STAssertEquals(GTMCGRectScale(rect, (CGFloat)0.2, (CGFloat)1.2),
rect2, nil);
}
- (void)testGTMScaleRectangleToSize {
CGRect rect = CGRectMake(0.0f, 0.0f, 10.0f, 10.0f);
typedef struct {
CGSize size_;
CGSize newSize_;
} Test;
Test tests[] = {
{ { 5.0, 10.0 }, { 5.0, 5.0 } },
{ { 10.0, 5.0 }, { 5.0, 5.0 } },
{ { 10.0, 10.0 }, { 10.0, 10.0 } },
{ { 11.0, 11.0, }, { 10.0, 10.0 } },
{ { 5.0, 2.0 }, { 2.0, 2.0 } },
{ { 2.0, 5.0 }, { 2.0, 2.0 } },
{ { 2.0, 2.0 }, { 2.0, 2.0 } },
{ { 0.0, 10.0 }, { 0.0, 0.0 } }
};
for (size_t i = 0; i < sizeof(tests) / sizeof(Test); ++i) {
CGRect result = GTMCGScaleRectangleToSize(rect, tests[i].size_,
GTMScaleProportionally);
STAssertEquals(result, GTMCGRectOfSize(tests[i].newSize_), @"failed on test %z", i);
}
CGRect result = GTMCGScaleRectangleToSize(CGRectZero, tests[0].size_,
GTMScaleProportionally);
STAssertEquals(result, CGRectZero, nil);
result = GTMCGScaleRectangleToSize(rect, tests[0].size_,
GTMScaleToFit);
STAssertEquals(result, GTMCGRectOfSize(tests[0].size_), nil);
result = GTMCGScaleRectangleToSize(rect, tests[0].size_,
GTMScaleNone);
STAssertEquals(result, rect, nil);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMGeometryUtilsTest.m | Objective-C | bsd | 6,789 |
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
This is a simple test page
</body>
</html>
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/TestData/GTMHTTPFetcherTestPage.html | HTML | bsd | 208 |
//
// NSAppleEventDescriptor+Handler.m
//
// Copyright 2008 Google Inc.
//
// 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.
//
#import "GTMNSAppleEventDescriptor+Handler.h"
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMMethodCheck.h"
#import <Carbon/Carbon.h>
@implementation NSAppleEventDescriptor (GTMAppleEventDescriptorHandlerAdditions)
GTM_METHOD_CHECK(NSProcessInfo, gtm_appleEventDescriptor); // COV_NF_LINE
+ (id)gtm_descriptorWithPositionalHandler:(NSString*)handler
parametersArray:(NSArray*)params {
return [[[self alloc] gtm_initWithPositionalHandler:handler
parametersArray:params] autorelease];
}
+ (id)gtm_descriptorWithPositionalHandler:(NSString*)handler
parametersDescriptor:(NSAppleEventDescriptor*)params {
return [[[self alloc] gtm_initWithPositionalHandler:handler
parametersDescriptor:params] autorelease];
}
+ (id)gtm_descriptorWithLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count {
return [[[self alloc] gtm_initWithLabeledHandler:handler
labels:labels
parameters:params
count:count] autorelease];
}
- (id)gtm_initWithPositionalHandler:(NSString*)handler
parametersArray:(NSArray*)params {
return [self gtm_initWithPositionalHandler:handler
parametersDescriptor:[params gtm_appleEventDescriptor]];
}
- (id)gtm_initWithPositionalHandler:(NSString*)handler
parametersDescriptor:(NSAppleEventDescriptor*)params {
if ((self = [self initWithEventClass:kASAppleScriptSuite
eventID:kASSubroutineEvent
targetDescriptor:[[NSProcessInfo processInfo] gtm_appleEventDescriptor]
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID])) {
// Create an NSAppleEventDescriptor with the method handler. Note that the
// name must be lowercase (even if it is uppercase in AppleScript).
// http://developer.apple.com/qa/qa2001/qa1111.html
// has details.
handler = [handler lowercaseString];
if (!handler) {
[self release];
return nil;
}
NSAppleEventDescriptor *handlerDesc
= [NSAppleEventDescriptor descriptorWithString:handler];
[self setParamDescriptor:handlerDesc forKeyword:keyASSubroutineName];
if (params) {
[self setParamDescriptor:params forKeyword:keyDirectObject];
}
}
return self;
}
- (id)gtm_initWithLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count {
if ((self = [self initWithEventClass:kASAppleScriptSuite
eventID:kASSubroutineEvent
targetDescriptor:[[NSProcessInfo processInfo] gtm_appleEventDescriptor]
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID])) {
if (!handler) {
[self release];
return nil;
}
// Create an NSAppleEventDescriptor with the method handler. Note that the
// name must be lowercase (even if it is uppercase in AppleScript).
NSAppleEventDescriptor *handlerDesc
= [NSAppleEventDescriptor descriptorWithString:[handler lowercaseString]];
[self setParamDescriptor:handlerDesc forKeyword:keyASSubroutineName];
for (NSUInteger i = 0; i < count; i++) {
NSAppleEventDescriptor *paramDesc = [params[i] gtm_appleEventDescriptor];
if(labels[i] == keyASPrepositionGiven) {
if (![params[i] isKindOfClass:[NSDictionary class]]) {
_GTMDevLog(@"Must pass in dictionary for keyASPrepositionGiven "
"(got %@)", params[i]);
[self release];
self = nil;
break;
}
NSAppleEventDescriptor *userDesc
= [paramDesc descriptorForKeyword:keyASUserRecordFields];
if (!userDesc) {
_GTMDevLog(@"Dictionary for keyASPrepositionGiven must be a user "
"record field dictionary (got %@)", params[i]);
[self release];
self = nil;
break;
}
[self setParamDescriptor:userDesc
forKeyword:keyASUserRecordFields];
} else {
[self setParamDescriptor:paramDesc
forKeyword:labels[i]];
}
}
}
return self;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+Handler.m | Objective-C | bsd | 5,289 |
//
// GTMNSString+FindFolder.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSString+FindFolder.h"
#import "GTMGarbageCollection.h"
@implementation NSString (GTMStringFindFolderAdditions)
+ (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
inDomain:(short)theDomain
doCreate:(BOOL)doCreate {
NSString* folderPath = nil;
FSRef folderRef;
OSErr err = FSFindFolder(theDomain, theFolderType, doCreate, &folderRef);
if (err == noErr) {
CFURLRef folderURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault,
&folderRef);
if (folderURL) {
folderPath = GTMCFAutorelease(CFURLCopyFileSystemPath(folderURL,
kCFURLPOSIXPathStyle));
CFRelease(folderURL);
}
}
return folderPath;
}
+ (NSString *)gtm_stringWithPathForFolder:(OSType)theFolderType
subfolderName:(NSString *)subfolderName
inDomain:(short)theDomain
doCreate:(BOOL)doCreate {
NSString *resultPath = nil;
NSString *subdirPath = nil;
NSString *parentFolderPath = [self gtm_stringWithPathForFolder:theFolderType
inDomain:theDomain
doCreate:doCreate];
if (parentFolderPath) {
// find the path to the subdirectory
subdirPath = [parentFolderPath stringByAppendingPathComponent:subfolderName];
NSFileManager* fileMgr = [NSFileManager defaultManager];
BOOL isDir = NO;
if ([fileMgr fileExistsAtPath:subdirPath isDirectory:&isDir] && isDir) {
// it already exists
resultPath = subdirPath;
} else if (doCreate) {
// create the subdirectory with the parent folder's attributes
NSDictionary* attrs = [fileMgr fileAttributesAtPath:parentFolderPath
traverseLink:YES];
if ([fileMgr createDirectoryAtPath:subdirPath
attributes:attrs]) {
resultPath = subdirPath;
}
}
}
return resultPath;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+FindFolder.m | Objective-C | bsd | 2,825 |
//
// GTMBase64.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMBase64.h"
#import "GTMDefines.h"
static const char *kBase64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char *kWebSafeBase64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static const char kBase64PaddingChar = '=';
static const char kBase64InvalidChar = 99;
static const char kBase64DecodeChars[] = {
// This array was generated by the following code:
// #include <sys/time.h>
// #include <stdlib.h>
// #include <string.h>
// main()
// {
// static const char Base64[] =
// "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// char *pos;
// int idx, i, j;
// printf(" ");
// for (i = 0; i < 255; i += 8) {
// for (j = i; j < i + 8; j++) {
// pos = strchr(Base64, j);
// if ((pos == NULL) || (j == 0))
// idx = 99;
// else
// idx = pos - Base64;
// if (idx == 99)
// printf(" %2d, ", idx);
// else
// printf(" %2d/*%c*/,", idx, j);
// }
// printf("\n ");
// }
// }
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 62/*+*/, 99, 99, 99, 63/*/ */,
52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
60/*8*/, 61/*9*/, 99, 99, 99, 99, 99, 99,
99, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
23/*X*/, 24/*Y*/, 25/*Z*/, 99, 99, 99, 99, 99,
99, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
49/*x*/, 50/*y*/, 51/*z*/, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
static const char kWebSafeBase64DecodeChars[] = {
// This array was generated by the following code:
// #include <sys/time.h>
// #include <stdlib.h>
// #include <string.h>
// main()
// {
// static const char Base64[] =
// "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
// char *pos;
// int idx, i, j;
// printf(" ");
// for (i = 0; i < 255; i += 8) {
// for (j = i; j < i + 8; j++) {
// pos = strchr(Base64, j);
// if ((pos == NULL) || (j == 0))
// idx = 99;
// else
// idx = pos - Base64;
// if (idx == 99)
// printf(" %2d, ", idx);
// else
// printf(" %2d/*%c*/,", idx, j);
// }
// printf("\n ");
// }
// }
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 62/*-*/, 99, 99,
52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
60/*8*/, 61/*9*/, 99, 99, 99, 99, 99, 99,
99, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
7/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
23/*X*/, 24/*Y*/, 25/*Z*/, 99, 99, 99, 99, 63/*_*/,
99, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
49/*x*/, 50/*y*/, 51/*z*/, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
// Tests a charact to see if it's a whitespace character.
//
// Returns:
// YES if the character is a whitespace character.
// NO if the character is not a whitespace character.
//
FOUNDATION_STATIC_INLINE BOOL IsSpace(unsigned char c) {
// we use our own mapping here because we don't want anything w/ locale
// support.
static BOOL kSpaces[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // 0-9
1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 10-19
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20-29
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, // 30-39
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40-49
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 50-59
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60-69
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 70-79
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80-89
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90-99
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100-109
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 110-119
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 120-129
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130-139
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140-149
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150-159
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-169
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170-179
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180-189
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190-199
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200-209
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210-219
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220-229
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230-239
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240-249
0, 0, 0, 0, 0, 1, // 250-255
};
return kSpaces[c];
}
// Calculate how long the data will be once it's base64 encoded.
//
// Returns:
// The guessed encoded length for a source length
//
FOUNDATION_STATIC_INLINE NSUInteger CalcEncodedLength(NSUInteger srcLen,
BOOL padded) {
NSUInteger intermediate_result = 8 * srcLen + 5;
NSUInteger len = intermediate_result / 6;
if (padded) {
len = ((len + 3) / 4) * 4;
}
return len;
}
// Tries to calculate how long the data will be once it's base64 decoded.
// Unlinke the above, this is always an upperbound, since the source data
// could have spaces and might end with the padding characters on them.
//
// Returns:
// The guessed decoded length for a source length
//
FOUNDATION_STATIC_INLINE NSUInteger GuessDecodedLength(NSUInteger srcLen) {
return (srcLen + 3) / 4 * 3;
}
@interface GTMBase64 (PrivateMethods)
+(NSData *)baseEncode:(const void *)bytes
length:(NSUInteger)length
charset:(const char *)charset
padded:(BOOL)padded;
+(NSData *)baseDecode:(const void *)bytes
length:(NSUInteger)length
charset:(const char*)charset
requirePadding:(BOOL)requirePadding;
+(NSUInteger)baseEncode:(const char *)srcBytes
srcLen:(NSUInteger)srcLen
destBytes:(char *)destBytes
destLen:(NSUInteger)destLen
charset:(const char *)charset
padded:(BOOL)padded;
+(NSUInteger)baseDecode:(const char *)srcBytes
srcLen:(NSUInteger)srcLen
destBytes:(char *)destBytes
destLen:(NSUInteger)destLen
charset:(const char *)charset
requirePadding:(BOOL)requirePadding;
@end
@implementation GTMBase64
//
// Standard Base64 (RFC) handling
//
+(NSData *)encodeData:(NSData *)data {
return [self baseEncode:[data bytes]
length:[data length]
charset:kBase64EncodeChars
padded:YES];
}
+(NSData *)decodeData:(NSData *)data {
return [self baseDecode:[data bytes]
length:[data length]
charset:kBase64DecodeChars
requirePadding:YES];
}
+(NSData *)encodeBytes:(const void *)bytes length:(NSUInteger)length {
return [self baseEncode:bytes
length:length
charset:kBase64EncodeChars
padded:YES];
}
+(NSData *)decodeBytes:(const void *)bytes length:(NSUInteger)length {
return [self baseDecode:bytes
length:length
charset:kBase64DecodeChars
requirePadding:YES];
}
+(NSString *)stringByEncodingData:(NSData *)data {
NSString *result = nil;
NSData *converted = [self baseEncode:[data bytes]
length:[data length]
charset:kBase64EncodeChars
padded:YES];
if (converted) {
result = [[[NSString alloc] initWithData:converted
encoding:NSASCIIStringEncoding] autorelease];
}
return result;
}
+(NSString *)stringByEncodingBytes:(const void *)bytes length:(NSUInteger)length {
NSString *result = nil;
NSData *converted = [self baseEncode:bytes
length:length
charset:kBase64EncodeChars
padded:YES];
if (converted) {
result = [[[NSString alloc] initWithData:converted
encoding:NSASCIIStringEncoding] autorelease];
}
return result;
}
+(NSData *)decodeString:(NSString *)string {
NSData *result = nil;
NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
if (data) {
result = [self baseDecode:[data bytes]
length:[data length]
charset:kBase64DecodeChars
requirePadding:YES];
}
return result;
}
//
// Modified Base64 encoding so the results can go onto urls.
//
// The changes are in the characters generated and also the result isn't
// padded to a multiple of 4.
// Must use the matching call to encode/decode, won't interop with the
// RFC versions.
//
+(NSData *)webSafeEncodeData:(NSData *)data
padded:(BOOL)padded {
return [self baseEncode:[data bytes]
length:[data length]
charset:kWebSafeBase64EncodeChars
padded:padded];
}
+(NSData *)webSafeDecodeData:(NSData *)data {
return [self baseDecode:[data bytes]
length:[data length]
charset:kWebSafeBase64DecodeChars
requirePadding:NO];
}
+(NSData *)webSafeEncodeBytes:(const void *)bytes
length:(NSUInteger)length
padded:(BOOL)padded {
return [self baseEncode:bytes
length:length
charset:kWebSafeBase64EncodeChars
padded:padded];
}
+(NSData *)webSafeDecodeBytes:(const void *)bytes length:(NSUInteger)length {
return [self baseDecode:bytes
length:length
charset:kWebSafeBase64DecodeChars
requirePadding:NO];
}
+(NSString *)stringByWebSafeEncodingData:(NSData *)data
padded:(BOOL)padded {
NSString *result = nil;
NSData *converted = [self baseEncode:[data bytes]
length:[data length]
charset:kWebSafeBase64EncodeChars
padded:padded];
if (converted) {
result = [[[NSString alloc] initWithData:converted
encoding:NSASCIIStringEncoding] autorelease];
}
return result;
}
+(NSString *)stringByWebSafeEncodingBytes:(const void *)bytes
length:(NSUInteger)length
padded:(BOOL)padded {
NSString *result = nil;
NSData *converted = [self baseEncode:bytes
length:length
charset:kWebSafeBase64EncodeChars
padded:padded];
if (converted) {
result = [[[NSString alloc] initWithData:converted
encoding:NSASCIIStringEncoding] autorelease];
}
return result;
}
+(NSData *)webSafeDecodeString:(NSString *)string {
NSData *result = nil;
NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding];
if (data) {
result = [self baseDecode:[data bytes]
length:[data length]
charset:kWebSafeBase64DecodeChars
requirePadding:NO];
}
return result;
}
@end
@implementation GTMBase64 (PrivateMethods)
//
// baseEncode:length:charset:padded:
//
// Does the common lifting of creating the dest NSData. it creates & sizes the
// data for the results. |charset| is the characters to use for the encoding
// of the data. |padding| controls if the encoded data should be padded to a
// multiple of 4.
//
// Returns:
// an autorelease NSData with the encoded data, nil if any error.
//
+(NSData *)baseEncode:(const void *)bytes
length:(NSUInteger)length
charset:(const char *)charset
padded:(BOOL)padded {
// how big could it be?
NSUInteger maxLength = CalcEncodedLength(length, padded);
// make space
NSMutableData *result = [NSMutableData data];
[result setLength:maxLength];
// do it
NSUInteger finalLength = [self baseEncode:bytes
srcLen:length
destBytes:[result mutableBytes]
destLen:[result length]
charset:charset
padded:padded];
if (finalLength) {
_GTMDevAssert(finalLength == maxLength, @"how did we calc the length wrong?");
} else {
// shouldn't happen, this means we ran out of space
result = nil;
}
return result;
}
//
// baseDecode:length:charset:requirePadding:
//
// Does the common lifting of creating the dest NSData. it creates & sizes the
// data for the results. |charset| is the characters to use for the decoding
// of the data.
//
// Returns:
// an autorelease NSData with the decoded data, nil if any error.
//
//
+(NSData *)baseDecode:(const void *)bytes
length:(NSUInteger)length
charset:(const char *)charset
requirePadding:(BOOL)requirePadding {
// could try to calculate what it will end up as
NSUInteger maxLength = GuessDecodedLength(length);
// make space
NSMutableData *result = [NSMutableData data];
[result setLength:maxLength];
// do it
NSUInteger finalLength = [self baseDecode:bytes
srcLen:length
destBytes:[result mutableBytes]
destLen:[result length]
charset:charset
requirePadding:requirePadding];
if (finalLength) {
if (finalLength != maxLength) {
// resize down to how big it was
[result setLength:finalLength];
}
} else {
// either an error in the args, or we ran out of space
result = nil;
}
return result;
}
//
// baseEncode:srcLen:destBytes:destLen:charset:padded:
//
// Encodes the buffer into the larger. returns the length of the encoded
// data, or zero for an error.
// |charset| is the characters to use for the encoding
// |padded| tells if the result should be padded to a multiple of 4.
//
// Returns:
// the length of the encoded data. zero if any error.
//
+(NSUInteger)baseEncode:(const char *)srcBytes
srcLen:(NSUInteger)srcLen
destBytes:(char *)destBytes
destLen:(NSUInteger)destLen
charset:(const char *)charset
padded:(BOOL)padded {
if (!srcLen || !destLen || !srcBytes || !destBytes) {
return 0;
}
char *curDest = destBytes;
const unsigned char *curSrc = (const unsigned char *)(srcBytes);
// Three bytes of data encodes to four characters of cyphertext.
// So we can pump through three-byte chunks atomically.
while (srcLen > 2) {
// space?
_GTMDevAssert(destLen >= 4, @"our calc for encoded length was wrong");
curDest[0] = charset[curSrc[0] >> 2];
curDest[1] = charset[((curSrc[0] & 0x03) << 4) + (curSrc[1] >> 4)];
curDest[2] = charset[((curSrc[1] & 0x0f) << 2) + (curSrc[2] >> 6)];
curDest[3] = charset[curSrc[2] & 0x3f];
curDest += 4;
curSrc += 3;
srcLen -= 3;
destLen -= 4;
}
// now deal with the tail (<=2 bytes)
switch (srcLen) {
case 0:
// Nothing left; nothing more to do.
break;
case 1:
// One byte left: this encodes to two characters, and (optionally)
// two pad characters to round out the four-character cypherblock.
_GTMDevAssert(destLen >= 2, @"our calc for encoded length was wrong");
curDest[0] = charset[curSrc[0] >> 2];
curDest[1] = charset[(curSrc[0] & 0x03) << 4];
curDest += 2;
destLen -= 2;
if (padded) {
_GTMDevAssert(destLen >= 2, @"our calc for encoded length was wrong");
curDest[0] = kBase64PaddingChar;
curDest[1] = kBase64PaddingChar;
curDest += 2;
destLen -= 2;
}
break;
case 2:
// Two bytes left: this encodes to three characters, and (optionally)
// one pad character to round out the four-character cypherblock.
_GTMDevAssert(destLen >= 3, @"our calc for encoded length was wrong");
curDest[0] = charset[curSrc[0] >> 2];
curDest[1] = charset[((curSrc[0] & 0x03) << 4) + (curSrc[1] >> 4)];
curDest[2] = charset[(curSrc[1] & 0x0f) << 2];
curDest += 3;
destLen -= 3;
if (padded) {
_GTMDevAssert(destLen >= 1, @"our calc for encoded length was wrong");
curDest[0] = kBase64PaddingChar;
curDest += 1;
destLen -= 1;
}
break;
}
// return the length
return (curDest - destBytes);
}
//
// baseDecode:srcLen:destBytes:destLen:charset:requirePadding:
//
// Decodes the buffer into the larger. returns the length of the decoded
// data, or zero for an error.
// |charset| is the character decoding buffer to use
//
// Returns:
// the length of the encoded data. zero if any error.
//
+(NSUInteger)baseDecode:(const char *)srcBytes
srcLen:(NSUInteger)srcLen
destBytes:(char *)destBytes
destLen:(NSUInteger)destLen
charset:(const char *)charset
requirePadding:(BOOL)requirePadding {
if (!srcLen || !destLen || !srcBytes || !destBytes) {
return 0;
}
int decode;
NSUInteger destIndex = 0;
int state = 0;
char ch = 0;
while (srcLen-- && (ch = *srcBytes++) != 0) {
if (IsSpace(ch)) // Skip whitespace
continue;
if (ch == kBase64PaddingChar)
break;
decode = charset[(unsigned int)ch];
if (decode == kBase64InvalidChar)
return 0;
// Four cyphertext characters decode to three bytes.
// Therefore we can be in one of four states.
switch (state) {
case 0:
// We're at the beginning of a four-character cyphertext block.
// This sets the high six bits of the first byte of the
// plaintext block.
_GTMDevAssert(destIndex < destLen, @"our calc for decoded length was wrong");
destBytes[destIndex] = decode << 2;
state = 1;
break;
case 1:
// We're one character into a four-character cyphertext block.
// This sets the low two bits of the first plaintext byte,
// and the high four bits of the second plaintext byte.
_GTMDevAssert((destIndex+1) < destLen, @"our calc for decoded length was wrong");
destBytes[destIndex] |= decode >> 4;
destBytes[destIndex+1] = (decode & 0x0f) << 4;
destIndex++;
state = 2;
break;
case 2:
// We're two characters into a four-character cyphertext block.
// This sets the low four bits of the second plaintext
// byte, and the high two bits of the third plaintext byte.
// However, if this is the end of data, and those two
// bits are zero, it could be that those two bits are
// leftovers from the encoding of data that had a length
// of two mod three.
_GTMDevAssert((destIndex+1) < destLen, @"our calc for decoded length was wrong");
destBytes[destIndex] |= decode >> 2;
destBytes[destIndex+1] = (decode & 0x03) << 6;
destIndex++;
state = 3;
break;
case 3:
// We're at the last character of a four-character cyphertext block.
// This sets the low six bits of the third plaintext byte.
_GTMDevAssert(destIndex < destLen, @"our calc for decoded length was wrong");
destBytes[destIndex] |= decode;
destIndex++;
state = 0;
break;
}
}
// We are done decoding Base-64 chars. Let's see if we ended
// on a byte boundary, and/or with erroneous trailing characters.
if (ch == kBase64PaddingChar) { // We got a pad char
if ((state == 0) || (state == 1)) {
return 0; // Invalid '=' in first or second position
}
if (srcLen == 0) {
if (state == 2) { // We run out of input but we still need another '='
return 0;
}
// Otherwise, we are in state 3 and only need this '='
} else {
if (state == 2) { // need another '='
while ((ch = *srcBytes++) && (srcLen-- > 0)) {
if (!IsSpace(ch))
break;
}
if (ch != kBase64PaddingChar) {
return 0;
}
}
// state = 1 or 2, check if all remain padding is space
while ((ch = *srcBytes++) && (srcLen-- > 0)) {
if (!IsSpace(ch)) {
return 0;
}
}
}
} else {
// We ended by seeing the end of the string.
if (requirePadding) {
// If we require padding, then anything but state 0 is an error.
if (state != 0) {
return 0;
}
} else {
// Make sure we have no partial bytes lying around. Note that we do not
// require trailing '=', so states 2 and 3 are okay too.
if (state == 1) {
return 0;
}
}
}
// If then next piece of output was valid and got written to it means we got a
// very carefully crafted input that appeared valid but contains some trailing
// bits past the real length, so just toss the thing.
if ((destIndex < destLen) &&
(destBytes[destIndex] != 0)) {
return 0;
}
return destIndex;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMBase64.m | Objective-C | bsd | 25,381 |
//
// GTMHTTPFetcher.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#define GTMHTTPFETCHER_DEFINE_GLOBALS 1
#import "GTMHTTPFetcher.h"
#import "GTMDebugSelectorValidation.h"
@interface GTMHTTPFetcher (GTMHTTPFetcherLoggingInternal)
- (void)logFetchWithError:(NSError *)error;
- (void)logCapturePostStream;
@end
// Make sure that if logging is disabled, the InputStream logging is also
// diabled.
#if !GTM_HTTPFETCHER_ENABLE_LOGGING
# undef GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
# define GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING 0
#endif // GTM_HTTPFETCHER_ENABLE_LOGGING
#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
#import "GTMProgressMonitorInputStream.h"
@interface GTMInputStreamLogger : GTMProgressMonitorInputStream
// GTMInputStreamLogger wraps any NSInputStream used for uploading so we can
// capture a copy of the data for the log
@end
#endif // !GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
@interface NSURLConnection (LeopardMethodsOnTigerBuilds)
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (void)start;
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
@end
#endif
NSString* const kGTMLastModifiedHeader = @"Last-Modified";
NSString* const kGTMIfModifiedSinceHeader = @"If-Modified-Since";
NSMutableArray* gGTMFetcherStaticCookies = nil;
Class gGTMFetcherConnectionClass = nil;
NSArray *gGTMFetcherDefaultRunLoopModes = nil;
const NSTimeInterval kDefaultMaxRetryInterval = 60. * 10.; // 10 minutes
@interface GTMHTTPFetcher (PrivateMethods)
- (void)setCookies:(NSArray *)newCookies
inArray:(NSMutableArray *)cookieStorageArray;
- (NSArray *)cookiesForURL:(NSURL *)theURL inArray:(NSMutableArray *)cookieStorageArray;
- (void)handleCookiesForResponse:(NSURLResponse *)response;
- (BOOL)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error;
- (void)retryTimerFired:(NSTimer *)timer;
- (void)destroyRetryTimer;
- (void)beginRetryTimer;
- (void)primeTimerWithNewTimeInterval:(NSTimeInterval)secs;
- (void)retryFetch;
@end
@implementation GTMHTTPFetcher
+ (GTMHTTPFetcher *)httpFetcherWithRequest:(NSURLRequest *)request {
return [[[GTMHTTPFetcher alloc] initWithRequest:request] autorelease];
}
+ (void)initialize {
if (!gGTMFetcherStaticCookies) {
gGTMFetcherStaticCookies = [[NSMutableArray alloc] init];
}
}
- (id)init {
return [self initWithRequest:nil];
}
- (id)initWithRequest:(NSURLRequest *)request {
if ((self = [super init]) != nil) {
request_ = [request mutableCopy];
[self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic];
}
return self;
}
// TODO: do we need finalize to call stopFetching?
- (void)dealloc {
[self stopFetching]; // releases connection_
[request_ release];
[downloadedData_ release];
[credential_ release];
[proxyCredential_ release];
[postData_ release];
[postStream_ release];
[loggedStreamData_ release];
[response_ release];
[userData_ release];
[runLoopModes_ release];
[fetchHistory_ release];
[self destroyRetryTimer];
[super dealloc];
}
#pragma mark -
// Begin fetching the URL. |delegate| is not retained
// The delegate must provide and implement the finished and failed selectors.
//
// finishedSEL has a signature like:
// - (void)fetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data
// failedSEL has a signature like:
// - (void)fetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error
- (BOOL)beginFetchWithDelegate:(id)delegate
didFinishSelector:(SEL)finishedSEL
didFailSelector:(SEL)failedSEL {
GTMAssertSelectorNilOrImplementedWithArguments(delegate, finishedSEL, @encode(GTMHTTPFetcher *), @encode(NSData *), NULL);
GTMAssertSelectorNilOrImplementedWithArguments(delegate, failedSEL, @encode(GTMHTTPFetcher *), @encode(NSError *), NULL);
GTMAssertSelectorNilOrImplementedWithArguments(delegate, receivedDataSEL_, @encode(GTMHTTPFetcher *), @encode(NSData *), NULL);
GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(delegate, retrySEL_, @encode(BOOL), @encode(GTMHTTPFetcher *), @encode(BOOL), @encode(NSError *), NULL);
if (connection_ != nil) {
_GTMDevAssert(connection_ != nil,
@"fetch object %@ being reused; this should never happen",
self);
goto CannotBeginFetch;
}
if (request_ == nil) {
_GTMDevAssert(request_ != nil, @"beginFetchWithDelegate requires a request");
goto CannotBeginFetch;
}
[downloadedData_ release];
downloadedData_ = nil;
[self setDelegate:delegate];
finishedSEL_ = finishedSEL;
failedSEL_ = failedSEL;
if (postData_ || postStream_) {
if ([request_ HTTPMethod] == nil || [[request_ HTTPMethod] isEqual:@"GET"]) {
[request_ setHTTPMethod:@"POST"];
}
if (postData_) {
[request_ setHTTPBody:postData_];
} else {
// if logging is enabled, it needs a buffer to accumulate data from any
// NSInputStream used for uploading. Logging will wrap the input
// stream with a stream that lets us keep a copy the data being read.
if ([GTMHTTPFetcher isLoggingEnabled] && postStream_ != nil) {
loggedStreamData_ = [[NSMutableData alloc] init];
[self logCapturePostStream];
}
[request_ setHTTPBodyStream:postStream_];
}
}
if (fetchHistory_) {
// If this URL is in the history, set the Last-Modified header field
// if we have a history, we're tracking across fetches, so we don't
// want to pull results from a cache
[request_ setCachePolicy:NSURLRequestReloadIgnoringCacheData];
NSDictionary* lastModifiedDict = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
NSString* urlString = [[request_ URL] absoluteString];
NSString* lastModifiedStr = [lastModifiedDict objectForKey:urlString];
// servers don't want last-modified-ifs on POSTs, so check for a body
if (lastModifiedStr
&& [request_ HTTPBody] == nil
&& [request_ HTTPBodyStream] == nil) {
[request_ addValue:lastModifiedStr forHTTPHeaderField:kGTMIfModifiedSinceHeader];
}
}
// get cookies for this URL from our storage array, if
// we have a storage array
if (cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
NSArray *cookies = [self cookiesForURL:[request_ URL]];
if ([cookies count]) {
NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSString *cookieHeader = [headerFields objectForKey:@"Cookie"]; // key used in header dictionary
if (cookieHeader) {
[request_ addValue:cookieHeader forHTTPHeaderField:@"Cookie"]; // header name
}
}
}
// finally, start the connection
Class connectionClass = [[self class] connectionClass];
NSArray *runLoopModes = nil;
if ([[self class] doesSupportRunLoopModes]) {
// use the connection-specific run loop modes, if they were provided,
// or else use the GTMHTTPFetcher default run loop modes, if any
if (runLoopModes_) {
runLoopModes = runLoopModes_;
} else {
runLoopModes = gGTMFetcherDefaultRunLoopModes;
}
}
if ([runLoopModes count] == 0) {
// if no run loop modes were specified, then we'll start the connection
// on the current run loop in the current mode
connection_ = [[connectionClass connectionWithRequest:request_
delegate:self] retain];
} else {
// schedule on current run loop in the specified modes
connection_ = [[connectionClass alloc] initWithRequest:request_
delegate:self
startImmediately:NO];
for (NSUInteger idx = 0; idx < [runLoopModes count]; idx++) {
NSString *mode = [runLoopModes objectAtIndex:idx];
[connection_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode];
}
[connection_ start];
}
if (!connection_) {
_GTMDevAssert(connection_ != nil,
@"beginFetchWithDelegate could not create a connection");
goto CannotBeginFetch;
}
// we'll retain the delegate only during the outstanding connection (similar
// to what Cocoa does with performSelectorOnMainThread:) since we'd crash
// if the delegate was released in the interim. We don't retain the selector
// at other times, to avoid vicious retain loops. This retain is balanced in
// the -stopFetch method.
[delegate_ retain];
downloadedData_ = [[NSMutableData alloc] init];
return YES;
CannotBeginFetch:
if (failedSEL) {
NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
code:kGTMHTTPFetcherErrorDownloadFailed
userInfo:nil];
[[self retain] autorelease]; // in case the callback releases us
[delegate performSelector:failedSEL_
withObject:self
withObject:error];
}
return NO;
}
// Returns YES if this is in the process of fetching a URL, or waiting to
// retry
- (BOOL)isFetching {
return (connection_ != nil || retryTimer_ != nil);
}
// Returns the status code set in connection:didReceiveResponse:
- (NSInteger)statusCode {
NSInteger statusCode;
if (response_ != nil
&& [response_ respondsToSelector:@selector(statusCode)]) {
statusCode = [(NSHTTPURLResponse *)response_ statusCode];
} else {
// Default to zero, in hopes of hinting "Unknown" (we can't be
// sure that things are OK enough to use 200).
statusCode = 0;
}
return statusCode;
}
// Cancel the fetch of the URL that's currently in progress.
- (void)stopFetching {
[self destroyRetryTimer];
if (connection_) {
// in case cancelling the connection calls this recursively, we want
// to ensure that we'll only release the connection and delegate once,
// so first set connection_ to nil
NSURLConnection* oldConnection = connection_;
connection_ = nil;
// this may be called in a callback from the connection, so use autorelease
[oldConnection cancel];
[oldConnection autorelease];
// balance the retain done when the connection was opened
[delegate_ release];
}
}
- (void)retryFetch {
id holdDelegate = [[delegate_ retain] autorelease];
[self stopFetching];
[self beginFetchWithDelegate:holdDelegate
didFinishSelector:finishedSEL_
didFailSelector:failedSEL_];
}
#pragma mark NSURLConnection Delegate Methods
//
// NSURLConnection Delegate Methods
//
// This method just says "follow all redirects", which _should_ be the default behavior,
// According to file:///Developer/ADC%20Reference%20Library/documentation/Cocoa/Conceptual/URLLoadingSystem
// but the redirects were not being followed until I added this method. May be
// a bug in the NSURLConnection code, or the documentation.
//
// In OS X 10.4.8 and earlier, the redirect request doesn't
// get the original's headers and body. This causes POSTs to fail.
// So we construct a new request, a copy of the original, with overrides from the
// redirect.
//
// Docs say that if redirectResponse is nil, just return the redirectRequest.
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)redirectRequest
redirectResponse:(NSURLResponse *)redirectResponse {
if (redirectRequest && redirectResponse) {
NSMutableURLRequest *newRequest = [[request_ mutableCopy] autorelease];
// copy the URL
NSURL *redirectURL = [redirectRequest URL];
NSURL *url = [newRequest URL];
// disallow scheme changes (say, from https to http)
NSString *redirectScheme = [url scheme];
NSString *newScheme = [redirectURL scheme];
NSString *newResourceSpecifier = [redirectURL resourceSpecifier];
if ([redirectScheme caseInsensitiveCompare:@"http"] == NSOrderedSame
&& newScheme != nil
&& [newScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) {
// allow the change from http to https
redirectScheme = newScheme;
}
NSString *newUrlString = [NSString stringWithFormat:@"%@:%@",
redirectScheme, newResourceSpecifier];
NSURL *newURL = [NSURL URLWithString:newUrlString];
[newRequest setURL:newURL];
// any headers in the redirect override headers in the original.
NSDictionary *redirectHeaders = [redirectRequest allHTTPHeaderFields];
if (redirectHeaders) {
NSEnumerator *enumerator = [redirectHeaders keyEnumerator];
NSString *key;
while (nil != (key = [enumerator nextObject])) {
NSString *value = [redirectHeaders objectForKey:key];
[newRequest setValue:value forHTTPHeaderField:key];
}
}
redirectRequest = newRequest;
// save cookies from the response
[self handleCookiesForResponse:redirectResponse];
// log the response we just received
[self setResponse:redirectResponse];
[self logFetchWithError:nil];
// update the request for future logging
[self setRequest:redirectRequest];
}
return redirectRequest;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// this method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
[downloadedData_ setLength:0];
[self setResponse:response];
// save cookies from the response
[self handleCookiesForResponse:response];
}
// handleCookiesForResponse: handles storage of cookies for responses passed to
// connection:willSendRequest:redirectResponse: and connection:didReceiveResponse:
- (void)handleCookiesForResponse:(NSURLResponse *)response {
if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
// do nothing special for NSURLConnection's default storage mechanism
} else if ([response respondsToSelector:@selector(allHeaderFields)]) {
// grab the cookies from the header as NSHTTPCookies and store them either
// into our static array or into the fetchHistory
NSDictionary *responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];
if (responseHeaderFields) {
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseHeaderFields
forURL:[response URL]];
if ([cookies count] > 0) {
NSMutableArray *cookieArray = nil;
// static cookies are stored in gGTMFetcherStaticCookies; fetchHistory
// cookies are stored in fetchHistory_'s kGTMHTTPFetcherHistoryCookiesKey
if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodStatic) {
cookieArray = gGTMFetcherStaticCookies;
} else if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodFetchHistory
&& fetchHistory_ != nil) {
cookieArray = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryCookiesKey];
if (cookieArray == nil) {
cookieArray = [NSMutableArray array];
[fetchHistory_ setObject:cookieArray forKey:kGTMHTTPFetcherHistoryCookiesKey];
}
}
if (cookieArray) {
@synchronized(cookieArray) {
[self setCookies:cookies inArray:cookieArray];
}
}
}
}
}
}
-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] <= 2) {
NSURLCredential *credential = credential_;
if ([[challenge protectionSpace] isProxy] && proxyCredential_ != nil) {
credential = proxyCredential_;
}
// Here, if credential is still nil, then we *could* try to get it from
// NSURLCredentialStorage's defaultCredentialForProtectionSpace:.
// We don't, because we're assuming:
//
// - for server credentials, we only want ones supplied by the program
// calling http fetcher
// - for proxy credentials, if one were necessary and available in the
// keychain, it would've been found automatically by NSURLConnection
// and this challenge delegate method never would've been called
// anyway
if (credential) {
// try the credential
[[challenge sender] useCredential:credential
forAuthenticationChallenge:challenge];
return;
}
}
// If we don't have credentials, or we've already failed auth 3x...
[[challenge sender] cancelAuthenticationChallenge:challenge];
// report the error, putting the challenge as a value in the userInfo
// dictionary
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:challenge
forKey:kGTMHTTPFetcherErrorChallengeKey];
NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
code:kGTMHTTPFetcherErrorAuthenticationChallengeFailed
userInfo:userInfo];
[self connection:connection didFailWithError:error];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[downloadedData_ appendData:data];
if (receivedDataSEL_) {
[delegate_ performSelector:receivedDataSEL_
withObject:self
withObject:downloadedData_];
}
}
- (void)updateFetchHistory {
if (fetchHistory_) {
NSString* urlString = [[request_ URL] absoluteString];
if ([response_ respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *headers = [(NSHTTPURLResponse *)response_ allHeaderFields];
NSString* lastModifiedStr = [headers objectForKey:kGTMLastModifiedHeader];
// get the dictionary mapping URLs to last-modified dates
NSMutableDictionary* lastModifiedDict = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
if (!lastModifiedDict) {
lastModifiedDict = [NSMutableDictionary dictionary];
[fetchHistory_ setObject:lastModifiedDict forKey:kGTMHTTPFetcherHistoryLastModifiedKey];
}
NSMutableDictionary* datedDataCache = nil;
if (shouldCacheDatedData_) {
// get the dictionary mapping URLs to cached, dated data
datedDataCache = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryDatedDataKey];
if (!datedDataCache) {
datedDataCache = [NSMutableDictionary dictionary];
[fetchHistory_ setObject:datedDataCache forKey:kGTMHTTPFetcherHistoryDatedDataKey];
}
}
NSInteger statusCode = [self statusCode];
if (statusCode != kGTMHTTPFetcherStatusNotModified) {
// save this last modified date string for successful results (<300)
// If there's no last modified string, clear the dictionary
// entry for this URL. Also cache or delete the data, if appropriate
// (when datedDataCache is non-nil.)
if (lastModifiedStr && statusCode < 300) {
[lastModifiedDict setValue:lastModifiedStr forKey:urlString];
[datedDataCache setValue:downloadedData_ forKey:urlString];
} else {
[lastModifiedDict removeObjectForKey:urlString];
[datedDataCache removeObjectForKey:urlString];
}
}
}
}
}
// for error 304's ("Not Modified") where we've cached the data, return status
// 200 ("OK") to the caller (but leave the fetcher status as 304)
// and copy the cached data to downloadedData_.
// For other errors or if there's no cached data, just return the actual status.
- (NSInteger)statusAfterHandlingNotModifiedError {
NSInteger status = [self statusCode];
if (status == kGTMHTTPFetcherStatusNotModified && shouldCacheDatedData_) {
// get the dictionary of URLs and data
NSString* urlString = [[request_ URL] absoluteString];
NSDictionary* datedDataCache = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryDatedDataKey];
NSData* cachedData = [datedDataCache objectForKey:urlString];
if (cachedData) {
// copy our stored data, and forge the status to pass on to the delegate
[downloadedData_ setData:cachedData];
status = 200;
}
}
return status;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self updateFetchHistory];
[[self retain] autorelease]; // in case the callback releases us
[self logFetchWithError:nil];
NSInteger status = [self statusAfterHandlingNotModifiedError];
if (status >= 300) {
if ([self shouldRetryNowForStatus:status error:nil]) {
[self beginRetryTimer];
} else {
// not retrying
// did they want failure notifications?
if (failedSEL_) {
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:downloadedData_
forKey:kGTMHTTPFetcherStatusDataKey];
NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain
code:status
userInfo:userInfo];
[delegate_ performSelector:failedSEL_
withObject:self
withObject:error];
}
// we're done fetching
[self stopFetching];
}
} else if (finishedSEL_) {
// successful http status (under 300)
[delegate_ performSelector:finishedSEL_
withObject:self
withObject:downloadedData_];
[self stopFetching];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self logFetchWithError:error];
if ([self shouldRetryNowForStatus:0 error:error]) {
[self beginRetryTimer];
} else {
if (failedSEL_) {
[[self retain] autorelease]; // in case the callback releases us
[delegate_ performSelector:failedSEL_
withObject:self
withObject:error];
}
[self stopFetching];
}
}
#pragma mark Retries
- (BOOL)isRetryError:(NSError *)error {
struct retryRecord {
NSString *const domain;
int code;
};
struct retryRecord retries[] = {
{ kGTMHTTPFetcherStatusDomain, 408 }, // request timeout
{ kGTMHTTPFetcherStatusDomain, 503 }, // service unavailable
{ kGTMHTTPFetcherStatusDomain, 504 }, // request timeout
{ NSURLErrorDomain, NSURLErrorTimedOut },
{ NSURLErrorDomain, NSURLErrorNetworkConnectionLost },
{ nil, 0 }
};
// NSError's isEqual always returns false for equal but distinct instances
// of NSError, so we have to compare the domain and code values explicitly
for (int idx = 0; retries[idx].domain != nil; idx++) {
if ([[error domain] isEqual:retries[idx].domain]
&& [error code] == retries[idx].code) {
return YES;
}
}
return NO;
}
// shouldRetryNowForStatus:error: returns YES if the user has enabled retries
// and the status or error is one that is suitable for retrying. "Suitable"
// means either the isRetryError:'s list contains the status or error, or the
// user's retrySelector: is present and returns YES when called.
- (BOOL)shouldRetryNowForStatus:(NSInteger)status
error:(NSError *)error {
if ([self isRetryEnabled]) {
if ([self nextRetryInterval] < [self maxRetryInterval]) {
if (error == nil) {
// make an error for the status
error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain
code:status
userInfo:nil];
}
BOOL willRetry = [self isRetryError:error];
if (retrySEL_) {
NSMethodSignature *signature = [delegate_ methodSignatureForSelector:retrySEL_];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:retrySEL_];
[invocation setTarget:delegate_];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&willRetry atIndex:3];
[invocation setArgument:&error atIndex:4];
[invocation invoke];
[invocation getReturnValue:&willRetry];
}
return willRetry;
}
}
return NO;
}
- (void)beginRetryTimer {
NSTimeInterval nextInterval = [self nextRetryInterval];
NSTimeInterval maxInterval = [self maxRetryInterval];
NSTimeInterval newInterval = MIN(nextInterval, maxInterval);
[self primeTimerWithNewTimeInterval:newInterval];
}
- (void)primeTimerWithNewTimeInterval:(NSTimeInterval)secs {
[self destroyRetryTimer];
lastRetryInterval_ = secs;
retryTimer_ = [NSTimer scheduledTimerWithTimeInterval:secs
target:self
selector:@selector(retryTimerFired:)
userInfo:nil
repeats:NO];
[retryTimer_ retain];
}
- (void)retryTimerFired:(NSTimer *)timer {
[self destroyRetryTimer];
retryCount_++;
[self retryFetch];
}
- (void)destroyRetryTimer {
[retryTimer_ invalidate];
[retryTimer_ autorelease];
retryTimer_ = nil;
}
- (unsigned int)retryCount {
return retryCount_;
}
- (NSTimeInterval)nextRetryInterval {
// the next wait interval is the factor (2.0) times the last interval,
// but never less than the minimum interval
NSTimeInterval secs = lastRetryInterval_ * retryFactor_;
secs = MIN(secs, maxRetryInterval_);
secs = MAX(secs, minRetryInterval_);
return secs;
}
- (BOOL)isRetryEnabled {
return isRetryEnabled_;
}
- (void)setIsRetryEnabled:(BOOL)flag {
if (flag && !isRetryEnabled_) {
// We defer initializing these until the user calls setIsRetryEnabled
// to avoid seeding the random number generator if it's not needed.
// However, it means min and max intervals for this fetcher are reset
// as a side effect of calling setIsRetryEnabled.
//
// seed the random value, and make an initial retry interval
// random between 1.0 and 2.0 seconds
srandomdev();
[self setMinRetryInterval:0.0];
[self setMaxRetryInterval:kDefaultMaxRetryInterval];
[self setRetryFactor:2.0];
lastRetryInterval_ = 0.0;
}
isRetryEnabled_ = flag;
};
- (SEL)retrySelector {
return retrySEL_;
}
- (void)setRetrySelector:(SEL)theSelector {
retrySEL_ = theSelector;
}
- (NSTimeInterval)maxRetryInterval {
return maxRetryInterval_;
}
- (void)setMaxRetryInterval:(NSTimeInterval)secs {
if (secs > 0) {
maxRetryInterval_ = secs;
} else {
maxRetryInterval_ = kDefaultMaxRetryInterval;
}
}
- (double)minRetryInterval {
return minRetryInterval_;
}
- (void)setMinRetryInterval:(NSTimeInterval)secs {
if (secs > 0) {
minRetryInterval_ = secs;
} else {
// set min interval to a random value between 1.0 and 2.0 seconds
// so that if multiple clients start retrying at the same time, they'll
// repeat at different times and avoid overloading the server
minRetryInterval_ = 1.0 + ((double)(random() & 0x0FFFF) / (double) 0x0FFFF);
}
}
- (double)retryFactor {
return retryFactor_;
}
- (void)setRetryFactor:(double)multiplier {
retryFactor_ = multiplier;
}
#pragma mark Getters and Setters
- (NSMutableURLRequest *)request {
return request_;
}
- (void)setRequest:(NSURLRequest *)theRequest {
[request_ autorelease];
request_ = [theRequest mutableCopy];
}
- (NSURLCredential *)credential {
return credential_;
}
- (void)setCredential:(NSURLCredential *)theCredential {
[credential_ autorelease];
credential_ = [theCredential retain];
}
- (NSURLCredential *)proxyCredential {
return proxyCredential_;
}
- (void)setProxyCredential:(NSURLCredential *)theCredential {
[proxyCredential_ autorelease];
proxyCredential_ = [theCredential retain];
}
- (NSData *)postData {
return postData_;
}
- (void)setPostData:(NSData *)theData {
[postData_ autorelease];
postData_ = [theData retain];
}
- (NSInputStream *)postStream {
return postStream_;
}
- (void)setPostStream:(NSInputStream *)theStream {
[postStream_ autorelease];
postStream_ = [theStream retain];
}
- (GTMHTTPFetcherCookieStorageMethod)cookieStorageMethod {
return cookieStorageMethod_;
}
- (void)setCookieStorageMethod:(GTMHTTPFetcherCookieStorageMethod)method {
cookieStorageMethod_ = method;
if (method == kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
[request_ setHTTPShouldHandleCookies:YES];
} else {
[request_ setHTTPShouldHandleCookies:NO];
}
}
- (id)delegate {
return delegate_;
}
- (void)setDelegate:(id)theDelegate {
// we retain delegate_ only during the life of the connection
if (connection_) {
[delegate_ autorelease];
delegate_ = [theDelegate retain];
} else {
delegate_ = theDelegate;
}
}
- (SEL)receivedDataSelector {
return receivedDataSEL_;
}
- (void)setReceivedDataSelector:(SEL)theSelector {
receivedDataSEL_ = theSelector;
}
- (NSURLResponse *)response {
return response_;
}
- (void)setResponse:(NSURLResponse *)response {
[response_ autorelease];
response_ = [response retain];
}
- (NSMutableDictionary *)fetchHistory {
return fetchHistory_;
}
- (void)setFetchHistory:(NSMutableDictionary *)fetchHistory {
[fetchHistory_ autorelease];
fetchHistory_ = [fetchHistory retain];
if (fetchHistory_ != nil) {
[self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodFetchHistory];
} else {
[self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic];
}
}
- (void)setShouldCacheDatedData:(BOOL)flag {
shouldCacheDatedData_ = flag;
if (!flag) {
[self clearDatedDataHistory];
}
}
- (BOOL)shouldCacheDatedData {
return shouldCacheDatedData_;
}
// delete last-modified dates and cached data from the fetch history
- (void)clearDatedDataHistory {
[fetchHistory_ removeObjectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
[fetchHistory_ removeObjectForKey:kGTMHTTPFetcherHistoryDatedDataKey];
}
- (id)userData {
return userData_;
}
- (void)setUserData:(id)theObj {
[userData_ autorelease];
userData_ = [theObj retain];
}
- (NSArray *)runLoopModes {
return runLoopModes_;
}
- (void)setRunLoopModes:(NSArray *)modes {
[runLoopModes_ autorelease];
runLoopModes_ = [modes retain];
}
+ (BOOL)doesSupportRunLoopModes {
SEL sel = @selector(initWithRequest:delegate:startImmediately:);
return [NSURLConnection instancesRespondToSelector:sel];
}
+ (NSArray *)defaultRunLoopModes {
return gGTMFetcherDefaultRunLoopModes;
}
+ (void)setDefaultRunLoopModes:(NSArray *)modes {
[gGTMFetcherDefaultRunLoopModes autorelease];
gGTMFetcherDefaultRunLoopModes = [modes retain];
}
+ (Class)connectionClass {
if (gGTMFetcherConnectionClass == nil) {
gGTMFetcherConnectionClass = [NSURLConnection class];
}
return gGTMFetcherConnectionClass;
}
+ (void)setConnectionClass:(Class)theClass {
gGTMFetcherConnectionClass = theClass;
}
#pragma mark Cookies
// return a cookie from the array with the same name, domain, and path as the
// given cookie, or else return nil if none found
//
// Both the cookie being tested and all cookies in cookieStorageArray should
// be valid (non-nil name, domains, paths)
- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie
inArray:(NSArray *)cookieStorageArray {
NSUInteger numberOfCookies = [cookieStorageArray count];
NSString *name = [cookie name];
NSString *domain = [cookie domain];
NSString *path = [cookie path];
_GTMDevAssert(name && domain && path,
@"Invalid cookie (name:%@ domain:%@ path:%@)",
name, domain, path);
for (NSUInteger idx = 0; idx < numberOfCookies; idx++) {
NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];
if ([[storedCookie name] isEqual:name]
&& [[storedCookie domain] isEqual:domain]
&& [[storedCookie path] isEqual:path]) {
return storedCookie;
}
}
return nil;
}
// remove any expired cookies from the array, excluding cookies with nil
// expirations
- (void)removeExpiredCookiesInArray:(NSMutableArray *)cookieStorageArray {
// count backwards since we're deleting items from the array
for (NSInteger idx = [cookieStorageArray count] - 1; idx >= 0; idx--) {
NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];
NSDate *expiresDate = [storedCookie expiresDate];
if (expiresDate && [expiresDate timeIntervalSinceNow] < 0) {
[cookieStorageArray removeObjectAtIndex:idx];
}
}
}
// retrieve all cookies appropriate for the given URL, considering
// domain, path, cookie name, expiration, security setting.
// Side effect: removed expired cookies from the storage array
- (NSArray *)cookiesForURL:(NSURL *)theURL inArray:(NSMutableArray *)cookieStorageArray {
[self removeExpiredCookiesInArray:cookieStorageArray];
NSMutableArray *foundCookies = [NSMutableArray array];
// we'll prepend "." to the desired domain, since we want the
// actual domain "nytimes.com" to still match the cookie domain ".nytimes.com"
// when we check it below with hasSuffix
NSString *host = [theURL host];
NSString *path = [theURL path];
NSString *scheme = [theURL scheme];
NSString *domain = nil;
if ([host isEqual:@"localhost"]) {
// the domain stored into NSHTTPCookies for localhost is "localhost.local"
domain = @"localhost.local";
} else {
if (host) {
domain = [@"." stringByAppendingString:host];
}
}
NSUInteger numberOfCookies = [cookieStorageArray count];
for (NSUInteger idx = 0; idx < numberOfCookies; idx++) {
NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];
NSString *cookieDomain = [storedCookie domain];
NSString *cookiePath = [storedCookie path];
BOOL cookieIsSecure = [storedCookie isSecure];
BOOL domainIsOK = [domain hasSuffix:cookieDomain];
BOOL pathIsOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath];
BOOL secureIsOK = (!cookieIsSecure) || [scheme isEqual:@"https"];
if (domainIsOK && pathIsOK && secureIsOK) {
[foundCookies addObject:storedCookie];
}
}
return foundCookies;
}
// return cookies for the given URL using the current cookie storage method
- (NSArray *)cookiesForURL:(NSURL *)theURL {
NSArray *cookies = nil;
NSMutableArray *cookieStorageArray = nil;
if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodStatic) {
cookieStorageArray = gGTMFetcherStaticCookies;
} else if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodFetchHistory) {
cookieStorageArray = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryCookiesKey];
} else {
// kGTMHTTPFetcherCookieStorageMethodSystemDefault
cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:theURL];
}
if (cookieStorageArray) {
@synchronized(cookieStorageArray) {
// cookiesForURL returns a new array of immutable NSCookie objects
// from cookieStorageArray
cookies = [self cookiesForURL:theURL
inArray:cookieStorageArray];
}
}
return cookies;
}
// add all cookies in the array |newCookies| to the storage array,
// replacing cookies in the storage array as appropriate
// Side effect: removes expired cookies from the storage array
- (void)setCookies:(NSArray *)newCookies
inArray:(NSMutableArray *)cookieStorageArray {
[self removeExpiredCookiesInArray:cookieStorageArray];
NSEnumerator *newCookieEnum = [newCookies objectEnumerator];
NSHTTPCookie *newCookie;
while ((newCookie = [newCookieEnum nextObject]) != nil) {
if ([[newCookie name] length] > 0
&& [[newCookie domain] length] > 0
&& [[newCookie path] length] > 0) {
// remove the cookie if it's currently in the array
NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie
inArray:cookieStorageArray];
if (oldCookie) {
[cookieStorageArray removeObject:oldCookie];
}
// make sure the cookie hasn't already expired
NSDate *expiresDate = [newCookie expiresDate];
if ((!expiresDate) || [expiresDate timeIntervalSinceNow] > 0) {
[cookieStorageArray addObject:newCookie];
}
} else {
_GTMDevAssert(NO, @"Cookie incomplete: %@", newCookie);
}
}
}
@end
#pragma mark Logging
// NOTE: Threads and Logging
//
// All the NSURLConnection callbacks happen on one thread, so we don't have
// to put any synchronization into the logging code. Yes, the state around
// logging (it's directory, etc.) could use it, but for now, that's punted.
// We don't invoke Leopard methods on 10.4, because we check if the methods are
// implemented before invoking it, but we need to be able to compile without
// warnings.
// This declaration means if you target <=10.4, this method will compile
// without complaint in this source, so you must test with
// -respondsToSelector:, too.
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
@interface NSFileManager (LeopardMethodsOnTigerBuilds)
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;
@end
#endif
// The iPhone Foundation removes the deprecated removeFileAtPath:handler:
#if GTM_IPHONE_SDK
@interface NSFileManager (TigerMethodsOniPhoneBuilds)
- (BOOL)removeFileAtPath:(NSString *)path handler:(id)handler;
@end
#endif
@implementation GTMHTTPFetcher (GTMHTTPFetcherLogging)
// if GTM_HTTPFETCHER_ENABLE_LOGGING is defined by the user's project then
// logging code will be compiled into the framework
#if !GTM_HTTPFETCHER_ENABLE_LOGGING
- (void)logFetchWithError:(NSError *)error {}
+ (void)setLoggingDirectory:(NSString *)path {}
+ (NSString *)loggingDirectory {return nil;}
+ (void)setIsLoggingEnabled:(BOOL)flag {}
+ (BOOL)isLoggingEnabled {return NO;}
+ (void)setLoggingProcessName:(NSString *)str {}
+ (NSString *)loggingProcessName {return nil;}
+ (void)setLoggingDateStamp:(NSString *)str {}
+ (NSString *)loggingDateStamp {return nil;}
- (void)appendLoggedStreamData:(NSData *)newData {}
- (void)logCapturePostStream {}
#else // GTM_HTTPFETCHER_ENABLE_LOGGING
// fetchers come and fetchers go, but statics are forever
static BOOL gIsLoggingEnabled = NO;
static NSString *gLoggingDirectoryPath = nil;
static NSString *gLoggingDateStamp = nil;
static NSString* gLoggingProcessName = nil;
+ (void)setLoggingDirectory:(NSString *)path {
[gLoggingDirectoryPath autorelease];
gLoggingDirectoryPath = [path copy];
}
+ (NSString *)loggingDirectory {
if (!gLoggingDirectoryPath) {
#if GTM_IPHONE_SDK
// default to a directory called GTMHTTPDebugLogs into a sandbox-safe
// directory that a devloper can find easily, the application home
NSArray *arr = [NSArray arrayWithObject:NSHomeDirectory()];
#else
// default to a directory called GTMHTTPDebugLogs in the desktop folder
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory,
NSUserDomainMask, YES);
#endif
if ([arr count] > 0) {
NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs";
NSString *desktopPath = [arr objectAtIndex:0];
NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName];
BOOL doesFolderExist;
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
doesFolderExist = [fileManager fileExistsAtPath:logsFolderPath
isDirectory:&isDir];
if (!doesFolderExist) {
// make the directory
doesFolderExist = [fileManager createDirectoryAtPath:logsFolderPath
attributes:nil];
}
if (doesFolderExist) {
// it's there; store it in the global
gLoggingDirectoryPath = [logsFolderPath copy];
}
}
}
return gLoggingDirectoryPath;
}
+ (void)setIsLoggingEnabled:(BOOL)flag {
gIsLoggingEnabled = flag;
}
+ (BOOL)isLoggingEnabled {
return gIsLoggingEnabled;
}
+ (void)setLoggingProcessName:(NSString *)str {
[gLoggingProcessName release];
gLoggingProcessName = [str copy];
}
+ (NSString *)loggingProcessName {
// get the process name (once per run) replacing spaces with underscores
if (!gLoggingProcessName) {
NSString *procName = [[NSProcessInfo processInfo] processName];
NSMutableString *loggingProcessName;
loggingProcessName = [[NSMutableString alloc] initWithString:procName];
[loggingProcessName replaceOccurrencesOfString:@" "
withString:@"_"
options:0
range:NSMakeRange(0, [gLoggingProcessName length])];
gLoggingProcessName = loggingProcessName;
}
return gLoggingProcessName;
}
+ (void)setLoggingDateStamp:(NSString *)str {
[gLoggingDateStamp release];
gLoggingDateStamp = [str copy];
}
+ (NSString *)loggingDateStamp {
// we'll pick one date stamp per run, so a run that starts at a later second
// will get a unique results html file
if (!gLoggingDateStamp) {
// produce a string like 08-21_01-41-23PM
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateFormat:@"M-dd_hh-mm-ssa"];
gLoggingDateStamp = [[formatter stringFromDate:[NSDate date]] retain] ;
}
return gLoggingDateStamp;
}
- (NSString *)cleanParameterFollowing:(NSString *)paramName
fromString:(NSString *)originalStr {
// We don't want the password written to disk
//
// find "&Passwd=" in the string, and replace it and the stuff that
// follows it with "Passwd=_snip_"
NSRange passwdRange = [originalStr rangeOfString:@"&Passwd="];
if (passwdRange.location != NSNotFound) {
// we found Passwd=; find the & that follows the parameter
NSUInteger origLength = [originalStr length];
NSRange restOfString = NSMakeRange(passwdRange.location+1,
origLength - passwdRange.location - 1);
NSRange rangeOfFollowingAmp = [originalStr rangeOfString:@"&"
options:0
range:restOfString];
NSRange replaceRange;
if (rangeOfFollowingAmp.location == NSNotFound) {
// found no other & so replace to end of string
replaceRange = NSMakeRange(passwdRange.location,
rangeOfFollowingAmp.location - passwdRange.location);
} else {
// another parameter after &Passwd=foo
replaceRange = NSMakeRange(passwdRange.location,
rangeOfFollowingAmp.location - passwdRange.location);
}
NSMutableString *result = [NSMutableString stringWithString:originalStr];
NSString *replacement = [NSString stringWithFormat:@"%@_snip_", paramName];
[result replaceCharactersInRange:replaceRange withString:replacement];
return result;
}
return originalStr;
}
// stringFromStreamData creates a string given the supplied data
//
// If NSString can create a UTF-8 string from the data, then that is returned.
//
// Otherwise, this routine tries to find a MIME boundary at the beginning of
// the data block, and uses that to break up the data into parts. Each part
// will be used to try to make a UTF-8 string. For parts that fail, a
// replacement string showing the part header and <<n bytes>> is supplied
// in place of the binary data.
- (NSString *)stringFromStreamData:(NSData *)data {
if (data == nil) return nil;
// optimistically, see if the whole data block is UTF-8
NSString *streamDataStr = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
if (streamDataStr) return streamDataStr;
// Munge a buffer by replacing non-ASCII bytes with underscores,
// and turn that munged buffer an NSString. That gives us a string
// we can use with NSScanner.
NSMutableData *mutableData = [NSMutableData dataWithData:data];
unsigned char *bytes = [mutableData mutableBytes];
for (NSUInteger idx = 0; idx < [mutableData length]; idx++) {
if (bytes[idx] > 0x7F || bytes[idx] == 0) {
bytes[idx] = '_';
}
}
NSString *mungedStr = [[[NSString alloc] initWithData:mutableData
encoding:NSUTF8StringEncoding] autorelease];
if (mungedStr != nil) {
// scan for the boundary string
NSString *boundary = nil;
NSScanner *scanner = [NSScanner scannerWithString:mungedStr];
if ([scanner scanUpToString:@"\r\n" intoString:&boundary]
&& [boundary hasPrefix:@"--"]) {
// we found a boundary string; use it to divide the string into parts
NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary];
// look at each of the munged parts in the original string, and try to
// convert those into UTF-8
NSMutableArray *origParts = [NSMutableArray array];
NSUInteger offset = 0;
for (NSUInteger partIdx = 0; partIdx < [mungedParts count]; partIdx++) {
NSString *mungedPart = [mungedParts objectAtIndex:partIdx];
NSUInteger partSize = [mungedPart length];
NSRange range = NSMakeRange(offset, partSize);
NSData *origPartData = [data subdataWithRange:range];
NSString *origPartStr = [[[NSString alloc] initWithData:origPartData
encoding:NSUTF8StringEncoding] autorelease];
if (origPartStr) {
// we could make this original part into UTF-8; use the string
[origParts addObject:origPartStr];
} else {
// this part can't be made into UTF-8; scan the header, if we can
NSString *header = nil;
NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart];
if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) {
// we couldn't find a header
header = @"";
}
// make a part string with the header and <<n bytes>>
NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%u bytes>>\r",
header, partSize - [header length]];
[origParts addObject:binStr];
}
offset += partSize + [boundary length];
}
// rejoin the original parts
streamDataStr = [origParts componentsJoinedByString:boundary];
}
}
if (!streamDataStr) {
// give up; just make a string showing the uploaded bytes
streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", [data length]];
}
return streamDataStr;
}
// logFetchWithError is called following a successful or failed fetch attempt
//
// This method does all the work for appending to and creating log files
- (void)logFetchWithError:(NSError *)error {
if (![[self class] isLoggingEnabled]) return;
NSFileManager *fileManager = [NSFileManager defaultManager];
// TODO: add Javascript to display response data formatted in hex
NSString *logDirectory = [[self class] loggingDirectory];
NSString *processName = [[self class] loggingProcessName];
NSString *dateStamp = [[self class] loggingDateStamp];
// each response's NSData goes into its own xml or txt file, though all
// responses for this run of the app share a main html file. This
// counter tracks all fetch responses for this run of the app.
static int zResponseCounter = 0;
zResponseCounter++;
// file name for the html file containing plain text in a <textarea>
NSString *responseDataUnformattedFileName = nil;
// file name for the "formatted" (raw) data file
NSString *responseDataFormattedFileName = nil;
NSUInteger responseDataLength = [downloadedData_ length];
NSURLResponse *response = [self response];
NSString *responseBaseName = nil;
// if there's response data, decide what kind of file to put it in based
// on the first bytes of the file or on the mime type supplied by the server
if (responseDataLength) {
NSString *responseDataExtn = nil;
// generate a response file base name like
// SyncProto_http_response_10-16_01-56-58PM_3
responseBaseName = [NSString stringWithFormat:@"%@_http_response_%@_%d",
processName, dateStamp, zResponseCounter];
NSString *dataStr = [[[NSString alloc] initWithData:downloadedData_
encoding:NSUTF8StringEncoding] autorelease];
if (dataStr) {
// we were able to make a UTF-8 string from the response data
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
dataStr = [dataStr stringByTrimmingCharactersInSet:whitespaceSet];
// save a plain-text version of the response data in an html cile
// containing a wrapped, scrollable <textarea>
//
// we'll use <textarea rows="33" cols="108" readonly=true wrap=soft>
// </textarea> to fit inside our iframe
responseDataUnformattedFileName = [responseBaseName stringByAppendingPathExtension:@"html"];
NSString *textFilePath = [logDirectory stringByAppendingPathComponent:responseDataUnformattedFileName];
NSString* wrapFmt = @"<textarea rows=\"33\" cols=\"108\" readonly=true"
" wrap=soft>\n%@\n</textarea>";
NSString* wrappedStr = [NSString stringWithFormat:wrapFmt, dataStr];
[wrappedStr writeToFile:textFilePath
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
// now determine the extension for the "formatted" file, which is really
// the raw data written with an appropriate extension
// for known file types, we'll write the data to a file with the
// appropriate extension
if ([dataStr hasPrefix:@"<?xml"]) {
responseDataExtn = @"xml";
} else if ([dataStr hasPrefix:@"<html"]) {
responseDataExtn = @"html";
} else {
// add more types of identifiable text here
}
} else if ([[response MIMEType] isEqual:@"image/jpeg"]) {
responseDataExtn = @"jpg";
} else if ([[response MIMEType] isEqual:@"image/gif"]) {
responseDataExtn = @"gif";
} else if ([[response MIMEType] isEqual:@"image/png"]) {
responseDataExtn = @"png";
} else {
// add more non-text types here
}
// if we have an extension, save the raw data in a file with that
// extension to be our "formatted" display file
if (responseDataExtn) {
responseDataFormattedFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn];
NSString *formattedFilePath = [logDirectory stringByAppendingPathComponent:responseDataFormattedFileName];
[downloadedData_ writeToFile:formattedFilePath atomically:NO];
}
}
// we'll have one main html file per run of the app
NSString *htmlName = [NSString stringWithFormat:@"%@_http_log_%@.html",
processName, dateStamp];
NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName];
// if the html file exists (from logging previous fetches) we don't need
// to re-write the header or the scripts
BOOL didFileExist = [fileManager fileExistsAtPath:htmlPath];
NSMutableString* outputHTML = [NSMutableString string];
NSURLRequest *request = [self request];
// we need file names for the various div's that we're going to show and hide,
// names unique to this response's bundle of data, so we format our div
// names with the counter that we incremented earlier
NSString *requestHeadersName = [NSString stringWithFormat:@"RequestHeaders%d", zResponseCounter];
NSString *postDataName = [NSString stringWithFormat:@"PostData%d", zResponseCounter];
NSString *responseHeadersName = [NSString stringWithFormat:@"ResponseHeaders%d", zResponseCounter];
NSString *responseDataDivName = [NSString stringWithFormat:@"ResponseData%d", zResponseCounter];
NSString *dataIFrameID = [NSString stringWithFormat:@"DataIFrame%d", zResponseCounter];
// we need a header to say we'll have UTF-8 text
if (!didFileExist) {
[outputHTML appendFormat:@"<html><head><meta http-equiv=\"content-type\" "
"content=\"text/html; charset=UTF-8\"><title>%@ HTTP fetch log %@</title>",
processName, dateStamp];
}
// write style sheets for each hideable element; each style sheet is
// customized with our current response number, since they'll share
// the html page with other responses
NSString *styleFormat = @"<style type=\"text/css\">div#%@ "
"{ margin: 0px 20px 0px 20px; display: none; }</style>\n";
[outputHTML appendFormat:styleFormat, requestHeadersName];
[outputHTML appendFormat:styleFormat, postDataName];
[outputHTML appendFormat:styleFormat, responseHeadersName];
[outputHTML appendFormat:styleFormat, responseDataDivName];
if (!didFileExist) {
// write javascript functions. The first one shows/hides the layer
// containing the iframe.
NSString *scriptFormat = @"<script type=\"text/javascript\"> "
"function toggleLayer(whichLayer){ var style2 = document.getElementById(whichLayer).style; "
"style2.display = style2.display ? \"\":\"block\";}</script>\n";
[outputHTML appendFormat:scriptFormat];
// the second function is passed the src file; if it's what's shown, it
// toggles the iframe's visibility. If some other src is shown, it shows
// the iframe and loads the new source. Note we want to load the source
// whenever we show the iframe too since Firefox seems to format it wrong
// when showing it if we don't reload it.
NSString *toggleIFScriptFormat = @"<script type=\"text/javascript\"> "
"function toggleIFrame(whichLayer,iFrameID,newsrc)"
"{ \n var iFrameElem=document.getElementById(iFrameID); "
"if (iFrameElem.src.indexOf(newsrc) != -1) { toggleLayer(whichLayer); } "
"else { document.getElementById(whichLayer).style.display=\"block\"; } "
"iFrameElem.src=newsrc; }</script>\n</head>\n<body>\n";
[outputHTML appendFormat:toggleIFScriptFormat];
}
// now write the visible html elements
// write the date & time
[outputHTML appendFormat:@"<b>%@</b><br>", [[NSDate date] description]];
// write the request URL
[outputHTML appendFormat:@"<b>request:</b> %@ <i>URL:</i> <code>%@</code><br>\n",
[request HTTPMethod], [request URL]];
// write the request headers, toggleable
NSDictionary *requestHeaders = [request allHTTPHeaderFields];
if ([requestHeaders count]) {
NSString *requestHeadersFormat = @"<a href=\"javascript:toggleLayer('%@');\">"
"request headers (%d)</a><div id=\"%@\"><pre>%@</pre></div><br>\n";
[outputHTML appendFormat:requestHeadersFormat,
requestHeadersName, // layer name
[requestHeaders count],
requestHeadersName,
[requestHeaders description]]; // description gives a human-readable dump
} else {
[outputHTML appendString:@"<i>Request headers: none</i><br>"];
}
// write the request post data, toggleable
NSData *postData = postData_;
if (loggedStreamData_) {
postData = loggedStreamData_;
}
if ([postData length]) {
NSString *postDataFormat = @"<a href=\"javascript:toggleLayer('%@');\">"
"posted data (%d bytes)</a><div id=\"%@\">%@</div><br>\n";
NSString *postDataStr = [self stringFromStreamData:postData];
if (postDataStr) {
NSString *postDataTextAreaFmt = @"<pre>%@</pre>";
if ([postDataStr rangeOfString:@"<"].location != NSNotFound) {
postDataTextAreaFmt = @"<textarea rows=\"15\" cols=\"100\""
" readonly=true wrap=soft>\n%@\n</textarea>";
}
NSString *cleanedPostData = [self cleanParameterFollowing:@"&Passwd="
fromString:postDataStr];
NSString *postDataTextArea = [NSString stringWithFormat:
postDataTextAreaFmt, cleanedPostData];
[outputHTML appendFormat:postDataFormat,
postDataName, // layer name
[postData length],
postDataName,
postDataTextArea];
}
} else {
// no post data
}
// write the response status, MIME type, URL
if (response) {
NSString *statusString = @"";
if ([response respondsToSelector:@selector(statusCode)]) {
NSInteger status = [(NSHTTPURLResponse *)response statusCode];
statusString = @"200";
if (status != 200) {
// purple for errors
statusString = [NSString stringWithFormat:@"<FONT COLOR=\"#FF00FF\">%d</FONT>",
status];
}
}
// show the response URL only if it's different from the request URL
NSString *responseURLStr = @"";
NSURL *responseURL = [response URL];
if (responseURL && ![responseURL isEqual:[request URL]]) {
NSString *responseURLFormat = @"<br><FONT COLOR=\"#FF00FF\">response URL:"
"</FONT> <code>%@</code>";
responseURLStr = [NSString stringWithFormat:responseURLFormat,
[responseURL absoluteString]];
}
NSDictionary *responseHeaders = nil;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
responseHeaders = [(NSHTTPURLResponse *)response allHeaderFields];
}
[outputHTML appendFormat:@"<b>response:</b> <i>status:</i> %@ <i> "
" MIMEType:</i><code> %@</code>%@<br>\n",
statusString,
[response MIMEType],
responseURLStr,
responseHeaders ? [responseHeaders description] : @""];
// write the response headers, toggleable
if ([responseHeaders count]) {
NSString *cookiesSet = [responseHeaders objectForKey:@"Set-Cookie"];
NSString *responseHeadersFormat = @"<a href=\"javascript:toggleLayer("
"'%@');\">response headers (%d) %@</a><div id=\"%@\"><pre>%@</pre>"
"</div><br>\n";
[outputHTML appendFormat:responseHeadersFormat,
responseHeadersName,
[responseHeaders count],
(cookiesSet ? @"<i>sets cookies</i>" : @""),
responseHeadersName,
[responseHeaders description]];
} else {
[outputHTML appendString:@"<i>Response headers: none</i><br>\n"];
}
}
// error
if (error) {
[outputHTML appendFormat:@"<b>error:</b> %@ <br>\n", [error description]];
}
// write the response data. We have links to show formatted and text
// versions, but they both show it in the same iframe, and both
// links also toggle visible/hidden
if (responseDataFormattedFileName || responseDataUnformattedFileName) {
// response data, toggleable links -- formatted and text versions
if (responseDataFormattedFileName) {
[outputHTML appendFormat:@"response data (%d bytes) formatted <b>%@</b> ",
responseDataLength,
[responseDataFormattedFileName pathExtension]];
// inline (iframe) link
NSString *responseInlineFormattedDataNameFormat = @" <a "
"href=\"javascript:toggleIFrame('%@','%@','%@');\">inline</a>\n";
[outputHTML appendFormat:responseInlineFormattedDataNameFormat,
responseDataDivName, // div ID
dataIFrameID, // iframe ID (for reloading)
responseDataFormattedFileName]; // src to reload
// plain link (so the user can command-click it into another tab)
[outputHTML appendFormat:@" <a href=\"%@\">stand-alone</a><br>\n",
[responseDataFormattedFileName
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
if (responseDataUnformattedFileName) {
[outputHTML appendFormat:@"response data (%d bytes) plain text ",
responseDataLength];
// inline (iframe) link
NSString *responseInlineDataNameFormat = @" <a href=\""
"javascript:toggleIFrame('%@','%@','%@');\">inline</a> \n";
[outputHTML appendFormat:responseInlineDataNameFormat,
responseDataDivName, // div ID
dataIFrameID, // iframe ID (for reloading)
responseDataUnformattedFileName]; // src to reload
// plain link (so the user can command-click it into another tab)
[outputHTML appendFormat:@" <a href=\"%@\">stand-alone</a><br>\n",
[responseDataUnformattedFileName
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
// make the iframe
NSString *divHTMLFormat = @"<div id=\"%@\">%@</div><br>\n";
NSString *src = responseDataFormattedFileName ?
responseDataFormattedFileName : responseDataUnformattedFileName;
NSString *escapedSrc = [src stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *iframeFmt = @" <iframe src=\"%@\" id=\"%@\" width=800 height=400>"
"\n<a href=\"%@\">%@</a>\n </iframe>\n";
NSString *dataIFrameHTML = [NSString stringWithFormat:iframeFmt,
escapedSrc, dataIFrameID, escapedSrc, src];
[outputHTML appendFormat:divHTMLFormat,
responseDataDivName, dataIFrameHTML];
} else {
// could not parse response data; just show the length of it
[outputHTML appendFormat:@"<i>Response data: %d bytes </i>\n",
responseDataLength];
}
[outputHTML appendString:@"<br><hr><p>"];
// append the HTML to the main output file
const char* htmlBytes = [outputHTML UTF8String];
NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath
append:YES];
[stream open];
[stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)];
[stream close];
// make a symlink to the latest html
NSString *symlinkName = [NSString stringWithFormat:@"%@_http_log_newest.html",
processName];
NSString *symlinkPath = [logDirectory stringByAppendingPathComponent:symlinkName];
// removeFileAtPath might be going away, but removeItemAtPath does not exist
// in 10.4
if ([fileManager respondsToSelector:@selector(removeFileAtPath:handler:)]) {
[fileManager removeFileAtPath:symlinkPath handler:nil];
} else if ([fileManager respondsToSelector:@selector(removeItemAtPath:error:)]) {
// To make the next line compile when targeting 10.4, we declare
// removeItemAtPath:error: in an @interface above
[fileManager removeItemAtPath:symlinkPath error:NULL];
}
[fileManager createSymbolicLinkAtPath:symlinkPath pathContent:htmlPath];
}
- (void)logCapturePostStream {
#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
// This is called when beginning a fetch. The caller should have already
// verified that logging is enabled, and should have allocated
// loggedStreamData_ as a mutable object.
// If we're logging, we need to wrap the upload stream with our monitor
// stream subclass that will call us back with the bytes being read from the
// stream
// our wrapper will retain the old post stream
[postStream_ autorelease];
// length can be
postStream_ = [GTMInputStreamLogger inputStreamWithStream:postStream_
length:0];
[postStream_ retain];
// we don't really want monitoring callbacks; our subclass will be
// calling our appendLoggedStreamData: method at every read instead
[(GTMInputStreamLogger *)postStream_ setMonitorDelegate:self
selector:nil];
#endif // GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
}
- (void)appendLoggedStreamData:(NSData *)newData {
[loggedStreamData_ appendData:newData];
}
#endif // GTM_HTTPFETCHER_ENABLE_LOGGING
@end
#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
@implementation GTMInputStreamLogger
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
// capture the read stream data, and pass it to the delegate to append to
NSInteger result = [super read:buffer maxLength:len];
if (result >= 0) {
NSData *data = [NSData dataWithBytes:buffer length:result];
[monitorDelegate_ appendLoggedStreamData:data];
}
return result;
}
@end
#endif // GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPFetcher.m | Objective-C | bsd | 65,856 |
//
// GTMRegex.h
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <Foundation/Foundation.h>
#import <regex.h>
#import "GTMDefines.h"
/// Options for controlling the behavior of the matches
enum {
kGTMRegexOptionIgnoreCase = 0x01,
// Ignore case in matching, ie: 'a' matches 'a' or 'A'
kGTMRegexOptionSupressNewlineSupport = 0x02,
// By default (without this option), regular expressions are implicitly
// processed on a line by line basis, where "lines" are delimited by newline
// characters. In this mode '.' (dot) does NOT match newline characters, and
// '^' and '$' match at the beginning and end of the string as well as
// around newline characters. This behavior matches the default behavior for
// regular expressions in other languages including Perl and Python. For
// example,
// foo.*bar
// would match
// fooAAAbar
// but would NOT match
// fooAAA\nbar
// With the kGTMRegexOptionSupressNewlineSupport option, newlines are treated
// just like any other character which means that '.' will match them. In
// this mode, ^ and $ only match the beginning and end of the input string
// and do NOT match around the newline characters. For example,
// foo.*bar
// would match
// fooAAAbar
// and would also match
// fooAAA\nbar
};
typedef NSUInteger GTMRegexOptions;
/// Global contants needed for errors from consuming patterns
#undef _EXTERN
#undef _INITIALIZE_AS
#ifdef GTMREGEX_DEFINE_GLOBALS
#define _EXTERN
#define _INITIALIZE_AS(x) =x
#else
#define _EXTERN extern
#define _INITIALIZE_AS(x)
#endif
_EXTERN NSString* kGTMRegexErrorDomain _INITIALIZE_AS(@"com.google.mactoolbox.RegexDomain");
enum {
kGTMRegexPatternParseFailedError = -100
};
// Keys for the userInfo from a kGTMRegexErrorDomain/kGTMRegexPatternParseFailedError error
_EXTERN NSString* kGTMRegexPatternErrorPattern _INITIALIZE_AS(@"pattern");
_EXTERN NSString* kGTMRegexPatternErrorErrorString _INITIALIZE_AS(@"patternError");
/// Class for doing Extended Regex operations w/ libregex (see re_format(7)).
//
// NOTE: the docs for recomp/regexec make *no* claims about i18n. All work
// within this class is done w/ UTF-8 so Unicode should move through it safely,
// however, the character classes described in re_format(7) might not really
// be unicode "savvy", so use them and this class w/ that in mind.
//
// Example usage:
//
// NSArray *inputArrayOfStrings = ...
// NSEnumerator *enumerator = [inputArrayOfString objectEnumerator];
// NSString *curStr = nil;
// NSArray *matches = [NSMutableArray array];
//
// GTMRegex *regex = [GTMRegex regexWithPattern:@"foo.*bar"];
// while ((curStr = [enumerator nextObject]) != nil) {
// if ([regex matchesString:curStr])
// [matches addObject:curStr];
// }
// ....
//
// -------------
//
// If you need to include something dynamic in a pattern:
//
// NSString *pattern =
// [NSString stringWithFormat:@"^foo:%@bar",
// [GTMRegex escapedPatternForString:inputStr]];
// GTMRegex *regex = [GTMRegex regexWithPattern:pattern];
// ....
//
// -------------
//
// GTMRegex *regex = [GTMRegex regexWithPattern:@"(foo+)(bar)"];
// NSString *highlighted =
// [regex stringByReplacingMatchesInString:inputString
// withReplacement:@"<i>\\1</i><b>\\2</b>"];
// ....
//
@interface GTMRegex : NSObject {
@private
NSString *pattern_;
GTMRegexOptions options_;
regex_t regexData_;
}
/// Create a new, autoreleased object w/ the given regex pattern with the default options
+ (id)regexWithPattern:(NSString *)pattern;
/// Create a new, autoreleased object w/ the given regex pattern and specify the matching options
+ (id)regexWithPattern:(NSString *)pattern options:(GTMRegexOptions)options;
/// Create a new, autoreleased object w/ the given regex pattern, specify the matching options and receive any error consuming the pattern.
+ (id)regexWithPattern:(NSString *)pattern
options:(GTMRegexOptions)options
withError:(NSError **)outErrorOrNULL;
/// Returns a new, autoreleased copy of |str| w/ any pattern chars in it escaped so they have no meaning when used w/in a pattern.
+ (NSString *)escapedPatternForString:(NSString *)str;
/// Initialize a new object w/ the given regex pattern with the default options
- (id)initWithPattern:(NSString *)pattern;
/// Initialize a new object w/ the given regex pattern and specify the matching options
- (id)initWithPattern:(NSString *)pattern options:(GTMRegexOptions)options;
/// Initialize a new object w/ the given regex pattern, specify the matching options, and receive any error consuming the pattern.
- (id)initWithPattern:(NSString *)pattern
options:(GTMRegexOptions)options
withError:(NSError **)outErrorOrNULL;
/// Returns the number of sub patterns in the pattern
//
// Sub Patterns are basically the number of parenthesis blocks w/in the pattern.
// ie: The pattern "foo((bar)|(baz))" has 3 sub patterns.
//
- (NSUInteger)subPatternCount;
/// Returns YES if the whole string |str| matches the pattern.
- (BOOL)matchesString:(NSString *)str;
/// Returns a new, autoreleased array of string that contain the subpattern matches for the string.
//
// If the whole string does not match the pattern, nil is returned.
//
// The api follows the conventions of most regex engines, and index 0 (zero) is
// the full match, then the subpatterns are index 1, 2, ... going left to right.
// If the pattern has optional subpatterns, then anything that didn't match
// will have NSNull at that index.
// ie: The pattern "(fo(o+))((bar)|(baz))" has five subpatterns, and when
// applied to the string "foooooobaz" you'd get an array of:
// 0: "foooooobaz"
// 1: "foooooo"
// 2: "ooooo"
// 3: "baz"
// 4: NSNull
// 5: "baz"
//
- (NSArray *)subPatternsOfString:(NSString *)str;
/// Returns the first match for this pattern in |str|.
- (NSString *)firstSubStringMatchedInString:(NSString *)str;
/// Returns YES if this pattern some substring of |str|.
- (BOOL)matchesSubStringInString:(NSString *)str;
/// Returns a new, autoreleased enumerator that will walk segments (GTMRegexStringSegment) of |str| based on the pattern.
//
// This will split the string into "segments" using the given pattern. You get
// both the matches and parts that are inbetween matches. ie-the entire string
// will eventually be returned.
//
// See GTMRegexStringSegment for more infomation and examples.
//
- (NSEnumerator *)segmentEnumeratorForString:(NSString *)str;
/// Returns a new, autoreleased enumerator that will walk only the matching segments (GTMRegexStringSegment) of |str| based on the pattern.
//
// This extracts the "segments" of the string that used the pattern. So it can
// be used to collect all of the matching substrings from within a string.
//
// See GTMRegexStringSegment for more infomation and examples.
//
- (NSEnumerator *)matchSegmentEnumeratorForString:(NSString *)str;
/// Returns a new, autoreleased string with all matches of the pattern in |str| replaced with |replacementPattern|.
//
// Replacement uses the SED substitution like syntax w/in |replacementPattern|
// to allow the use of matches in the replacment. The replacement pattern can
// make use of any number of match references by using a backslash followed by
// the match subexpression number (ie-"\2", "\0", ...), see subPatternsOfString:
// for details on the subexpression indexing.
//
// REMINDER: you need to double-slash since the slash has meaning to the
// compiler/preprocessor. ie: "\\0"
//
- (NSString *)stringByReplacingMatchesInString:(NSString *)str
withReplacement:(NSString *)replacementPattern;
@end
/// Class returned by the nextObject for the enumerators from GTMRegex
//
// The two enumerators on from GTMRegex return objects of this type. This object
// represents a "piece" of the string the enumerator is walking. It's the apis
// on this object allow you to figure out why each segment was returned and to
// act on it.
//
// The easiest way to under stand this how the enumerators and this class works
// is through and examples ::
// Pattern: "foo+"
// String: "fo bar foobar foofooo baz"
// If you walk this w/ -segmentEnumeratorForString you'll get:
// # nextObjects Calls -isMatch -string
// 1 NO "fo bar "
// 2 YES "foo"
// 3 NO "bar "
// 4 YES "foo"
// 5 YES "fooo"
// 6 NO " baz"
// And if you walk this w/ -matchSegmentEnumeratorForString you'll get:
// # nextObjects Calls -isMatch -string
// 1 YES "foo"
// 2 YES "foo"
// 3 YES "fooo"
// (see the comments on subPatternString for how it works)
//
// Example usage:
//
// NSMutableString processedStr = [NSMutableString string];
// NSEnumerator *enumerator =
// [inputStr segmentEnumeratorForPattern:@"foo+((ba+r)|(ba+z))"];
// GTMRegexStringSegment *segment = nil;
// while ((segment = [enumerator nextObject]) != nil) {
// if ([segment isMatch]) {
// if ([segment subPatterString:2] != nil) {
// // matched: "(ba+r)"
// [processStr appendFormat:@"<b>%@</b>", [segment string]];
// } else {
// // matched: "(ba+z)"
// [processStr appendFormat:@"<i>%@</i>", [segment string]];
// }
// } else {
// [processStr appendString:[segment string]];
// }
// }
// // proccessedStr now has all the versions of foobar wrapped in bold tags,
// // and all the versons of foobaz in italics tags.
// // ie: " fooobar foobaaz " ==> " <b>fooobar</b> <i>foobaaz</i> "
//
@interface GTMRegexStringSegment : NSObject {
@private
NSData *utf8StrBuf_;
regmatch_t *regMatches_; // STRONG: ie-we call free
NSUInteger numRegMatches_;
BOOL isMatch_;
}
/// Returns YES if this segment from from a match of the regex, false if it was a segment between matches.
//
// Use -isMatch to see if the segment from from a match of the pattern or if the
// segment is some text between matches. (NOTE: isMatch is always YES for
// matchSegmentEnumeratorForString)
//
- (BOOL)isMatch;
/// Returns a new, autoreleased string w/ the full text segment from the original string.
- (NSString *)string;
/// Returns a new, autoreleased string w/ the |index| sub pattern from this segment of the original string.
//
// This api follows the conventions of most regex engines, and index 0 (zero) is
// the full match, then the subpatterns are index 1, 2, ... going left to right.
// If the pattern has optional subpatterns, then anything that didn't match
// will return nil.
// ie: When using the pattern "(fo(o+))((bar)|(baz))" the following indexes
// fetch these values for a segment where -string is @"foooooobaz":
// 0: "foooooobaz"
// 1: "foooooo"
// 2: "ooooo"
// 3: "baz"
// 4: nil
// 5: "baz"
//
- (NSString *)subPatternString:(NSUInteger)index;
@end
/// Some helpers to streamline usage of GTMRegex
//
// Example usage:
//
// if ([inputStr matchesPattern:@"foo.*bar"]) {
// // act on match
// ....
// }
//
// -------------
//
// NSString *subStr = [inputStr firstSubStringMatchedByPattern:@"^foo:.*$"];
// if (subStr != nil) {
// // act on subStr
// ....
// }
//
// -------------
//
// NSArray *headingList =
// [inputStr allSubstringsMatchedByPattern:@"^Heading:.*$"];
// // act on the list of headings
// ....
//
// -------------
//
// NSString *highlightedString =
// [inputString stringByReplacingMatchesOfPattern:@"(foo+)(bar)"
// withReplacement:@"<i>\\1</i><b>\\2</b>"];
// ....
//
@interface NSString (GTMRegexAdditions)
/// Returns YES if the full string matches regex |pattern| using the default match options
- (BOOL)gtm_matchesPattern:(NSString *)pattern;
/// Returns a new, autoreleased array of strings that contain the subpattern matches of |pattern| using the default match options
//
// See [GTMRegex subPatternsOfString:] for information about the returned array.
//
- (NSArray *)gtm_subPatternsOfPattern:(NSString *)pattern;
/// Returns a new, autoreleased string w/ the first substring that matched the regex |pattern| using the default match options
- (NSString *)gtm_firstSubStringMatchedByPattern:(NSString *)pattern;
/// Returns YES if a substring string matches regex |pattern| using the default match options
- (BOOL)gtm_subStringMatchesPattern:(NSString *)pattern;
/// Returns a new, autoreleased array of substrings in the string that match the regex |pattern| using the default match options
//
// Note: if the string has no matches, you get an empty array.
- (NSArray *)gtm_allSubstringsMatchedByPattern:(NSString *)pattern;
/// Returns a new, autoreleased segment enumerator that will break the string using pattern w/ the default match options
//
// The enumerator returns GTMRegexStringSegment options, see that class for more
// details and examples.
//
- (NSEnumerator *)gtm_segmentEnumeratorForPattern:(NSString *)pattern;
/// Returns a new, autoreleased segment enumerator that will only return matching segments from the string using pattern w/ the default match options
//
// The enumerator returns GTMRegexStringSegment options, see that class for more
// details and examples.
//
- (NSEnumerator *)gtm_matchSegmentEnumeratorForPattern:(NSString *)pattern;
/// Returns a new, autoreleased string with all matches for pattern |pattern| are replaced w/ |replacementPattern|. Uses the default match options.
//
// |replacemetPattern| has support for using any subExpression that matched,
// see [GTMRegex stringByReplacingMatchesInString:withReplacement:] above
// for details.
//
- (NSString *)gtm_stringByReplacingMatchesOfPattern:(NSString *)pattern
withReplacement:(NSString *)replacementPattern;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMRegex.h | Objective-C | bsd | 14,844 |
//
// GTMNSString+XML.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMDefines.h"
#import "GTMNSString+XML.h"
#import "GTMGarbageCollection.h"
enum {
kGTMXMLCharModeEncodeQUOT = 0,
kGTMXMLCharModeEncodeAMP = 1,
kGTMXMLCharModeEncodeAPOS = 2,
kGTMXMLCharModeEncodeLT = 3,
kGTMXMLCharModeEncodeGT = 4,
kGTMXMLCharModeValid = 99,
kGTMXMLCharModeInvalid = 100,
};
typedef NSUInteger GTMXMLCharMode;
static NSString *gXMLEntityList[] = {
// this must match the above order
@""",
@"&",
@"'",
@"<",
@">",
};
FOUNDATION_STATIC_INLINE GTMXMLCharMode XMLModeForUnichar(UniChar c) {
// Per XML spec Section 2.2 Characters
// ( http://www.w3.org/TR/REC-xml/#charsets )
//
// Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
// [#x10000-#x10FFFF]
if (c <= 0xd7ff) {
if (c >= 0x20) {
switch (c) {
case 34:
return kGTMXMLCharModeEncodeQUOT;
case 38:
return kGTMXMLCharModeEncodeAMP;
case 39:
return kGTMXMLCharModeEncodeAPOS;
case 60:
return kGTMXMLCharModeEncodeLT;
case 62:
return kGTMXMLCharModeEncodeGT;
default:
return kGTMXMLCharModeValid;
}
} else {
if (c == '\n')
return kGTMXMLCharModeValid;
if (c == '\r')
return kGTMXMLCharModeValid;
if (c == '\t')
return kGTMXMLCharModeValid;
return kGTMXMLCharModeInvalid;
}
}
if (c < 0xE000)
return kGTMXMLCharModeInvalid;
if (c <= 0xFFFD)
return kGTMXMLCharModeValid;
// UniChar can't have the following values
// if (c < 0x10000)
// return kGTMXMLCharModeInvalid;
// if (c <= 0x10FFFF)
// return kGTMXMLCharModeValid;
return kGTMXMLCharModeInvalid;
} // XMLModeForUnichar
static NSString *AutoreleasedCloneForXML(NSString *src, BOOL escaping) {
//
// NOTE:
// We don't use CFXMLCreateStringByEscapingEntities because it's busted in
// 10.3 (http://lists.apple.com/archives/Cocoa-dev/2004/Nov/msg00059.html) and
// it doesn't do anything about the chars that are actually invalid per the
// xml spec.
//
// we can't use the CF call here because it leaves the invalid chars
// in the string.
NSUInteger length = [src length];
if (!length) {
return src;
}
NSMutableString *finalString = [NSMutableString string];
// this block is common between GTMNSString+HTML and GTMNSString+XML but
// it's so short that it isn't really worth trying to share.
const UniChar *buffer = CFStringGetCharactersPtr((CFStringRef)src);
if (!buffer) {
// We want this buffer to be autoreleased.
NSMutableData *data = [NSMutableData dataWithLength:length * sizeof(UniChar)];
if (!data) {
// COV_NF_START - Memory fail case
_GTMDevLog(@"couldn't alloc buffer");
return nil;
// COV_NF_END
}
[src getCharacters:[data mutableBytes]];
buffer = [data bytes];
}
const UniChar *goodRun = buffer;
NSUInteger goodRunLength = 0;
for (NSUInteger i = 0; i < length; ++i) {
GTMXMLCharMode cMode = XMLModeForUnichar(buffer[i]);
// valid chars go as is, and if we aren't doing entities, then
// everything goes as is.
if ((cMode == kGTMXMLCharModeValid) ||
(!escaping && (cMode != kGTMXMLCharModeInvalid))) {
// goes as is
goodRunLength += 1;
} else {
// it's something we have to encode or something invalid
// start by adding what we already collected (if anything)
if (goodRunLength) {
CFStringAppendCharacters((CFMutableStringRef)finalString,
goodRun,
goodRunLength);
goodRunLength = 0;
}
// if it wasn't invalid, add the encoded version
if (cMode != kGTMXMLCharModeInvalid) {
// add this encoded
[finalString appendString:gXMLEntityList[cMode]];
}
// update goodRun to point to the next UniChar
goodRun = buffer + i + 1;
}
}
// anything left to add?
if (goodRunLength) {
CFStringAppendCharacters((CFMutableStringRef)finalString,
goodRun,
goodRunLength);
}
return finalString;
} // AutoreleasedCloneForXML
@implementation NSString (GTMNSStringXMLAdditions)
- (NSString *)gtm_stringBySanitizingAndEscapingForXML {
return AutoreleasedCloneForXML(self, YES);
} // gtm_stringBySanitizingAndEscapingForXML
- (NSString *)gtm_stringBySanitizingToXMLSpec {
return AutoreleasedCloneForXML(self, NO);
} // gtm_stringBySanitizingToXMLSpec
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+XML.m | Objective-C | bsd | 5,274 |
//
// GTMScriptRunner.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMScriptRunner.h"
#import "GTMDefines.h"
static BOOL LaunchNSTaskCatchingExceptions(NSTask *task);
@interface GTMScriptRunner (PrivateMethods)
- (NSTask *)interpreterTaskWithAdditionalArgs:(NSArray *)args;
@end
@implementation GTMScriptRunner
+ (GTMScriptRunner *)runner {
return [[[self alloc] init] autorelease];
}
+ (GTMScriptRunner *)runnerWithBash {
return [self runnerWithInterpreter:@"/bin/bash"];
}
+ (GTMScriptRunner *)runnerWithPerl {
return [self runnerWithInterpreter:@"/usr/bin/perl"];
}
+ (GTMScriptRunner *)runnerWithPython {
return [self runnerWithInterpreter:@"/usr/bin/python"];
}
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp {
return [self runnerWithInterpreter:interp withArgs:nil];
}
+ (GTMScriptRunner *)runnerWithInterpreter:(NSString *)interp withArgs:(NSArray *)args {
return [[[self alloc] initWithInterpreter:interp withArgs:args] autorelease];
}
- (id)init {
return [self initWithInterpreter:nil];
}
- (id)initWithInterpreter:(NSString *)interp {
return [self initWithInterpreter:interp withArgs:nil];
}
- (id)initWithInterpreter:(NSString *)interp withArgs:(NSArray *)args {
if ((self = [super init])) {
trimsWhitespace_ = YES;
interpreter_ = [interp copy];
interpreterArgs_ = [args retain];
if (!interpreter_) {
interpreter_ = @"/bin/sh";
}
}
return self;
}
- (void)dealloc {
[interpreter_ release];
[interpreterArgs_ release];
[super dealloc];
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@<%p>{ interpreter = '%@', args = %@, environment = %@ }",
[self class], self, interpreter_, interpreterArgs_, environment_];
}
- (NSString *)run:(NSString *)cmds {
return [self run:cmds standardError:nil];
}
- (NSString *)run:(NSString *)cmds standardError:(NSString **)err {
if (!cmds) return nil;
NSTask *task = [self interpreterTaskWithAdditionalArgs:nil];
NSFileHandle *toTask = [[task standardInput] fileHandleForWriting];
NSFileHandle *fromTask = [[task standardOutput] fileHandleForReading];
if (!LaunchNSTaskCatchingExceptions(task)) {
return nil;
}
[toTask writeData:[cmds dataUsingEncoding:NSUTF8StringEncoding]];
[toTask closeFile];
NSData *outData = [fromTask readDataToEndOfFile];
NSString *output = [[[NSString alloc] initWithData:outData
encoding:NSUTF8StringEncoding] autorelease];
// Handle returning standard error if |err| is not nil
if (err) {
NSFileHandle *stderror = [[task standardError] fileHandleForReading];
NSData *errData = [stderror readDataToEndOfFile];
*err = [[[NSString alloc] initWithData:errData
encoding:NSUTF8StringEncoding] autorelease];
if (trimsWhitespace_) {
*err = [*err stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// let folks test for nil instead of @""
if ([*err length] < 1) {
*err = nil;
}
}
[task terminate];
if (trimsWhitespace_) {
output = [output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// let folks test for nil instead of @""
if ([output length] < 1) {
output = nil;
}
return output;
}
- (NSString *)runScript:(NSString *)path {
return [self runScript:path withArgs:nil];
}
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args {
return [self runScript:path withArgs:args standardError:nil];
}
- (NSString *)runScript:(NSString *)path withArgs:(NSArray *)args standardError:(NSString **)err {
if (!path) return nil;
NSArray *scriptPlusArgs = [[NSArray arrayWithObject:path] arrayByAddingObjectsFromArray:args];
NSTask *task = [self interpreterTaskWithAdditionalArgs:scriptPlusArgs];
NSFileHandle *fromTask = [[task standardOutput] fileHandleForReading];
if (!LaunchNSTaskCatchingExceptions(task)) {
return nil;
}
NSData *outData = [fromTask readDataToEndOfFile];
NSString *output = [[[NSString alloc] initWithData:outData
encoding:NSUTF8StringEncoding] autorelease];
// Handle returning standard error if |err| is not nil
if (err) {
NSFileHandle *stderror = [[task standardError] fileHandleForReading];
NSData *errData = [stderror readDataToEndOfFile];
*err = [[[NSString alloc] initWithData:errData
encoding:NSUTF8StringEncoding] autorelease];
if (trimsWhitespace_) {
*err = [*err stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// let folks test for nil instead of @""
if ([*err length] < 1) {
*err = nil;
}
}
[task terminate];
if (trimsWhitespace_) {
output = [output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// let folks test for nil instead of @""
if ([output length] < 1) {
output = nil;
}
return output;
}
- (NSDictionary *)environment {
return environment_;
}
- (void)setEnvironment:(NSDictionary *)newEnv {
[environment_ autorelease];
environment_ = [newEnv retain];
}
- (BOOL)trimsWhitespace {
return trimsWhitespace_;
}
- (void)setTrimsWhitespace:(BOOL)trim {
trimsWhitespace_ = trim;
}
@end
@implementation GTMScriptRunner (PrivateMethods)
- (NSTask *)interpreterTaskWithAdditionalArgs:(NSArray *)args {
NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:interpreter_];
[task setStandardInput:[NSPipe pipe]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardError:[NSPipe pipe]];
// If |environment_| is nil, then use an empty dictionary, otherwise use
// environment_ exactly.
[task setEnvironment:(environment_
? environment_
: [NSDictionary dictionary])];
// Build args to interpreter. The format is:
// interp [args-to-interp] [script-name [args-to-script]]
NSArray *allArgs = nil;
if (interpreterArgs_) {
allArgs = interpreterArgs_;
}
if (args) {
allArgs = allArgs ? [allArgs arrayByAddingObjectsFromArray:args] : args;
}
if (allArgs){
[task setArguments:allArgs];
}
return task;
}
@end
static BOOL LaunchNSTaskCatchingExceptions(NSTask *task) {
BOOL isOK = YES;
@try {
[task launch];
} @catch (id ex) {
isOK = NO;
_GTMDevLog(@"Failed to launch interpreter '%@' due to: %@",
[task launchPath], ex);
}
return isOK;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMScriptRunner.m | Objective-C | bsd | 7,161 |
//
// GTMNSString+URLArguments.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMNSString+URLArguments.h"
#import "GTMGarbageCollection.h"
@implementation NSString (GTMNSStringURLArgumentsAdditions)
- (NSString*)gtm_stringByEscapingForURLArgument {
// Encode all the reserved characters, per RFC 3986
// (<http://www.ietf.org/rfc/rfc3986.txt>)
CFStringRef escaped =
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return [GTMNSMakeCollectable(escaped) autorelease];
}
- (NSString*)gtm_stringByUnescapingFromURLArgument {
NSMutableString *resultString = [NSMutableString stringWithString:self];
[resultString replaceOccurrencesOfString:@"+"
withString:@" "
options:NSLiteralSearch
range:NSMakeRange(0, [resultString length])];
return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.m | Objective-C | bsd | 1,799 |
//
// GTMNSData+zlib.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import "GTMNSData+zlib.h"
#import <zlib.h>
#import "GTMDefines.h"
#define kChunkSize 1024
@interface NSData (GTMZlibAdditionsPrivate)
+ (NSData *)gtm_dataByCompressingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level
useGzip:(BOOL)useGzip;
@end
@implementation NSData (GTMZlibAdditionsPrivate)
+ (NSData *)gtm_dataByCompressingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level
useGzip:(BOOL)useGzip {
if (!bytes || !length) {
return nil;
}
// TODO: support 64bit inputs
// avail_in is a uInt, so if length > UINT_MAX we actually need to loop
// feeding the data until we've gotten it all in. not supporting this
// at the moment.
_GTMDevAssert(length <= UINT_MAX, @"Currently don't support >32bit lengths");
if (level == Z_DEFAULT_COMPRESSION) {
// the default value is actually outside the range, so we have to let it
// through specifically.
} else if (level < Z_BEST_SPEED) {
level = Z_BEST_SPEED;
} else if (level > Z_BEST_COMPRESSION) {
level = Z_BEST_COMPRESSION;
}
z_stream strm;
bzero(&strm, sizeof(z_stream));
int windowBits = 15; // the default
int memLevel = 8; // the default
if (useGzip) {
windowBits += 16; // enable gzip header instead of zlib header
}
int retCode;
if ((retCode = deflateInit2(&strm, level, Z_DEFLATED, windowBits,
memLevel, Z_DEFAULT_STRATEGY)) != Z_OK) {
// COV_NF_START - no real way to force this in a unittest (we guard all args)
_GTMDevLog(@"Failed to init for deflate w/ level %d, error %d",
level, retCode);
return nil;
// COV_NF_END
}
// hint the size at 1/4 the input size
NSMutableData *result = [NSMutableData dataWithCapacity:(length/4)];
unsigned char output[kChunkSize];
// setup the input
strm.avail_in = (unsigned int)length;
strm.next_in = (unsigned char*)bytes;
// loop to collect the data
do {
// update what we're passing in
strm.avail_out = kChunkSize;
strm.next_out = output;
retCode = deflate(&strm, Z_FINISH);
if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) {
// COV_NF_START - no real way to force this in a unittest
// (in inflate, we can feed bogus/truncated data to test, but an error
// here would be some internal issue w/in zlib, and there isn't any real
// way to test it)
_GTMDevLog(@"Error trying to deflate some of the payload, error %d",
retCode);
deflateEnd(&strm);
return nil;
// COV_NF_END
}
// collect what we got
unsigned gotBack = kChunkSize - strm.avail_out;
if (gotBack > 0) {
[result appendBytes:output length:gotBack];
}
} while (retCode == Z_OK);
// if the loop exits, we used all input and the stream ended
_GTMDevAssert(strm.avail_in == 0,
@"thought we finished deflate w/o using all input, %u bytes left",
strm.avail_in);
_GTMDevAssert(retCode == Z_STREAM_END,
@"thought we finished deflate w/o getting a result of stream end, code %d",
retCode);
// clean up
deflateEnd(&strm);
return result;
} // gtm_dataByCompressingBytes:length:compressionLevel:useGzip:
@end
@implementation NSData (GTMZLibAdditions)
+ (NSData *)gtm_dataByGzippingBytes:(const void *)bytes
length:(NSUInteger)length {
return [self gtm_dataByCompressingBytes:bytes
length:length
compressionLevel:Z_DEFAULT_COMPRESSION
useGzip:YES];
} // gtm_dataByGzippingBytes:length:
+ (NSData *)gtm_dataByGzippingData:(NSData *)data {
return [self gtm_dataByCompressingBytes:[data bytes]
length:[data length]
compressionLevel:Z_DEFAULT_COMPRESSION
useGzip:YES];
} // gtm_dataByGzippingData:
+ (NSData *)gtm_dataByGzippingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level {
return [self gtm_dataByCompressingBytes:bytes
length:length
compressionLevel:level
useGzip:YES];
} // gtm_dataByGzippingBytes:length:level:
+ (NSData *)gtm_dataByGzippingData:(NSData *)data
compressionLevel:(int)level {
return [self gtm_dataByCompressingBytes:[data bytes]
length:[data length]
compressionLevel:level
useGzip:YES];
} // gtm_dataByGzippingData:level:
+ (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes
length:(NSUInteger)length {
return [self gtm_dataByCompressingBytes:bytes
length:length
compressionLevel:Z_DEFAULT_COMPRESSION
useGzip:NO];
} // gtm_dataByDeflatingBytes:length:
+ (NSData *)gtm_dataByDeflatingData:(NSData *)data {
return [self gtm_dataByCompressingBytes:[data bytes]
length:[data length]
compressionLevel:Z_DEFAULT_COMPRESSION
useGzip:NO];
} // gtm_dataByDeflatingData:
+ (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level {
return [self gtm_dataByCompressingBytes:bytes
length:length
compressionLevel:level
useGzip:NO];
} // gtm_dataByDeflatingBytes:length:level:
+ (NSData *)gtm_dataByDeflatingData:(NSData *)data
compressionLevel:(int)level {
return [self gtm_dataByCompressingBytes:[data bytes]
length:[data length]
compressionLevel:level
useGzip:NO];
} // gtm_dataByDeflatingData:level:
+ (NSData *)gtm_dataByInflatingBytes:(const void *)bytes
length:(NSUInteger)length {
if (!bytes || !length) {
return nil;
}
// TODO: support 64bit inputs
// avail_in is a uInt, so if length > UINT_MAX we actually need to loop
// feeding the data until we've gotten it all in. not supporting this
// at the moment.
_GTMDevAssert(length <= UINT_MAX, @"Currently don't support >32bit lengths");
z_stream strm;
bzero(&strm, sizeof(z_stream));
// setup the input
strm.avail_in = (unsigned int)length;
strm.next_in = (unsigned char*)bytes;
int windowBits = 15; // 15 to enable any window size
windowBits += 32; // and +32 to enable zlib or gzip header detection.
int retCode;
if ((retCode = inflateInit2(&strm, windowBits)) != Z_OK) {
// COV_NF_START - no real way to force this in a unittest (we guard all args)
_GTMDevLog(@"Failed to init for inflate, error %d", retCode);
return nil;
// COV_NF_END
}
// hint the size at 4x the input size
NSMutableData *result = [NSMutableData dataWithCapacity:(length*4)];
unsigned char output[kChunkSize];
// loop to collect the data
do {
// update what we're passing in
strm.avail_out = kChunkSize;
strm.next_out = output;
retCode = inflate(&strm, Z_NO_FLUSH);
if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) {
_GTMDevLog(@"Error trying to inflate some of the payload, error %d",
retCode);
inflateEnd(&strm);
return nil;
}
// collect what we got
unsigned gotBack = kChunkSize - strm.avail_out;
if (gotBack > 0) {
[result appendBytes:output length:gotBack];
}
} while (retCode == Z_OK);
// make sure there wasn't more data tacked onto the end of a valid compressed
// stream.
if (strm.avail_in != 0) {
_GTMDevLog(@"thought we finished inflate w/o using all input, %u bytes left",
strm.avail_in);
result = nil;
}
// the only way out of the loop was by hitting the end of the stream
_GTMDevAssert(retCode == Z_STREAM_END,
@"thought we finished inflate w/o getting a result of stream end, code %d",
retCode);
// clean up
inflateEnd(&strm);
return result;
} // gtm_dataByInflatingBytes:length:
+ (NSData *)gtm_dataByInflatingData:(NSData *)data {
return [self gtm_dataByInflatingBytes:[data bytes]
length:[data length]];
} // gtm_dataByInflatingData:
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSData+zlib.m | Objective-C | bsd | 9,413 |
//
// GTMCalculatedRange.m
//
// Copyright 2006-2008 Google Inc.
//
// 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.
//
#import "GTMCalculatedRange.h"
// Our internal storage type. It keeps track of an item and it's
// position.
@interface GTMCalculatedRangeStopPrivate : NSObject {
id item_; // the item (STRONG)
CGFloat position_; //
}
+ (id)stopWithObject:(id)item position:(CGFloat)inPosition;
- (id)initWithObject:(id)item position:(CGFloat)inPosition;
- (id)item;
- (CGFloat)position;
@end
CG_INLINE BOOL FPEqual(CGFloat a, CGFloat b) {
return (fpclassify(a - b) == FP_ZERO);
}
@implementation GTMCalculatedRangeStopPrivate
+ (id)stopWithObject:(id)item position:(CGFloat)inPosition {
return [[[[self class] alloc] initWithObject:item position:inPosition] autorelease];
}
- (id)initWithObject:(id)item position:(CGFloat)inPosition {
self = [super init];
if (self != nil) {
item_ = [item retain];
position_ = inPosition;
}
return self;
}
- (void)dealloc {
[item_ release];
[super dealloc];
}
- (id)item {
return item_;
}
- (CGFloat)position {
return position_;
}
- (NSString *)description {
return [NSString stringWithFormat: @"%f %@", position_, item_];
}
@end
@implementation GTMCalculatedRange
- (id)init {
self = [super init];
if (self != nil) {
storage_ = [[NSMutableArray arrayWithCapacity:0] retain];
}
return self;
}
- (void)dealloc {
[storage_ release];
[super dealloc];
}
- (void)insertStop:(id)item atPosition:(CGFloat)position {
NSUInteger positionIndex = 0;
NSEnumerator *theEnumerator = [storage_ objectEnumerator];
GTMCalculatedRangeStopPrivate *theStop;
while (nil != (theStop = [theEnumerator nextObject])) {
if ([theStop position] < position) {
positionIndex += 1;
}
else if (FPEqual([theStop position], position)) {
// remove and stop the enum since we just modified the object
[storage_ removeObjectAtIndex:positionIndex];
break;
}
}
[storage_ insertObject:[GTMCalculatedRangeStopPrivate stopWithObject:item position:position]
atIndex:positionIndex];
}
- (BOOL)removeStopAtPosition:(CGFloat)position {
NSUInteger positionIndex = 0;
BOOL foundStop = NO;
NSEnumerator *theEnumerator = [storage_ objectEnumerator];
GTMCalculatedRangeStopPrivate *theStop;
while (nil != (theStop = [theEnumerator nextObject])) {
if (FPEqual([theStop position], position)) {
break;
} else {
positionIndex += 1;
}
}
if (nil != theStop) {
[self removeStopAtIndex:positionIndex];
foundStop = YES;
}
return foundStop;
}
- (void)removeStopAtIndex:(NSUInteger)positionIndex {
[storage_ removeObjectAtIndex:positionIndex];
}
- (NSUInteger)stopCount {
return [storage_ count];
}
- (id)stopAtIndex:(NSUInteger)positionIndex position:(CGFloat*)outPosition {
GTMCalculatedRangeStopPrivate *theStop = [storage_ objectAtIndex:positionIndex];
if (nil != outPosition) {
*outPosition = [theStop position];
}
return [theStop item];
}
- (id)valueAtPosition:(CGFloat)position {
id theValue = nil;
GTMCalculatedRangeStopPrivate *theStop;
NSEnumerator *theEnumerator = [storage_ objectEnumerator];
while (nil != (theStop = [theEnumerator nextObject])) {
if (FPEqual([theStop position], position)) {
theValue = [theStop item];
break;
}
}
return theValue;
}
- (NSString *)description {
return [storage_ description];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMCalculatedRange.m | Objective-C | bsd | 3,964 |
//
// GTMScriptRunnerTest.m
//
// Copyright 2007-2008 Google Inc.
//
// 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.
//
#import <sys/types.h>
#import <unistd.h>
#import "GTMSenTestCase.h"
#import "GTMScriptRunner.h"
#import "GTMUnitTestDevLog.h"
@interface GTMScriptRunnerTest : GTMTestCase {
@private
NSString *shScript_;
NSString *perlScript_;
NSString *shOutputScript_;
}
@end
@interface GTMScriptRunnerTest (PrivateMethods)
- (void)helperTestBourneShellUsingScriptRunner:(GTMScriptRunner *)sr;
@end
@implementation GTMScriptRunnerTest
- (void)setUp {
shScript_ = [NSString stringWithFormat:@"/tmp/script_runner_unittest_%d_%d_sh", geteuid(), getpid()];
[@"#!/bin/sh\n"
@"i=1\n"
@"if [ -n \"$1\" ]; then\n"
@" i=$1\n"
@"fi\n"
@"echo $i\n"
writeToFile:shScript_ atomically:YES encoding:NSUTF8StringEncoding error:nil];
perlScript_ = [NSString stringWithFormat:@"/tmp/script_runner_unittest_%d_%d_pl", geteuid(), getpid()];
[@"#!/usr/bin/perl\n"
@"use strict;\n"
@"my $i = 1;\n"
@"if (defined $ARGV[0]) {\n"
@" $i = $ARGV[0];\n"
@"}\n"
@"print \"$i\n\"\n"
writeToFile:perlScript_ atomically:YES encoding:NSUTF8StringEncoding error:nil];
shOutputScript_ = [NSString stringWithFormat:@"/tmp/script_runner_unittest_err_%d_%d_sh", geteuid(), getpid()];
[@"#!/bin/sh\n"
@"if [ \"err\" = \"$1\" ]; then\n"
@" echo \" on err \" > /dev/stderr\n"
@"else\n"
@" echo \" on out \"\n"
@"fi\n"
writeToFile:shOutputScript_ atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (void)tearDown {
const char *path = [shScript_ fileSystemRepresentation];
if (path) {
unlink(path);
}
path = [perlScript_ fileSystemRepresentation];
if (path) {
unlink(path);
}
path = [shOutputScript_ fileSystemRepresentation];
if (path) {
unlink(path);
}
}
- (void)testShCommands {
GTMScriptRunner *sr = [GTMScriptRunner runner];
[self helperTestBourneShellUsingScriptRunner:sr];
}
- (void)testBashCommands {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithBash];
[self helperTestBourneShellUsingScriptRunner:sr];
}
- (void)testZshCommands {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithInterpreter:@"/bin/zsh"];
[self helperTestBourneShellUsingScriptRunner:sr];
}
- (void)testBcCommands {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithInterpreter:@"/usr/bin/bc"
withArgs:[NSArray arrayWithObject:@"-lq"]];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple expression (NOTE that bc requires that commands end with a newline)
output = [sr run:@"1 + 2\n"];
STAssertEqualObjects(output, @"3", @"output should equal '3'");
// Simple expression with variables and multiple statements
output = [sr run:@"i=1; i+2\n"];
STAssertEqualObjects(output, @"3", @"output should equal '3'");
// Simple expression with base conversion
output = [sr run:@"obase=2; 2^5\n"];
STAssertEqualObjects(output, @"100000", @"output should equal '100000'");
// Simple expression with sine and cosine functions
output = [sr run:@"scale=3;s(0)+c(0)\n"];
STAssertEqualObjects(output, @"1.000", @"output should equal '1.000'");
}
- (void)testPerlCommands {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithPerl];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple print
output = [sr run:@"print 'hi'"];
STAssertEqualObjects(output, @"hi", @"output should equal 'hi'");
// Simple print x4
output = [sr run:@"print 'A'x4"];
STAssertEqualObjects(output, @"AAAA", @"output should equal 'AAAA'");
// Simple perl-y stuff
output = [sr run:@"my $i=0; until ($i++==41){} print $i"];
STAssertEqualObjects(output, @"42", @"output should equal '42'");
}
- (void)testPythonCommands {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithPython];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple print
output = [sr run:@"print 'hi'"];
STAssertEqualObjects(output, @"hi", @"output should equal 'hi'");
// Simple python expression
output = [sr run:@"print '-'.join(['a', 'b', 'c'])"];
STAssertEqualObjects(output, @"a-b-c", @"output should equal 'a-b-c'");
}
- (void)testBashScript {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithBash];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple sh script
output = [sr runScript:shScript_];
STAssertEqualObjects(output, @"1", @"output should equal '1'");
// Simple sh script with 1 command line argument
output = [sr runScript:shScript_ withArgs:[NSArray arrayWithObject:@"2"]];
STAssertEqualObjects(output, @"2", @"output should equal '2'");
}
- (void)testPerlScript {
GTMScriptRunner *sr = [GTMScriptRunner runnerWithPerl];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple Perl script
output = [sr runScript:perlScript_];
STAssertEqualObjects(output, @"1", @"output should equal '1'");
// Simple perl script with 1 command line argument
output = [sr runScript:perlScript_ withArgs:[NSArray arrayWithObject:@"2"]];
STAssertEqualObjects(output, @"2", @"output should equal '2'");
}
- (void)testEnvironment {
GTMScriptRunner *sr = [GTMScriptRunner runner];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
STAssertNil([sr environment], @"should start w/ empty env");
output = [sr run:@"/usr/bin/env | wc -l"];
int numVars = [output intValue];
STAssertGreaterThan(numVars, 0, @"numVars should be positive");
// By default the environment is wiped clean, however shells often add a few
// of their own env vars after things have been wiped. For example, sh will
// add about 3 env vars (PWD, _, and SHLVL).
STAssertLessThan(numVars, 5, @"Our env should be almost empty");
NSDictionary *newEnv = [NSDictionary dictionaryWithObject:@"bar"
forKey:@"foo"];
[sr setEnvironment:newEnv];
output = [sr run:@"/usr/bin/env | wc -l"];
STAssertEquals([output intValue], numVars + 1,
@"should have one more env var now");
[sr setEnvironment:nil];
output = [sr run:@"/usr/bin/env | wc -l"];
STAssertEquals([output intValue], numVars,
@"should be back down to %d vars", numVars);
NSDictionary *currVars = [[NSProcessInfo processInfo] environment];
[sr setEnvironment:currVars];
output = [sr run:@"/usr/bin/env | wc -l"];
STAssertEquals([output intValue], (int)[currVars count],
@"should be back down to %d vars", numVars);
}
- (void)testDescription {
// make sure description doesn't choke
GTMScriptRunner *sr = [GTMScriptRunner runner];
STAssertNotNil(sr, @"Script runner must not be nil");
STAssertGreaterThan([[sr description] length], (NSUInteger)10,
@"expected a description of at least 10 chars");
}
- (void)testRunCommandOutputHandling {
// Test whitespace trimming & stdout vs. stderr w/ run command api
GTMScriptRunner *sr = [GTMScriptRunner runnerWithBash];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
NSString *err = nil;
// w/o whitespace trimming
{
[sr setTrimsWhitespace:NO];
STAssertFalse([sr trimsWhitespace], @"setTrimsWhitespace to NO failed");
// test stdout
output = [sr run:@"echo \" on out \"" standardError:&err];
STAssertEqualObjects(output, @" on out \n", @"failed to get stdout output");
STAssertNil(err, @"stderr should have been empty");
// test stderr
output = [sr run:@"echo \" on err \" > /dev/stderr" standardError:&err];
STAssertNil(output, @"stdout should have been empty");
STAssertEqualObjects(err, @" on err \n", nil);
}
// w/ whitespace trimming
{
[sr setTrimsWhitespace:YES];
STAssertTrue([sr trimsWhitespace], @"setTrimsWhitespace to YES failed");
// test stdout
output = [sr run:@"echo \" on out \"" standardError:&err];
STAssertEqualObjects(output, @"on out", @"failed to get stdout output");
STAssertNil(err, @"stderr should have been empty");
// test stderr
output = [sr run:@"echo \" on err \" > /dev/stderr" standardError:&err];
STAssertNil(output, @"stdout should have been empty");
STAssertEqualObjects(err, @"on err", nil);
}
}
- (void)testScriptOutputHandling {
// Test whitespace trimming & stdout vs. stderr w/ script api
GTMScriptRunner *sr = [GTMScriptRunner runner];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
NSString *err = nil;
// w/o whitespace trimming
{
[sr setTrimsWhitespace:NO];
STAssertFalse([sr trimsWhitespace], @"setTrimsWhitespace to NO failed");
// test stdout
output = [sr runScript:shOutputScript_
withArgs:[NSArray arrayWithObject:@"out"]
standardError:&err];
STAssertEqualObjects(output, @" on out \n", nil);
STAssertNil(err, @"stderr should have been empty");
// test stderr
output = [sr runScript:shOutputScript_
withArgs:[NSArray arrayWithObject:@"err"]
standardError:&err];
STAssertNil(output, @"stdout should have been empty");
STAssertEqualObjects(err, @" on err \n", nil);
}
// w/ whitespace trimming
{
[sr setTrimsWhitespace:YES];
STAssertTrue([sr trimsWhitespace], @"setTrimsWhitespace to YES failed");
// test stdout
output = [sr runScript:shOutputScript_
withArgs:[NSArray arrayWithObject:@"out"]
standardError:&err];
STAssertEqualObjects(output, @"on out", nil);
STAssertNil(err, @"stderr should have been empty");
// test stderr
output = [sr runScript:shOutputScript_
withArgs:[NSArray arrayWithObject:@"err"]
standardError:&err];
STAssertNil(output, @"stdout should have been empty");
STAssertEqualObjects(err, @"on err", nil);
}
}
- (void)testBadRunCommandInput {
GTMScriptRunner *sr = [GTMScriptRunner runner];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *err = nil;
STAssertNil([sr run:nil standardError:&err], nil);
STAssertNil(err, nil);
}
- (void)testBadScriptInput {
GTMScriptRunner *sr = [GTMScriptRunner runner];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *err = nil;
STAssertNil([sr runScript:nil withArgs:nil standardError:&err], nil);
STAssertNil(err, nil);
STAssertNil([sr runScript:@"/path/that/does/not/exists/foo/bar/baz"
withArgs:nil standardError:&err], nil);
STAssertNotNil(err,
@"should have gotten something about the path not existing");
}
- (void)testBadCmdInterpreter {
GTMScriptRunner *sr =
[GTMScriptRunner runnerWithInterpreter:@"/path/that/does/not/exists/interpreter"];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *err = nil;
STAssertNil([sr run:nil standardError:&err], nil);
STAssertNil(err, nil);
[GTMUnitTestDevLog expectString:@"Failed to launch interpreter "
"'/path/that/does/not/exists/interpreter' due to: launch path not accessible"];
STAssertNil([sr run:@"ls /" standardError:&err], nil);
STAssertNil(err, nil);
}
- (void)testBadScriptInterpreter {
GTMScriptRunner *sr =
[GTMScriptRunner runnerWithInterpreter:@"/path/that/does/not/exists/interpreter"];
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *err = nil;
[GTMUnitTestDevLog expectString:@"Failed to launch interpreter "
"'/path/that/does/not/exists/interpreter' due to: launch path not accessible"];
STAssertNil([sr runScript:shScript_ withArgs:nil standardError:&err], nil);
STAssertNil(err, nil);
[GTMUnitTestDevLog expectString:@"Failed to launch interpreter "
"'/path/that/does/not/exists/interpreter' due to: launch path not accessible"];
STAssertNil([sr runScript:@"/path/that/does/not/exists/foo/bar/baz"
withArgs:nil standardError:&err], nil);
STAssertNil(err, nil);
}
@end
@implementation GTMScriptRunnerTest (PrivateMethods)
- (void)helperTestBourneShellUsingScriptRunner:(GTMScriptRunner *)sr {
STAssertNotNil(sr, @"Script runner must not be nil");
NSString *output = nil;
// Simple command
output = [sr run:@"ls /etc/passwd"];
STAssertEqualObjects(output, @"/etc/passwd", @"output should equal '/etc/passwd'");
// Simple command pipe-line
output = [sr run:@"ls /etc/ | grep passwd | tail -1"];
STAssertEqualObjects(output, @"passwd", @"output should equal 'passwd'");
// Simple pipe-line with quotes and awk variables
output = [sr run:@"ps jaxww | awk '{print $2}' | sort -nr | tail -2 | head -1"];
STAssertEqualObjects(output, @"1", @"output should equal '1'");
// Simple shell loop with variables
output = [sr run:@"i=0; while [ $i -lt 100 ]; do i=$((i+1)); done; echo $i"];
STAssertEqualObjects(output, @"100", @"output should equal '100'");
// Simple command with newlines
output = [sr run:@"i=1\necho $i"];
STAssertEqualObjects(output, @"1", @"output should equal '1'");
// Simple full shell script
output = [sr run:@"#!/bin/sh\ni=1\necho $i\n"];
STAssertEqualObjects(output, @"1", @"output should equal '1'");
NSString *err = nil;
// Test getting standard error with no stdout
output = [sr run:@"ls /etc/does-not-exist" standardError:&err];
STAssertNil(output, @"output should be nil due to expected error");
STAssertEqualObjects(err, @"ls: /etc/does-not-exist: No such file or directory", @"");
// Test getting standard output along with some standard error
output = [sr run:@"ls /etc/does-not-exist /etc/passwd" standardError:&err];
STAssertEqualObjects(output, @"/etc/passwd", @"");
STAssertEqualObjects(err, @"ls: /etc/does-not-exist: No such file or directory", @"");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMScriptRunnerTest.m | Objective-C | bsd | 14,471 |
//
// GTMHTTPServer.h
//
// This is a *very* *simple* webserver that can be built into something, it is
// not meant to stand up a site, it sends all requests to its delegate for
// processing on the main thread. It does not support pipelining, etc. It's
// great for places where you need a simple webserver to unittest some code
// that hits a server.
//
// NOTE: there are several TODOs left in here as markers for things that could
// be done if one wanted to add more to this class.
//
// Copyright 2008 Google Inc.
//
// 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.
//
// Based a little on HTTPServer, part of the CocoaHTTPServer sample code
// http://developer.apple.com/samplecode/CocoaHTTPServer/index.html
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// Global contants needed for errors from start
#undef _EXTERN
#undef _INITIALIZE_AS
#ifdef GTMHTTPSERVER_DEFINE_GLOBALS
#define _EXTERN
#define _INITIALIZE_AS(x) =x
#else
#define _EXTERN extern
#define _INITIALIZE_AS(x)
#endif
_EXTERN NSString* kGTMHTTPServerErrorDomain _INITIALIZE_AS(@"com.google.mactoolbox.HTTPServerDomain");
enum {
kGTMHTTPServerSocketCreateFailedError = -100,
kGTMHTTPServerBindFailedError = -101,
kGTMHTTPServerListenFailedError = -102,
kGTMHTTPServerHandleCreateFailedError = -103,
};
@class GTMHTTPRequestMessage, GTMHTTPResponseMessage;
// ----------------------------------------------------------------------------
// See comment at top of file for the intened use of this class.
@interface GTMHTTPServer : NSObject {
@private
id delegate_;
uint16_t port_;
BOOL localhostOnly_;
NSFileHandle *listenHandle_;
NSMutableArray *connections_;
}
// The delegate must support the httpServer:handleRequest: method in
// NSObject(GTMHTTPServerDeletateMethods) below.
- (id)initWithDelegate:(id)delegate;
- (id)delegate;
// Passing port zero will let one get assigned.
- (uint16_t)port;
- (void)setPort:(uint16_t)port;
// Receive connections on the localHost loopback address only or on all
// interfaces for this machine. The default is to only listen on localhost.
- (BOOL)localhostOnly;
- (void)setLocalhostOnly:(BOOL)yesno;
// Start/Stop the web server. If there is an error starting up the server, |NO|
// is returned, and the specific startup failure can be returned in |error| (see
// above for the error domain and error codes). If the server is started, |YES|
// is returned and the server's delegate is called for any requests that come
// in.
- (BOOL)start:(NSError **)error;
- (void)stop;
// returns the number of requests currently active in the server (i.e.-being
// read in, sent replies).
- (NSUInteger)activeRequestCount;
@end
@interface NSObject (GTMHTTPServerDeletateMethods)
- (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server
handleRequest:(GTMHTTPRequestMessage *)request;
@end
// ----------------------------------------------------------------------------
// Encapsulates an http request, one of these is sent to the server's delegate
// for each request.
@interface GTMHTTPRequestMessage : NSObject {
@private
CFHTTPMessageRef message_;
}
- (NSString *)version;
- (NSURL *)URL;
- (NSString *)method;
- (NSData *)body;
- (NSDictionary *)allHeaderFieldValues;
@end
// ----------------------------------------------------------------------------
// Encapsulates an http response, the server's delegate should return one for
// each request received.
@interface GTMHTTPResponseMessage : NSObject {
@private
CFHTTPMessageRef message_;
}
+ (id)responseWithHTMLString:(NSString *)htmlString;
+ (id)responseWithBody:(NSData *)body
contentType:(NSString *)contentType
statusCode:(int)statusCode;
+ (id)emptyResponseWithCode:(int)statusCode;
// TODO: class method for redirections?
// TODO: add helper for expire/no-cache
- (void)setValue:(NSString*)value forHeaderField:(NSString*)headerField;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPServer.h | Objective-C | bsd | 4,460 |