Monday, March 18, 2013

Smart Card FAQ


Smart Card FAQ

What is a smart card?

A smart card is a device that includes an embedded integrated circuit that can be either a secure microcontroller or equivalent intelligence with internal memory or a memory chip alone. The card connects to a reader with direct physical contact or with a remote contactless radio frequency interface. With an embedded microcontroller, smart cards have the unique ability to store large amounts of data, carry out their own on-card functions (e.g., encryption and mutual authentication) and interact intelligently with a smart card reader. Smart card technology conforms to international standards (ISO/IEC 7816 and ISO/IEC 14443) and is available in a variety of form factors, including plastic cards, key fobs, watches, subscriber identification modules used in GSM mobile phones, and USB-based tokens.
For the purposes of this FAQ, “card” is used as the generic term to describe any device in which smart card technology is used.

What are the ISO/IEC 14443 and ISO/IEC 7816 standards?

ISO/IEC 14443 is the international standard for contactless smart chips and cards that operate (i.e., can be read from or written to) at a distance of less than 10 centimeters (4 inches). This standard operates at 13.56 MHz and includes specifications for the physical characteristics, radio frequency power and signal interface, initialization and anticollision protocols and transmission protocol.
ISO/IEC 7816 is the international standard for contact smart cards. ISO/IEC 7816 Parts 4 and above are used by both contact and contactless smart card applications for security operations and commands for interchange.

What is a contactless smart card?

A contactless smart card includes an embedded smart card secure microcontroller or equivalent intelligence, internal memory and a small antenna and communicates with a reader through a contactless radio frequency (RF) interface. Contactless smart card technology is used in applications that need to protect personal information and/or deliver fast, secure transactions, such as transit fare payment cards, government and corporate identification cards, documents such as electronic passports and visas, and financial payment cards. Example applications using contactless smart card technology include:
  • The U.S. FIPS 201 Personal Identity Verification (PIV) card being issued by all Federal agencies for employees and contractors;
  • The Transportation Worker Identification Credential (TWIC) being issued by the Transportation Security Administration;
  • The First Responder Authentication Card (FRAC) being issued in Department of Homeland Security pilots;
  • The new U.S. ePassport being issued by the Department of State;
  • Contactless payment cards and devices being issued by American Express, MasterCard and Visa;
  • Contactless transit fare payment systems currently operating or being installed in such cities as Washington, DC, Chicago, Boston, Atlanta, San Francisco and Los Angeles.
Contactless smart cards have the ability to securely manage, store and provide access to data on the card, perform on-card functions (e.g., encryption and mutual authentication) and interact intelligently with a contactless smart card reader. Contactless smart card technology and applications conform to international standards (ISO/IEC 14443 and ISO/IEC 7816). Contactless smart card technology is available in a variety of forms - in plastic cards, watches, key fobs, documents and other handheld devices (e.g., built into mobile phones).

How do contactless smart cards work?

Contactless smart card systems are closely related to contact smart card systems. Like contact smart card systems, information is stored on a chip embedded within the contactless smart card. However, unlike the contact smart card, the power supplied to the card as well as the data exchanged between the card and the reader are achieved without the use of contacts, using magnetic or electromagnetic fields to both power the card as well as to exchange data with the reader.
The contactless smart card contains an antenna embedded within the plastic body of the card (or within a key fob, watch or other document). When the card is brought into the electromagnetic field of the reader, the chip in the card is powered on. Once the chip is powered on, a wireless communication protocol is initiated and established between the card and the reader for data transfer.
The following four functions describe at a high level the sequence of events that happen when a contactless smart card is brought near a card reader:
  • Energy transfer to the card for powering the integrated circuit (chip)
  • Clock signal transfer
  • Data transfer to the contactless smart card
  • Data transfer from the contactless smart card
Hence, once the card is brought within range of an electromagnetic field of the required frequency, the card will be powered up, ready to communicate with the reader. Since the contactless smart cards described in this FAQ are based on the ISO/IEC 14443 standard, this frequency is 13.56 MHz and a reader that complies with the standard would have an activation field (range) of about 4 inches (approximately 10 centimeters). In other words, the card needs to be within 10 centimeters of a reader for it to be effectively powered; however, the effective range for communications for the card to be read will depend on a number of factors like the power of the reader, the antenna of the reader and the antenna of the card.

