#!/usr/bin/env python

import DNS
import spf
import sys

DNS.DiscoverNameServers()

# Meng Weng Wong includes a test file in his Mail::Spf::Query Perl module.
# We use the same file, and try to keep in sync.
#
f = open('test-1.9.5.txt')

# map result codes from PySPF to Meng Weng Wong's test cases in test.txt
#
RESULTS = {'deny': 'fail'}

try:
	tests = failures = 0
	for line in f:
		line = line.strip()

		if not line or line[0] == '#':
			continue

		data = line.split()
		if len(data) >= 4:
			num = data[0]
			sender = data[1]
			ipaddr = data[2]
			expected_result = data[3]

			sys.stdout.write('%s...' % num)
			sys.stdout.flush()

			x = spf.check(i=ipaddr, s=sender, h=ipaddr)
			if RESULTS.get(x[0], x[0]) != expected_result:
				print 'TEST FAILURE:', x, line
				failures+=1
			tests+=1

			if tests % 10 == 0:
				sys.stdout.write('\n')

	if failures == 0:
		print tests, "tests succeeded"
	else:
		print "%d/%d" % (failures, tests), "tests failed"
finally:
	f.close()


syntax highlighted by Code2HTML, v. 0.9.1