What is contactless payment?

Contactless payment is a change to the way debit or credit payment is handled when making a purchase. Contactless payment transactions require little to no physical connection between the card and the checkout device. Instead of “swiping” or “inserting” a card, the contactless card or fob is tapped on or held within an inch of a machine that reads the card, with the payment information is sent to the merchant wirelessly. Contactless credit and debit cards include a smart card chip.
In the U.S., contactless credit or debit cards or small keychain devices are being issued by a number of financial issuers (American Express, Chase, MBNA, Citibank, HSBC Bank, Keybank, Wells Fargo, Citizens Bank). For additional information on contactless payment, see the Smart Card Alliance Contactless Payments Resources.

How do smart cards help to protect privacy?

Smart cards offer a number of features that can be used to provide or enhance privacy protection in systems. The following is a brief description of some of these features and how they can be used to protect privacy.
  • Authentication. Smart cards provide mechanisms for authenticating others who want to gain access to the card. These mechanisms can be used to authenticate users, devices, or applications wishing to use the data on the card’s chip. These features can be utilized by a system to protect privacy by, for example, ensuring that a banking application has been authenticated as having the appropriate access rights before accessing financial data or functions on the card.
  • Secure data storage. Smart cards provide a means of securely storing data on the card. This data can only be accessed through the smart card operating system by those with proper access rights. This feature can be utilized by a system to enhance privacy by, for example, storing personal user data on the card rather than in a central database. In this example, the user has better knowledge and control of when and by whom their personal data is being granted access.
  • Encryption. Smart cards provide a robust set of encryption capabilities including key generation, secure key storage, hashing, and digital signing. These capabilities can be used by a system to protect privacy in a number of ways. For example, a smart card system can produce a digital signature for the content in an email, providing a means to validate the email authenticity. This protects the email message from subsequently being tampered with and provides the email recipient with an assurance of where it originated. The fact that the signing key originated from a smart card adds credibility to the origin and intent of the signer.
  • Strong device security. Smart card technology is extremely difficult to duplicate or forge and has built-in tamper-resistance. Smart card chips include a variety of hardware and software capabilities that detect and react to tampering attempts and help counter possible attacks. For example, the chips are manufactured with features such as extra metal layers, sensors to detect thermal and UV light attacks, and additional software and hardware circuitry to thwart differential power analysis.
  • Secure communications. Smart cards provide a means of secure communications between the card and card readers. Similar in concept to security protocols used in many networks, this feature allows smart cards to send and receive data in a secure and private manner. This capability can be used by a system to enhance privacy by ensuring that data sent to and from the card is not intercepted or tapped into.
  • Biometrics. Smart cards provide mechanisms to securely store biometric templates and perform biometric matching functions. These features can be used to improve privacy in systems that utilize biometrics. For example, storing fingerprint templates on a smart card rather than in a central database can be an effective way of increasing privacy in a single sign-on system that uses fingerprint biometrics as the single sign-on credential.
  • Personal device. A smart card is, of course, a personal and portable device associated with a particular cardholder. The smart card plastic is often personalized, providing an even stronger binding to the cardholder. These features, while somewhat obvious, can be leveraged by systems to improve privacy. For example, a healthcare application might elect to store drug prescription information on the card instead of in paper form to improve the accuracy and privacy of a patient’s prescriptions.
  • Certifications. Many of today’s smart cards have been certified that they comply with industry and government security standards. They obtain these certifications only after completing rigorous testing and evaluation criteria by independent certification facilities. These certifications help systems protect privacy by ensuring that the security and privacy features and functions of the smart card hardware and software operate as specified and intended.

Why are smart cards better than other ID token technologies?

Smart cards are widely acknowledged as one of the most secure and reliable forms of an electronic identification (ID) token. A smart card includes an embedded integrated circuit chip that can be either a microcontroller chip with internal memory or a secured memory chip alone. The card communicates with a reader either through direct physical contact or with a remote contactless electromagnetic field that energizes the chip and transfers data between the card and the reader. With an embedded microcontroller, smart cards have the unique ability to store large amounts of data, carry out their own on-card functions (e.g., data storage and management, encryption, decryption, and digital signature calculations) and interact intelligently with a smart card reader.
A smart card ID can combine several ID technologies, including the embedded chip, visual security markings, magnetic stripe, barcode and/or an optical stripe. By combining these various technologies into a smart card ID token, the resulting ID can support both future and legacy physical and logical access applications. They can also support other applications that have traditionally required separate ID processes and tokens.
Biometrics are used in many new identity management systems to improve the accuracy of identifying individuals. How can smart cards be used to help assure privacy in a biometrics-based system?
Smart cards provide a highly effective mechanism to protect the privacy of an individual that has a requirement to use a biometric identity system.
  • The biometric information can be stored on the smart card rather than in an online database, allowing the biometric owner the opportunity to manage the physical possession of the card holding the individual’s biometric information.
  • The biometric data can be secured with state-of-the-art encryption techniques while providing full three-factor authentication capability at the card/reader level.
    • Something you have – the card with all of its security capabilities
    • Something you know – a password or personal identification number (PIN)
    • Something you are – the biometric
  • In a smart card-based application, the individual’s biometric can be captured by a reader and passed to the smart card for matching, rather than passing the stored biometric information to the reader for matching. The individual’s biometric information would never leave the card, preventing virtually any possibility of compromise.
In a non-smart-card-based application, the password or PIN and biometric would be stored in an online database outside the control of the individual and the biometric information would be captured and passed to an application for matching.

What is an RFID tag?

Radio frequency identification (RFID) tags are used in a wide range of applications such as: identifying animals, tracking goods through the supply chain, tracking assets such as gas bottles and beer kegs, and controlling access into buildings. RFID tags include a chip that typically stores a static number (an ID) and an antenna that enables the chip to transmit the stored number to a reader. Some RFID tags contain read/write memory to store dynamic data. When the tag comes within range of the appropriate RF reader, the tag is powered by the reader’s RF field and transmits its ID to the reader.
RFID tags are simple, low-cost and commonly disposable, although this is not always the case such as reusable laundry tags. There is little to no security on the RFID tag or during communication with the reader. Any reader using the appropriate RF frequency (low frequency: 125/134 KHz; high frequency: 13.56 MHz; and ultra-high frequency: 900MHz) and protocol can get the RFID tag to communicate its contents. (Note that this is not true of car keys which contain a secure RFID tag.) Passive RFID tags (i.e., those not containing a battery) can be read from distances of several inches (centimeters) to many yards (meters), depending on the frequency and strength of the RF field used with the particular tag. RFID tags have common characteristics, including:
  • Low cost designs and high volume manufacturing to minimize investment required in implementation.
  • Minimal security in many applications, with tags able to be read by any compatible reader. Some applications like car keys do have security features, most notably provisions to authenticate the RFID tag before enabling the ignition to start the car.
  • Minimal data storage comparable to bar code, usually a fixed format written once when the tag is manufactured, although read/write tags do exist.
  • Read range optimized to increase speed and utility.

Is contactless smart card technology the same as RFID technology?

No. There is significant confusion in discussions of RF-enabled applications, with contactless smart card technology often incorrectly categorized as ‘RFID.’ There is a wide range of RF technologies used for a variety of applications – each with different operational parameters, frequencies, read ranges and capabilities to support security and privacy features. For example, the RFID technologies that are used to add value in manufacturing, shipping and object-related tracking operate over long ranges (e.g., 25 feet), were designed for that purpose alone and have minimal built-in support for security and privacy. Contactless smart cards, on the other hand, use RF technology, but, by design, operate at a short range (less than 4 inches) and can support the equivalent security capabilities of a contact smart card chip.

What security capabilities do contactless smart cards support?

Contactless smart cards use RF technology, but, by design, operate at a short range (less than 4 inches) and can support the equivalent security capabilities of a contact smart card chip (see below). Contactless smart cards and readers conform to international standards, ISO/IEC 14443 and ISO/IEC 7816, and can implement a variety of industry-standard cryptographic protocols (e.g., AES, 3DES, RSA, ECC).
The contactless smart chip includes a smart card secure microcontroller and internal memory and has unique attributes RFID tags lack – i.e., the ability to securely manage, store and provide access to data on the card, perform complex functions (for example, encryption and mutual authentication) and interact intelligently via RF with a contactless reader. Applications using contactless smart cards support many security features that ensure the integrity, confidentiality and privacy of information stored or transmitted, including the following:
  • Mutual authentication. For applications requiring secure card access, the contactless smart card-based device can verify that the reader is authentic and can prove its own authenticity to the reader before starting a secure transaction.
  • Strong information security. For applications requiring complete data protection, information stored on cards or documents using contactless smart card technology can be encrypted and communication between the contactless smart card-based device and the reader can be encrypted to prevent eavesdropping. Hashes and/or digital signatures can be used to ensure data integrity and to authenticate the card and the credentials it contains. Cryptographically strong random number generators can be used to enable dynamic cryptographic keys, preventing replay attacks.
  • Strong contactless device security. Like contact smart cards, contactless smart card technology is extremely difficult to duplicate or forge and has built-in tamper-resistance. Smart card chips include a variety of hardware and software capabilities that detect and react to tampering attempts and help counter possible attacks. For example, the chips are manufactured with features such as extra metal layers, sensors to detect thermal and UV light attacks, and additional software and hardware circuitry to thwart differential power analysis.
  • Authenticated and authorized information access. The contactless smart card’s ability to process information and react to its environment allows it to uniquely provide authenticated information access and protect the privacy of personal information. The contactless smart card can verify the authority of the information requestor and then allow access only to the information required. Access to stored information can also be further protected by a personal identification number (PIN) or biometric to protect privacy and counter unauthorized access.
  • Support for biometric authentication. For human identification systems that require the highest degree of security and privacy, smart cards can be implemented in combination with biometric technology. Biometrics are measurable physical characteristics or personal behavioral traits that can be used to recognize the identity or verify the claimed identity of an individual. Smart cards and biometrics are a natural fit to provide two- or multi-factor authentication. A smart card is the logical secure storage medium for biometric information. During the enrollment process, the biometric template can be stored on the smart card chip for later verification. Only the authorized user with a biometric matching the stored enrollment template receives access and privileges.
  • Strong support for information privacy. The use of smart card technology strengthens the ability of a system to protect individual privacy. Unlike other technologies, smart card-based devices can implement a personal firewall for an individual, releasing only the information required and only when it is required. The ability to support authenticated and authorized information access and the strong contactless device and data security make contactless smart cards excellent guardians of personal information and individual privacy.
It is important to note that information privacy and security must be designed into an application at the system level by the organization issuing the contactless device, card or document. It is critical that issuing organizations have the appropriate policies in place to support the security and privacy requirements of the application being deployed and then implement the appropriate technology that delivers those features. The ability of contactless smart card technology to support a wide array of security features provides organizations with the flexibility to implement the level of security that is commensurate with the risk expected in the application.

NFC and Contactless Technologies


NFC and Contactless Technologies

NFC complements many popular consumer level wireless technologies, by utilizing the key elements in existing standards for contactless card technology (ISO/IEC 14443 A&B and JIS-X 6319-4). NFC can be compatible with existing contactless card infrastructure and enables a consumer to utilize one device across different systems.
Extending the ability of the contactless card technology, NFC also enables devices to share information at a distance less than 4 centimeters with a maximum communication speed of 424kbps. Users can share business cards, make transactions, access information from smart posters or provide credentials for access control systems with a simple touch.
NFC’s bidirectional communication ability is ideal for establishing connections with other technologies by the simplicity of touch. For example if the user wants to connect their mobile device to their stereo to play media, they can simply touch the device to the stereo’s NFC touch point and the devices will negotiate the best wireless technology to use.
What does this mean for the end user? Easy connections, quick transactions, and simple data sharing.
NFC compared to other contactless technologies, including wireless, Bluetooth, and 3G

What is the difference between NFC and contactless?

What is the difference between NFC and contactless?

Just a matter of words. In fact there are a number of terms (RFID / Contactless / NFC) which have more or less precise definitions for the experts, but are used in the more general press in a variety of ways. So these terms are used in different ways by different people.

To be slightly more precise. Contactless refers to a range of technologies using RF (Radio Frequency) to communicate between a terminal and another device (often a card). It is most often used to refer to products around the ISO 14443 and ISO 15693 standards, which both use a 13.56Mhz frequency, but people will use it for other devices and frequencies.

NFC (Near Field Communications) is a set of specifications published by the NFC forum, based on ISO14443 and ISO 18092 which also work at 13.56MHz but with the particularity of using the technology both ways round. So integrated into a phone NFC can be used to make the phone behave like a contactless card (called card emulation) or as a card reader. By extension many people refer to cards and terminals that can do one half (using ISO14443) as NFC Cards or NFC Readers.

To wrap up Contactless is a more generic term covering several technoloical standards, NFC refers to a precise set of specifications, they are pretty closely related but both terms are used with varying amounts of precision.

Thursday, November 8, 2012

Control the bandwidth with Mac Wifi sharing

During the development and test, you always need to consider the bad connectivity situation. Testing become hard for this situation, now find an easy way, when you share your wifi from mac, you can limit the bandwidth to simulate the bad connection.

Here is the detailed man page from Apple
https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/ipfw.8.html

copy someone else's introduction as well. But I prefer follow the Apple guide.



Traffic Shaping in Mac OS X

December 18, 2005 - 12:38am
As a result of a previous question I was informed that Tiger finally has dummynet support in the kernel. What this means to you is that now you can do traffic shaping with no additional software.
Here’s how the idea works: you create several pipes that have a set bandwidth and other properties for all packets that get filed into them; you then add queues to those pipes that determine what priority certain requests will get in that pipe; then you add actual firewall rules to identify packets and file them into queues.
So let’s say you create a pipe with 1Mbit/s of allowed traffic. Within this you would setup three queues: one for high-priority services like incoming mail, DNS requests, and such; one for medium priority services like web and FTP; then one for low-priority services like file sharing and other network “noise”. With this setup you would, on a saturated pipe have a large amount of traffic coming in and going out for web andFTP, giving it priority over the noise, and when someone wanted to talk about mail orDNS those would have a higher chance of getting handled quickly. It’s a good boost in chance, but keep in mind that traffic shaping is not Quality of Service (QoS). Traffic shaping introduces delays in lower-priority packets so that higher-priority packets get in faster, but it offers no advanced logic or guarantees on delivery. If you want QoS, use either a userspace filter that does this or another kernel (like Linux) that has this built-in. For home and moderate server use, shaping is more than acceptable.
Okay, some demonstrations are in order here. Let’s take a typical example, such as the one from the question given, and say that you’re on DSL and your upload is 384k (this is mine) and you want email uploads to only take up 300k of that so you can actually do other things. So, we create a pipe with a 300kbit/s limit for all traffic I send to it:
The hash symbol means you’ll need to be root.
# ipfw pipe 1 config bw 300kbit/s
We have a pipe now. Now we need to setup some queues for priority in this pipe. Because we set the pipe to be lower than the actual upload bandwidth, any traffic that isn’t caught by this will go through on that extra 84kbit/s of bandwidth, so we don’t need a queue for this example as nothing will be sharing this pipe; we only need one rule to catch this traffic:
# ipfw add pipe 1 dst-port smtp
This catches inbound SMTP traffic, too, if you run an SMTP server. But, of course, that’s the point: we don’t want mail to take over.
Now, of course, if you wanted to limit POP/IMAP traffic to the same queue, you could:
# ipfw add pipe 1 dst-port pop3
# ipfw add pipe 1 dst-port pop3s
# ipfw add pipe 1 dst-port imap
# ipfw add pipe 1 dst-port imaps
Now every mail-related transaction will be filed into the limited pipe causing the system to have some leftover upstream bandwidth for browsing.
Of course, within this one could see some problems. Sending a large mail will not affect web browsing, but would affect mail retrieval since they’re in the same pipe, so we need a queue for incoming and one for outgoing so that there’s some control over that share of bandwidth. You could do this with multiple pipes, but then you’re cutting out a swath of bandwidth for incoming that outbound can’t use (presuming you make two 150k pipes).
So, one would do this:
# ipfw pipe 1 config bw 300kbit/s
# ipfw queue 1 config pipe 1 weight 50
# ipfw queue 2 config pipe 1 weight 50
Now we have an equal weight between the two services. You can go from 1 to 100 on the weights if you like, but for this I’d like an even traffic stream on each. When one is finished, the other will get the full pipe. So, we add the rules in:
# ipfw add queue 1 dst-port smtp
# ipfw add queue 2 dst-port pop3
# ipfw add queue 2 dst-port pop3s
# ipfw add queue 2 dst-port imap
# ipfw add queue 2 dst-port imaps
All inbound mail goes through queue 2 and all outbound mail goes through queue 1. Each is given a high chance of getting half the bandwidth allotted to pipe 1.
You can, obviously, have a lot of fun with this, but there’s also some serious fun to be had. Web designers: ever wonder what it’s like to load your site at 56k, or 33, 28, 14, or even 9600? Do this:
# ipfw pipe 1 config bw 56kbit/s
# ipfw add pipe 1 dst-port http
Now browse the web like a modem user. This, obviously, only works for sites served on port 80, but it does work. For the record, MG should be very usable on a modem. Smiling
If you’ve had fun playing, or locked yourself out at some point, just flush the rules:
# ipfw flush
All of this requires Mac OS X 10.4 or a FreeBSD with dummynet support. Anything else will laugh at you and order Yanni CDs from Amazon and send them to all of your friends for Christmas right before erasing the data on your computer in a spectacular flash of light that will blind you and your progeny. Best not to try. Specifically, it’ll either error out or appear to work and drop packets. The Yanni fate might be worse, so don’t risk it.

Tuesday, November 6, 2012

KIF Testing

Spending sometime to setup the KIF testing environment, it is not bad and working well. Just the wiki page's guide has problem, did not discribe clearly. If you follow the Example in their package, it is easier.

OK, past someone else's document


Keep It Functional – iPhone Test Automation

How we implement automated tests for the native iPhone App by Daniel Knott

Currently all the XING Mobile Apps generate more than 20% of the overall XING traffic and this number will likely increase in the near future. In my last devblog post, I dealed with Android Apps and how to implement automated tests with the framework Robotium. This article describes how to implement automated tests using the tool KIF (Keep It Functional).
KIF is an open source test framework developed by the company square. It is an iOS integration test framework that allows you to implement test cases with objective C that can be executed, currently only, against the iPhone/ iPad simulator. The KIF tests are integrated to your Xcode workspace, there is no need for additional servers or services that must be started.
KIF is like a Grey Box Test Tool because you need knowledge of the structure of the App you want to test. KIF use the provided accessibility labels from iOS to interact with the UI elements in the App. The labels are normally used to make Apps available for people with visual disabilities.
With KIF you are able to simulate real user interaction like tap, click, drag, enter text and many more. Also you are able to verify elements on the screen. It is really fast in executing the test cases on the simulator. Also it is really easy to integrate to your xCode and Continuous Integration environment.
Don’t submit your tests to Apple
It is really important that the KIF tests are not part of your production code, otherwise Apple will deny your submission because of undocumented APIs. Why this?
KIF uses these undocumented Apple APIs, to interact with the App, but that is not a problem when it comes to developing the tests. Most of the available iOS test frameworks use these undocumented Apple APIs.
Installation
To install and configure KIF please follow the provided information on the github page. These instructions are always up to date to the latest version of KIF.
Accessibility Inspector
If your project is configured with KIF you have also to activate the “Accessibility Inspector” on the iPhone or iPad simulator to have access to the labels. Do the following steps on the simulator:
  1. Open the Settings
  2. Click on General
  3. Click on Accessibility
  4. And activate the Inspector
Afterwards you see the inspector with a colorful layer within your simulator. You can drag the layer wherever you want. Clicking the small (x) on the left side opens the inspector. If you now do a single tap on an app you get information about the accessibility label and some more information (Screenshot). If you do a double click you can e.g. enter the app. If you close the inspector layer with the (x) again, you have again single click on the simulator.
NOTE: The inspector must be activated to use KIF for testing. Now you can start implementing your test classes.
iPhone Simulator with Accessibility Inspector
Code Example
KIF has three main classes that can be used to implement tests within your project. There is a test runner the KIFTestController, a scenario the KIFTestScenario and a step the KIFTestStep. The KIFTestController is like a test suite where all the test scenarios are listed that should be executed. A KIFTestScenario is like a container that includes several steps that should be done within a test. A step is the smallest and simplest action that represents user interaction like tap, enter text or wait for views.
The following listings show the Controller h-file and m-file. The m-file includes the list of possible scenarios.
XINGTestController.h
#import
#import "KIFTestController.h"
@interface XINGTestController : KIFTestController {}
@end
XINGTestController.m
#import "XINGTestController.h"
@implementation XINGTestController
 
   - (void)initializeScenarios {
      [self addScenario:[KIFTestScenario scenarioLoginWithWrongCredentials]];
      // Add here additional scenarios
   }
@end
Now you need to implement the scenario scenarioLoginWithWrongCredentials. You need again an h-file and an m-file for that. The h-file includes the scenario definitions. The m-file is the class where the test methods are implemented.
KIFTestScenario+XINGLogin.h
#import
#import "KIFTestScenario.h"
 
@interface KIFTestScenario (Login)
 
   + (id) scenarioLoginWithWrongCredentials;
 
@end
KIFTestScenario+Login.m
#import "KIFTestScenario+Login.h"
#import "KIFTestStep.h"
 
@implementation KIFTestScenario (Login)
 
   + (id)scenarioLoginWithWrongCredentials{
      KIFTestScenario *scenario = [KIFTestScenario scenarioWithDescription:@"Wrong credentials"];
 
      // enter wrong credentials in the username and password field
      [scenario addStep:[KIFTestStep stepToEnterText:@"wrongusername" intoViewWithAccessibilityLabel:@"Username"]];
 
      [scenario addStep:[KIFTestStep stepToEnterText:@"wrongpassword" intoViewWithAccessibilityLabel:@"password"]];
 
      // click the done button on the keyboard
      [scenario addStep:[KIFTestStep stepToTapViewWithAccessibilityLabel:@"done"]];
 
      // verify that the error message is shown with a localized string
      [scenario addStep:[KIFTestStep stepToWaitForViewWithAccessibilityLabel:LocalizedString (@"FAILED_MESSAGE")]];
 
      // click the button on the error message
      [scenario addStep:[KIFTestStep stepToTapViewWithAccessibilityLabel:LocalizedString (@"OK_BUTTON")]];
 
      return scenario;
   }
 
@end
Now you have a really simple test that tries to login with wrong credentials against an app. After pressing the done button on the keyboard KIF verifies with the stepToWaitForView… method that the right error message is shown. The following screenshots show the login screen where KIF tries to login with the wrong credentials. Please also have a look at the provided screencast videos at the end of this article. You get a really good impression how KIF is working.
   
Continuous Integration
It is highly recommended to integrate KIF to a CI server like Jenkins to build up a regression testsuite to be sure that the existing functionality is still working after a commit. To integrate and execute your KIF tests from the CI server you must be able to start the simulator from the command line. To do this, you need an additional tool called WaxSim. One Note from the KIF github page: “Note that the Square fork of WaxSim provides a number of bug fixes and some useful additional functionality. Your CI script should resemble something like the this:”
Adapt the following script to your environment and add it to your Jenkins build configuration:
#!/bin/bash
 
killall "iPhone Simulator"
 
set -o errexit
set -o verbose
# Build the "Integration Tests" target to run in the simulator
# xcodebuild -target "Integration Tests" -configuration Release -sdk iphonesimulator build
 
# Run the app we just built in the simulator and send its output to a file
 
# /path/to/XINGApp.app should be the relative or absolute path to the application bundle that was built in the previous step
/path/to/waxsim -f "iphone" "/path/to/XINGApp.app" > /tmp/KIF-$$.out 2>&1
 
# WaxSim hides the return value from the app, so to determine success we search for a "no failures" line
grep -q "TESTING FINISHED: 0 failures" /tmp/KIF-$$.out
Store this script as a shell script within your KIF test folder and call the script from the CI server. The iPhone simulator should start automatically and should execute the tests on the simulator.
That is the way, how we at XING use KIF to automate our iPhone App. Besides all the manual testing we use the automated tests to check, that code changes doesn’t affect to current functionality.
We hope that this post gives you an impression on how to build a test automation suite for your iPhone or iPad apps!
Screencasts
The following screencasts show the functionality of KIF. The first video shows the example code mentioned in this blog post. The second video shows how KIF is starting the XING handshake with some testusers on our testsystem.
Login with wrong credentials
Handshake
The latest XING iPhone App is available here.
Further information can be found in this really good google group about KIF.
This post based on sources from:

About the Author

Daniel KnottDaniel Knott works as a Manager Quality Assurance in XING’s mobile team. He likes to automate test cases using technologies such as Robotium, KIF(Keep It Functional), Selenium and Java.
XING Profile »

Thursday, October 18, 2012

debug iphone app wait for lunch


For Xcode 4 you have to:
  1. Edit your active scheme via "Schemes" dropdown.
  2. Than choose your product - 'Run MyApp.app' on the left.
  3. Select 'Info' tab on the right.
  4. And finally choose "Wait for MyApp.app to launch" option.
More here in "Customize Executables in the Scheme Editor" section.

Wednesday, October 17, 2012

iphone basic


Discover Whether an Object Is an Instance of a Particular Class or its Subclasses

To discover whether an object is an instance of a class or its subclasses, call the isKindOfClass: method on the object. An app sometimes makes this check when it wants to discover the messages (implemented or inherited) that an app responds to.
static int sum = 0;
for (id item in myArray) {
    if ([item isKindOfClass:[NSNumber class]]) {
        int i = (int)[item intValue];
        sum += i;
    }
}
The isKindOfClass: method takes an object of type Class as a parameter; to get this object, you call the class method on the class symbol. Then evaluate the Boolean value returned by this method and proceed accordingly.
NSObject declares other methods for discovering information about object inheritance. The isMemberOfClass: method, for example, tells you whether an object is an instance of a specific class, whereas isKindOfClass: tells you whether the object is a member of that class or any of its descendent classes.

Discover Whether an Object Responds to a Message

To discover whether an object responds to a message, call the respondsToSelector: method on the object. App code often verifies that an object responds to a message before it sends the message to the object.
if ([item respondsToSelector:@selector(setState:)]) {
    [item setState:[self.arcView.font isBold] ? NSOnState : NSOffState];
}
The respondsToSelector: method takes a selector as its parameter. A selector is an Objective-C data type for runtime identifiers of methods; you specify a selector using the @selector compiler directive. In your code, evaluate the Boolean value returned by this method and proceed accordingly.
For identifying the messages an object responds to, calling respondsToSelector: is generally more useful than evaluating class type. For example, a more recent version of a class might implement a method that isn’t found in a prior version.

Discover Whether an Object Conforms to a Protocol

To discover whether an object conforms to a protocol, call the conformsToProtocol: method on the object.
- (void) setDelegate:(id __weak) obj {
    NSParameterAssert([obj conformsToProtocol:
        @protocol(SubviewTableViewControllerDataSourceProtocol)]);
    delegate = obj;
}
The conformsToProtocol: method takes a runtime identifier of a protocol as a parameter; you specify this identifier using the @protocol compiler directive. Evaluate the Boolean value returned by this method and proceed accordingly. Note than an object can conform to a protocol without implementing its optional methods.

Compare Objects

You can compare two objects by using the isEqual: method. The object receiving the message is compared to the passed-in object; if they’re the same, the method returns YES. For example:
BOOL objectsAreEqual = [obj1 isEqual:obj2];
if (objectsAreEqual) {
    // do something...
}
Note that object equality is different from object identity. For the latter, use the equality operator == to test whether two variables point to the same instance.
What is compared when you compare two objects of the same class? That depends on the class. The root class, NSObject, uses pointer equality as the basis of comparison. Subclasses at any level can override their superclass’s implementation to base the comparison on class-specific criteria, such as object state. For example, a hypothetical Person object might equal another Person object if the first-name, last-name, and birth-date attributes of both objects match.
The value and collection classes of the Foundation framework declare comparison methods of the form isEqualToType:, where Type is the class type minus the NS prefix—for example, isEqualToString: and isEqualToDictionary:. The comparison methods assume that the passed-in object is of the given type and raise an exception if it is not.

Copy Objects

You make a copy of an object by sending a copy message to it.
NSArray *myArray = [yourArray copy];
To be copied, the class of the receiving object must conform to the NSCopying protocol. If you want your objects to be copyable, you must adopt and implement the copy method of this protocol.
You sometimes copy an object obtained from elsewhere in a program when you want to ensure the object’s state does not change while you’re using it.
Copying behavior is specific to a class and depends upon the specific nature of the instance. Most classes implement deep copying, which makes a duplicate of all instance variables and properties; some classes (for example, the collection classes) implement shallow copying, which only duplicates the references to those instance variables and properties.
Classes that have mutable and immutable variants also declare a mutableCopy method to create a mutable copy of an object. For example, if you call mutableCopy on an NSString object, you get an instance of NSMutableString.