<commit_before>import os.path as op
from os import listdir
import numpy as np
import sys, getopt

from retrieval.flickrwrapper import FlickrWrapper
from features.extract import extract, create_neutral_vector
from analysis import pca, kclosest
from display import plothelper
from features.featuremode import FeatureMode
from runmode import RunMode

class FlickrRsBundler:

    desc_file = "{0}_desc.txt"
    color_desc_file = "{0}_colordesc.txt"
    color_rand_file = "{0}_colorrand.txt"

    def __init__(self, api_key, tag):
        self.flickrWrapper = FlickrWrapper(api_key)
        self.tag = tag
        self.image_dir = op.dirname(op.abspath(__file__)) + "/images/" + self.tag + "/"

    def run(self):
        self.download()
        self.extract()
        self.save()
        self.process()
        self.plot()

    def download(self):
        self.flickrWrapper.download(self.image_dir, self.tag)

    def files(self):
        self.image_files = [op.join(self.image_dir,f) for f in listdir(self.image_dir) if op.isfile(op.join(self.image_dir,f)) and f.endswith(".jpg")]

    def extract(self):
        self.files()
        self.D, self.C_desc, self.C_rand = extract(self.image_files)

    def save(self):
        np.savetxt(self.image_dir + self.desc_file.format(self.tag), self.D)
        np.savetxt(self.image_dir + self.color_desc_file.format(self.tag), self.C_desc)
        np.savetxt(self.image_dir + self.color_rand_file.format(self.tag), self.C_rand)

    def load(self):
        self.files()
        self.D = np.loadtxt(self.image_dir + self.desc_file.format(self.tag), float)
        self.C_desc = np.loadtxt(self.image_dir + self.color_desc_file.format(self.tag), float)
        self.C_rand = np.loadtxt(self.image_dir + self.color_rand_file.format(self.tag), float)

    def process(self, mode=FeatureMode.All, neut_factor=0.8, d_weight=0.725):

        if mode == FeatureMode.Colors:
            N = create_neutral_vector(np.array([[self.C_rand.shape[1], 1]]), self.C_rand.shape[0])
            F = self.C_rand
        elif mode == FeatureMode.Descriptors:
            N = create_neutral_vector(np.array([[self.D.shape[1], 1]]), self.D.shape[0])
            F = self.D
        else:
            c_weight = (1-d_weight)/2
            N = create_neutral_vector(np.array([[self.D.shape[1], np.sqrt(d_weight)],[self.C_desc.shape[1], np.sqrt(c_weight)],[self.C_rand.shape[1], np.sqrt(c_weight)]]), self.D.shape[0])
            F = np.hstack((np.sqrt(d_weight)*self.D, np.hstack((np.sqrt(c_weight)*self.C_desc, np.sqrt(c_weight)*self.C_rand))))

        self.Y, V = pca.neutral_sub_pca_vector(F, neut_factor*N)

        Y30 = self.Y[:,:30]
        self.closest30 = kclosest.k_closest(30, Y30)
        self.closest5 = self.closest30[kclosest.k_closest(5, Y30[self.closest30,:])]

    def plot(self):
        plothelper.plot_images(np.array(self.image_files)[self.closest30], 3, 10)
        plothelper.plot_images(np.array(self.image_files)[self.closest5], 1, 5)

    def plot_pca(self):
        plothelper.plot_pca_projections(self.Y, 1, 2)
        plothelper.plot_pca_projections(self.Y, 3, 4)

def main(argv):
    api_key = None
    tag = None
    feature_mode = FeatureMode.All
    run_mode = RunMode.Download

    helptext = """To run the bundler from command line enter:

               rsbundler.py -t <tag> -a <apikey>

               The following options are available:

               Required:
               -t : The tag to search for
               -a : The flickr api key

               Optional:
               -f : The feature mode. Possible values:
                    a - Both descriptors and colors. This is the default.
                    d - Descriptors only
                    c - Colors only
               -r : The run mode. Possible values:
                    d - Downloads, extracts, saves and processes images.
                        This is the default.
                    e - Extracts, saves and processes images.
                    o - Loads saved data and processes images.
               """

    try:
        opts, args = getopt.getopt(argv,"ha:t:f:r:", ["apikey=", "tag=", "featuremode=", "runmode="])
    except getopt.GetoptError:
        print helptext
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print helptext
            sys.exit()
        elif opt in ("-a", "--apikey"):
            api_key = arg
        elif opt in ("-t", "--tag"):
            tag = arg
        elif opt in ("-f", "--featuremode"):
            if (arg == "d"):
                feature_mode = FeatureMode.Descriptors
            elif (arg == "c"):
                feature_mode = FeatureMode.Colors
        elif opt in ("-r", "--runmode"):
            if (arg == "e"):
                run_mode = RunMode.Extract
            elif (arg == "o"):
                run_mode = RunMode.Load

    if tag is None:
        sys.exit("""Tag is required. Usage: """ + helptext)

    if api_key is None:
        with open ("flickr_key.txt", "r") as myfile: api_key=myfile.readline().rstrip()

    bundler = FlickrRsBundler(api_key, tag)

    if (run_mode == RunMode.Download):
        bundler.download()
        bundler.extract()
        bundler.save()
    elif (run_mode == RunMode.Extract):
        bundler.extract()
        bundler.save()
    else:
        bundler.load()

    bundler.process(feature_mode)
    bundler.plot()
    bundler.plot_pca()

if __name__ == "__main__":
    main(sys.argv[1:])<commit_msg>Better formatting in bundler.<commit_after>import os.path as op
from os import listdir
import numpy as np
import sys, getopt

from retrieval.flickrwrapper import FlickrWrapper
from features.extract import extract, create_neutral_vector
from analysis import pca, kclosest
from display import plothelper
from features.featuremode import FeatureMode
from runmode import RunMode

class FlickrRsBundler:

    desc_file = "{0}_desc.txt"
    color_desc_file = "{0}_colordesc.txt"
    color_rand_file = "{0}_colorrand.txt"

    def __init__(self, api_key, tag):
        self.flickrWrapper = FlickrWrapper(api_key)
        self.tag = tag
        self.image_dir = op.dirname(op.abspath(__file__)) + "/images/" + self.tag + "/"

        self.image_files = None

        self.D = None
        self.C_desc = None
        self.C_rand = None

        self.Y = None
        self.closest30 = None
        self.closest5 = None

    def run(self):
        self.download()
        self.extract()
        self.save()
        self.process()
        self.plot()

    def download(self):
        self.flickrWrapper.download(self.image_dir, self.tag)

    def files(self):
        self.image_files = [op.join(self.image_dir,f) for f in listdir(self.image_dir) if op.isfile(op.join(self.image_dir,f)) and f.endswith(".jpg")]

    def extract(self):
        self.files()
        self.D, self.C_desc, self.C_rand = extract(self.image_files)

    def save(self):
        np.savetxt(self.image_dir + self.desc_file.format(self.tag), self.D)
        np.savetxt(self.image_dir + self.color_desc_file.format(self.tag), self.C_desc)
        np.savetxt(self.image_dir + self.color_rand_file.format(self.tag), self.C_rand)

    def load(self):
        self.files()
        self.D = np.loadtxt(self.image_dir + self.desc_file.format(self.tag), float)
        self.C_desc = np.loadtxt(self.image_dir + self.color_desc_file.format(self.tag), float)
        self.C_rand = np.loadtxt(self.image_dir + self.color_rand_file.format(self.tag), float)

    def process(self, mode=FeatureMode.All, neut_factor=0.8, d_weight=0.725):

        if mode == FeatureMode.Colors:
            N = create_neutral_vector(np.array([[self.C_rand.shape[1], 1]]), self.C_rand.shape[0])
            F = self.C_rand
        elif mode == FeatureMode.Descriptors:
            N = create_neutral_vector(np.array([[self.D.shape[1], 1]]), self.D.shape[0])
            F = self.D
        else:
            c_weight = (1-d_weight)/2
            N = create_neutral_vector(
                np.array([[self.D.shape[1], np.sqrt(d_weight)],
                          [self.C_desc.shape[1], np.sqrt(c_weight)],
                          [self.C_rand.shape[1], np.sqrt(c_weight)]]),
                self.D.shape[0])
            F = np.hstack((np.sqrt(d_weight)*self.D,
                           np.hstack((np.sqrt(c_weight)*self.C_desc, np.sqrt(c_weight)*self.C_rand))))

        self.Y, V = pca.neutral_sub_pca_vector(F, neut_factor*N)

        Y30 = self.Y[:,:30]
        self.closest30 = kclosest.k_closest(30, Y30)
        self.closest5 = self.closest30[kclosest.k_closest(5, Y30[self.closest30,:])]

    def plot(self):
        plothelper.plot_images(np.array(self.image_files)[self.closest30], 3, 10)
        plothelper.plot_images(np.array(self.image_files)[self.closest5], 1, 5)

    def plot_pca(self):
        plothelper.plot_pca_projections(self.Y, 1, 2)
        plothelper.plot_pca_projections(self.Y, 3, 4)

def main(argv):
    api_key = None
    tag = None
    feature_mode = FeatureMode.All
    run_mode = RunMode.Download

    helptext = """To run the bundler from command line enter:

               rsbundler.py -t <tag> -a <apikey>

               The following options are available:

               Required:
               -t : The tag to search for
               -a : The flickr api key

               Optional:
               -f : The feature mode. Possible values:
                    a - Both descriptors and colors. This is the default.
                    d - Descriptors only
                    c - Colors only
               -r : The run mode. Possible values:
                    d - Downloads, extracts, saves and processes images.
                        This is the default.
                    e - Extracts, saves and processes images.
                    o - Loads saved data and processes images.
               """

    try:
        opts, args = getopt.getopt(argv,"ha:t:f:r:", ["apikey=", "tag=", "featuremode=", "runmode="])
    except getopt.GetoptError:
        print helptext
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print helptext
            sys.exit()
        elif opt in ("-a", "--apikey"):
            api_key = arg
        elif opt in ("-t", "--tag"):
            tag = arg
        elif opt in ("-f", "--featuremode"):
            if (arg == "d"):
                feature_mode = FeatureMode.Descriptors
            elif (arg == "c"):
                feature_mode = FeatureMode.Colors
        elif opt in ("-r", "--runmode"):
            if (arg == "e"):
                run_mode = RunMode.Extract
            elif (arg == "o"):
                run_mode = RunMode.Load

    if tag is None:
        sys.exit("""Tag is required. Usage: """ + helptext)

    if api_key is None:
        with open ("flickr_key.txt", "r") as myfile: api_key=myfile.readline().rstrip()

    bundler = FlickrRsBundler(api_key, tag)

    if (run_mode == RunMode.Download):
        bundler.download()
        bundler.extract()
        bundler.save()
    elif (run_mode == RunMode.Extract):
        bundler.extract()
        bundler.save()
    else:
        bundler.load()

    bundler.process(feature_mode)
    bundler.plot()
    bundler.plot_pca()

if __name__ == "__main__":
    main(sys.argv[1:])<|endoftext|>


<commit_before>
from sequana.gff3 import GFF3
from sequana import sequana_data
from easydev import TempFile

def test_gff():
    gff = GFF3(sequana_data('test_small.gff3'))
    df = gff.df
    assert "telomere" in gff.features

def test_gff_rnadiff():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    df = gff.df
    gff.get_duplicated_attributes_per_type()
    with TempFile() as fout:
        gff.create_files_for_rnadiff(fout.name)

        import pandas as pd
        df1 = pd.read_csv("{}_gene_lengths.tsv".format(fout.name), sep='\t')
        # changed in 21/07/2021 from 31755 to 29199.
        # not clear why the sum was 31755 before. 291999 check manually in the
        # GFF file
         assert df1.Length.sum() == 29199

    with TempFile() as fout:
        gff.save_annotation_to_csv(fout.name)

def test_gff_to_gtf():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    with TempFile() as fout:
        df = gff.to_gtf(fout.name)

def test_save_gff_filtered():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    with TempFile() as fout:
        df = gff.save_gff_filtered(filename=fout.name)
<commit_msg>Update test_gff3.py<commit_after>
from sequana.gff3 import GFF3
from sequana import sequana_data
from easydev import TempFile

def test_gff():
    gff = GFF3(sequana_data('test_small.gff3'))
    df = gff.df
    assert "telomere" in gff.features

def test_gff_rnadiff():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    df = gff.df
    gff.get_duplicated_attributes_per_type()
    with TempFile() as fout:
        gff.create_files_for_rnadiff(fout.name)

        import pandas as pd
        df1 = pd.read_csv("{}_gene_lengths.tsv".format(fout.name), sep='\t')
        # changed in 21/07/2021 from 31755 to 29199.
        # not clear why the sum was 31755 before. 291999 check manually in the
        # GFF file
        assert df1.Length.sum() == 29199

    with TempFile() as fout:
        gff.save_annotation_to_csv(fout.name)

def test_gff_to_gtf():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    with TempFile() as fout:
        df = gff.to_gtf(fout.name)

def test_save_gff_filtered():
    gff = GFF3(sequana_data('saccer3_truncated.gff'))
    with TempFile() as fout:
        df = gff.save_gff_filtered(filename=fout.name)
<|endoftext|>


<commit_before>from __future__ import unicode_literals, absolute_import
import os
import sys
import unittest
try:
    from StringIO import StringIO
except Exception as e:
    from io import StringIO

from greb import meaning as greb

from . import data

class TestGreb(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = greb.read_page(url)
            self.assertEqual(status_code, expected_status_code)

    def test_find_meaning(self):
        for each_word, each_word_meaning in data.INPUT_WORDS['MEANING'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            meaning = greb.find_meaning(tree)
            self.assertEqual(meaning, each_word_meaning)

    def test_find_sentences(self):
        for each_word, each_word_sentence in data.INPUT_WORDS['SENTENCE'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            sentence = greb.find_sentences(tree, each_word)
            self.assertEqual(sentence, each_word_sentence)

    def test_find_synonyms(self):
        for each_word, each_word_synonym in data.INPUT_WORDS['SYNONYM'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            synonym = greb.find_synonyms(tree)
            self.assertEqual(synonym, each_word_synonym)

    def test_find_antonyms(self):
        for each_word, each_word_antonym in data.INPUT_WORDS['ANTONYM'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            antonym = greb.find_antonyms(tree)
            self.assertEqual(antonym, each_word_antonym)

    def test_find_trending_words(self):
        tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['home'])
        self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

        trending_words = greb.find_trending_words(tree)
        self.assertEqual(len(trending_words), 5)

    def test_find_trending_word_with_exception(self):
        for each_word, each_word_dict in data.EXCEPTION_THROWING_WORDS['trending'].items():
            expected_status_code = each_word_dict.get('status_code')
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)
            suggestions = greb.find_suggestions(tree)
            trending_words = greb.find_trending_words(tree)
            self.assertEqual(trending_words, each_word_dict.get('console_output'))

    def test_find_word_of_the_day(self):
        tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['home'])
        self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

        word_of_day = greb.find_word_of_the_day(tree)
        self.assertEqual(len(word_of_day), 1)

    def test_find_suggestions(self):
        for each_word, each_word_dict in data.MISSPELLED_WORDS.items():
            expected_status_code = each_word_dict.get('status_code')
            suggestion_string = each_word_dict.get('suggestion_string')
            suggestion_key = each_word_dict.get('suggestion_key')
            # expected_suggestions = each_word_dict.get('suggestions')

            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)

            self.assertIn(suggestion_string, tree.get_text())

            result = greb.find_suggestions(tree)
            self.assertIn(suggestion_key, result)
            # suggestions = result.get('suggestion')
            # self.assertEqual(suggestions, expected_suggestions)

    def test_find_suggestions_with_exception(self):
        for each_word, each_word_dict in data.EXCEPTION_THROWING_WORDS['suggestions'].items():
            expected_status_code = each_word_dict.get('status_code')
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)
            suggestions = greb.find_suggestions(tree)
            self.assertEqual(suggestions, each_word_dict.get('console_output'))

    def test_print_heading(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_heading(data.PRINT_FUNCTION['print_heading']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_heading']['output'])

    def test_print_word(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_word(data.PRINT_FUNCTION['print_word']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_word']['output'])

    def test_print_error_messages(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_error_messages(data.PRINT_FUNCTION['print_error_messages']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_error_messages']['output'])

    def test_print_result_for_info_msg(self):

        result = {}
        result['info_msg'] = data.PRINT_FUNCTION['print_result_for_info_msg']['input']
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_result(result)
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_result_for_info_msg']['output'])

    def test_print_result_for_error_msg(self):

        result = {}
        result['erroneous_key'] = data.PRINT_FUNCTION['print_result_for_error_msg']['input']
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_result(result)
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_result_for_error_msg']['output'])

    def test_write_meaning_to_file(self):

        dummy_meaning_file = os.path.join(os.getcwd(), 'test', 'dummy_meaning.json')
        options = {'word': 'awesome', 'meaning': True, 'file_path': dummy_meaning_file}

        greb.greb(**options)

    def test_write_and_find_meaning_from_history(self):

        dummy_meaning_file = os.path.join(os.getcwd(), 'test', 'dummy_meaning.json')

        greb.find_meaning_from_history(file_path=dummy_meaning_file)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Test: Remove dummy meaning file after test completes<commit_after>from __future__ import unicode_literals, absolute_import
import os
import sys
import unittest
try:
    from StringIO import StringIO
except Exception as e:
    from io import StringIO

from greb import meaning as greb

from . import data

class TestGreb(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = greb.read_page(url)
            self.assertEqual(status_code, expected_status_code)

    def test_find_meaning(self):
        for each_word, each_word_meaning in data.INPUT_WORDS['MEANING'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            meaning = greb.find_meaning(tree)
            self.assertEqual(meaning, each_word_meaning)

    def test_find_sentences(self):
        for each_word, each_word_sentence in data.INPUT_WORDS['SENTENCE'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            sentence = greb.find_sentences(tree, each_word)
            self.assertEqual(sentence, each_word_sentence)

    def test_find_synonyms(self):
        for each_word, each_word_synonym in data.INPUT_WORDS['SYNONYM'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            synonym = greb.find_synonyms(tree)
            self.assertEqual(synonym, each_word_synonym)

    def test_find_antonyms(self):
        for each_word, each_word_antonym in data.INPUT_WORDS['ANTONYM'].items():
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

            antonym = greb.find_antonyms(tree)
            self.assertEqual(antonym, each_word_antonym)

    def test_find_trending_words(self):
        tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['home'])
        self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

        trending_words = greb.find_trending_words(tree)
        self.assertEqual(len(trending_words), 5)

    def test_find_trending_word_with_exception(self):
        for each_word, each_word_dict in data.EXCEPTION_THROWING_WORDS['trending'].items():
            expected_status_code = each_word_dict.get('status_code')
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)
            suggestions = greb.find_suggestions(tree)
            trending_words = greb.find_trending_words(tree)
            self.assertEqual(trending_words, each_word_dict.get('console_output'))

    def test_find_word_of_the_day(self):
        tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['home'])
        self.assertEqual(status_code, data.COMMON['STATUS_CODE']['ok'])

        word_of_day = greb.find_word_of_the_day(tree)
        self.assertEqual(len(word_of_day), 1)

    def test_find_suggestions(self):
        for each_word, each_word_dict in data.MISSPELLED_WORDS.items():
            expected_status_code = each_word_dict.get('status_code')
            suggestion_string = each_word_dict.get('suggestion_string')
            suggestion_key = each_word_dict.get('suggestion_key')
            # expected_suggestions = each_word_dict.get('suggestions')

            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)

            self.assertIn(suggestion_string, tree.get_text())

            result = greb.find_suggestions(tree)
            self.assertIn(suggestion_key, result)
            # suggestions = result.get('suggestion')
            # self.assertEqual(suggestions, expected_suggestions)

    def test_find_suggestions_with_exception(self):
        for each_word, each_word_dict in data.EXCEPTION_THROWING_WORDS['suggestions'].items():
            expected_status_code = each_word_dict.get('status_code')
            tree, status_code = greb.make_parse_tree(data.COMMON['URLS']['base'].format(word=each_word))
            self.assertEqual(status_code, expected_status_code)
            suggestions = greb.find_suggestions(tree)
            self.assertEqual(suggestions, each_word_dict.get('console_output'))

    def test_print_heading(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_heading(data.PRINT_FUNCTION['print_heading']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_heading']['output'])

    def test_print_word(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_word(data.PRINT_FUNCTION['print_word']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_word']['output'])

    def test_print_error_messages(self):
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_error_messages(data.PRINT_FUNCTION['print_error_messages']['input'])
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_error_messages']['output'])

    def test_print_result_for_info_msg(self):

        result = {}
        result['info_msg'] = data.PRINT_FUNCTION['print_result_for_info_msg']['input']
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_result(result)
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_result_for_info_msg']['output'])

    def test_print_result_for_error_msg(self):

        result = {}
        result['erroneous_key'] = data.PRINT_FUNCTION['print_result_for_error_msg']['input']
        captured_output = StringIO()
        sys.stdout = captured_output
        greb.print_result(result)
        sys.stdout = sys.__stdout__
        self.assertEqual(captured_output.getvalue(), data.PRINT_FUNCTION['print_result_for_error_msg']['output'])

    def test_write_meaning_to_file(self):

        dummy_meaning_file = os.path.join(os.getcwd(), 'test', 'dummy_meaning.json')
        options = {'word': 'awesome', 'meaning': True, 'file_path': dummy_meaning_file}
        greb.greb(**options)
        os.remove(dummy_meaning_file)

    def test_write_and_find_meaning_from_history(self):

        dummy_meaning_file = os.path.join(os.getcwd(), 'test', 'dummy_meaning.json')

        greb.find_meaning_from_history(file_path=dummy_meaning_file)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# coding=utf-8

import os
import re
import time
import datetime
import hashlib
import string
import random

import config

from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Note

from v2ex.babel import SYSTEM_VERSION

from v2ex.babel.security import *
from v2ex.babel.ua import *
from v2ex.babel.da import *
from v2ex.babel.l10n import *
from v2ex.babel.ext.cookies import Cookies

template.register_template_library('v2ex.templatetags.filters')

class SSOV0Handler(webapp.RequestHandler):
    def get(self):
        site = GetSite()
        self.response.headers['Content-type'] = 'application/json'
        u = self.request.get('u').strip().lower()
        p = self.request.get('p').strip()
        failed = '{"ok" : 0}'
        if (len(u) > 0) and (len(p) > 0):
            q = db.GqlQuery("SELECT * FROM Member WHERE username_lower = :1 AND password = :2", u, p)
            if q.count() > 0:
                member = q[0]
                if member.avatar_mini_url:
                    if (member.avatar_mini_url[0:1] == '/'):
                        member.avatar_mini_url = 'http://' + site.domain + member.avatar_mini_url
                        member.avatar_normal_url = 'http://' +  site.domain + member.avatar_normal_url
                        member.avatar_large_url = 'http://' + site.domain + member.avatar_large_url
                else:
                    member.avatar_mini_url = 'http://' + site.domain + '/static/img/avatar_mini.png'
                    member.avatar_normal_url = 'http://' + site.domain + '/static/img/avatar_normal.png'
                    member.avatar_large_url = 'http://' + site.domain + '/static/img/avatar_large.png'
                self.response.out.write('{"ok" : 1, "num" : ' + str(member.num) + ', "username" : "' + member.username + '", "username_lower" : "' + member.username_lower + '", "email" : "' + member.email + '", "avatar_mini_url" : "' + member.avatar_mini_url + '", "avatar_normal_url" : "' + member.avatar_normal_url + '", "avatar_large_url" : "' + member.avatar_large_url + '", "created" : ' + str(time.mktime(member.created.timetuple())) + ', "last_modified" : ' + str(time.mktime(member.last_modified.timetuple())) + '}')
            else:
                self.response.out.write(failed)
        else:
            self.response.out.write(failed)

class SSOX0Handler(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-type'] = 'application/json'
        x = self.request.get('x').strip()
        n = self.request.get('n').strip().lower()
        failed = '{"ok" : 0}'
        if x == config.ssox:
            q = db.GqlQuery("SELECT * FROM Member WHERE username_lower = :1", n)
            if q.count() > 0:
                member = q[0]
                if member.avatar_mini_url:
                    site = GetSite()
                    if (member.avatar_mini_url[0:1] == '/'):
                        member.avatar_mini_url = 'http://' + site.domain + member.avatar_mini_url
                        member.avatar_normal_url = 'http://' +  site.domain + member.avatar_normal_url
                        member.avatar_large_url = 'http://' + site.domain + member.avatar_large_url
                else:
                    member.avatar_mini_url = 'http://' + site.domain + '/static/img/avatar_mini.png'
                    member.avatar_normal_url = 'http://' + site.domain + '/static/img/avatar_normal.png'
                    member.avatar_large_url = 'http://' + site.domain + '/static/img/avatar_large.png'
                self.response.out.write('{"ok" : 1, "num" : ' + str(member.num) + ', "username" : "' + member.username + '", "username_lower" : "' + member.username_lower + '", "email" : "' + member.email + '", "password" : "' + member.password + '", "avatar_mini_url" : "' + member.avatar_mini_url + '", "avatar_normal_url" : "' + member.avatar_normal_url + '", "avatar_large_url" : "' + member.avatar_large_url + '", "created" : ' + str(time.mktime(member.created.timetuple())) + ', "last_modified" : ' + str(time.mktime(member.last_modified.timetuple())) + '}')
            else:
                self.response.out.write(failed)
        else:
            self.response.out.write(failed)

def main():
    application = webapp.WSGIApplication([
    ('/sso/v0', SSOV0Handler),
    ('/sso/x0', SSOX0Handler)
    ],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()<commit_msg>Fixed a bug.<commit_after>#!/usr/bin/env python
# coding=utf-8

import os
import re
import time
import datetime
import hashlib
import string
import random

import config

from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Note

from v2ex.babel import SYSTEM_VERSION

from v2ex.babel.security import *
from v2ex.babel.ua import *
from v2ex.babel.da import *
from v2ex.babel.l10n import *
from v2ex.babel.ext.cookies import Cookies

template.register_template_library('v2ex.templatetags.filters')

class SSOV0Handler(webapp.RequestHandler):
    def get(self):
        site = GetSite()
        self.response.headers['Content-type'] = 'application/json'
        u = self.request.get('u').strip().lower()
        p = self.request.get('p').strip()
        failed = '{"ok" : 0}'
        if (len(u) > 0) and (len(p) > 0):
            q = db.GqlQuery("SELECT * FROM Member WHERE username_lower = :1 AND password = :2", u, p)
            if q.count() > 0:
                member = q[0]
                if member.avatar_mini_url:
                    if (member.avatar_mini_url[0:1] == '/'):
                        member.avatar_mini_url = 'http://' + site.domain + member.avatar_mini_url
                        member.avatar_normal_url = 'http://' +  site.domain + member.avatar_normal_url
                        member.avatar_large_url = 'http://' + site.domain + member.avatar_large_url
                else:
                    member.avatar_mini_url = 'http://' + site.domain + '/static/img/avatar_mini.png'
                    member.avatar_normal_url = 'http://' + site.domain + '/static/img/avatar_normal.png'
                    member.avatar_large_url = 'http://' + site.domain + '/static/img/avatar_large.png'
                self.response.out.write('{"ok" : 1, "num" : ' + str(member.num) + ', "username" : "' + member.username + '", "username_lower" : "' + member.username_lower + '", "email" : "' + member.email + '", "avatar_mini_url" : "' + member.avatar_mini_url + '", "avatar_normal_url" : "' + member.avatar_normal_url + '", "avatar_large_url" : "' + member.avatar_large_url + '", "created" : ' + str(time.mktime(member.created.timetuple())) + ', "last_modified" : ' + str(time.mktime(member.last_modified.timetuple())) + '}')
            else:
                self.response.out.write(failed)
        else:
            self.response.out.write(failed)

class SSOX0Handler(webapp.RequestHandler):
    def get(self):
        site = GetSite()
        self.response.headers['Content-type'] = 'application/json'
        x = self.request.get('x').strip()
        n = self.request.get('n').strip().lower()
        failed = '{"ok" : 0}'
        if x == config.ssox:
            q = db.GqlQuery("SELECT * FROM Member WHERE username_lower = :1", n)
            if q.count() > 0:
                member = q[0]
                if member.avatar_mini_url:
                    if (member.avatar_mini_url[0:1] == '/'):
                        member.avatar_mini_url = 'http://' + site.domain + member.avatar_mini_url
                        member.avatar_normal_url = 'http://' +  site.domain + member.avatar_normal_url
                        member.avatar_large_url = 'http://' + site.domain + member.avatar_large_url
                else:
                    member.avatar_mini_url = 'http://' + site.domain + '/static/img/avatar_mini.png'
                    member.avatar_normal_url = 'http://' + site.domain + '/static/img/avatar_normal.png'
                    member.avatar_large_url = 'http://' + site.domain + '/static/img/avatar_large.png'
                self.response.out.write('{"ok" : 1, "num" : ' + str(member.num) + ', "username" : "' + member.username + '", "username_lower" : "' + member.username_lower + '", "email" : "' + member.email + '", "password" : "' + member.password + '", "avatar_mini_url" : "' + member.avatar_mini_url + '", "avatar_normal_url" : "' + member.avatar_normal_url + '", "avatar_large_url" : "' + member.avatar_large_url + '", "created" : ' + str(time.mktime(member.created.timetuple())) + ', "last_modified" : ' + str(time.mktime(member.last_modified.timetuple())) + '}')
            else:
                self.response.out.write(failed)
        else:
            self.response.out.write(failed)

def main():
    application = webapp.WSGIApplication([
    ('/sso/v0', SSOV0Handler),
    ('/sso/x0', SSOX0Handler)
    ],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import unittest

import logging
import test_common
from StringIO import StringIO

from flvlib import primitives, astypes, tags

tags.STRICT_PARSING = True

class TestTag(unittest.TestCase):

    def test_simple_parse(self):
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        t.parse()

        self.assertEquals(s.read(), '')
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 10)
        self.assertEquals(t.timestamp, 9823)

    def test_negative_timestamp(self):
        s = StringIO('\x00\x00\x0f\xcc\xff\x1b\xff\x00\x00\x00' +
                     '\x11' * 15 +
                     '\x00\x00\x00\x1a')
        t = tags.Tag(None, s)

        # This should give a warning
        f = test_common.WarningCounterFilter()
        logging.getLogger('flvlib.tags').addFilter(f)
        t.parse()
        logging.getLogger('flvlib.tags').removeFilter(f)

        self.assertEquals(f.warnings, 1)

        self.assertEquals(s.read(), '')
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 15)
        self.assertEquals(t.timestamp, -3342565)

    def test_zero_size_data(self):
        s = StringIO('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b')
        t = tags.Tag(None, s)
        t.parse()

        self.assertEquals(s.read(), '')
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 0)
        self.assertEquals(t.timestamp, 0)

    def test_errors(self):
        # nonzero StreamID
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x01' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # PreviousTagSize too small
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x14')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # PreviousTagSize too big
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x16')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # DataSize too big
        s = StringIO('\x00\x00\x10\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.EndOfFile, t.parse)

        # file too short
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00')
        t = tags.Tag(None, s)
        self.assertRaises(primitives.EndOfFile, t.parse)
<commit_msg>Add complete test suite for the tags module.<commit_after># -*- coding: utf-8 -*-

import unittest

import logging
import test_common
from StringIO import StringIO

from flvlib import constants, primitives, astypes, tags

class LStringIO(StringIO):
    """
    A StringIO that lies about its tell() position.

    Useful to simulate being in the middle of a file
    """

    def __init__(self, buf='', offset=0):
        self.offset = offset
        StringIO.__init__(self, buf)

    def tell(self):
        return StringIO.tell(self) + self.offset

class TestEnsure(unittest.TestCase):

    def setUp(self):
        self.old_strict = tags.STRICT_PARSING

    def tearDown(self):
        tags.STRICT_PARSING = self.old_strict

    def test_ensure_strict(self):
        tags.STRICT_PARSING = True
        self.assertRaises(tags.MalformedFLV, tags.ensure, 1, 2, "error")

    def test_ensure_nonstrict(self):
        tags.STRICT_PARSING = False
        f = test_common.WarningCounterFilter()
        logging.getLogger('flvlib.tags').addFilter(f)
        tags.ensure(1, 2, "error")
        logging.getLogger('flvlib.tags').removeFilter(f)

        self.assertEquals(f.warnings, 1)

    def test_ensure_noerror(self):
        tags.STRICT_PARSING = True
        tags.ensure(1, 1, "no error")

class TestUnderStrictParsing(unittest.TestCase):

    def setUp(self):
        self.old_strict = tags.STRICT_PARSING
        tags.STRICT_PARSING = True

    def tearDown(self):
        tags.STRICT_PARSING = self.old_strict

class BodyGeneratorMixin(object):

    # this header contains DataSize of 10 and timestamp of 9823
    tag_header = '\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00'
    tag_footer = '\x00\x00\x00\x15'

    DATASIZE = 10

    def tag_body(self, content):
        return (self.tag_header + content +
                '\x00' * (self.DATASIZE - len(content)) + self.tag_footer)

class TestTag(TestUnderStrictParsing):

    def test_simple_parse(self):
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        t.parse()

        self.assertEquals(s.read(), '')
        # the offset should be StringIO.tell() - 1, which means -1
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, BodyGeneratorMixin.DATASIZE)
        self.assertEquals(t.timestamp, 9823)

    def test_negative_timestamp(self):
        s = StringIO('\x00\x00\x0f\xcc\xff\x1b\xff\x00\x00\x00' +
                     '\x11' * 15 +
                     '\x00\x00\x00\x1a')
        t = tags.Tag(None, s)

        # This should give a warning
        f = test_common.WarningCounterFilter()
        logging.getLogger('flvlib.tags').addFilter(f)
        t.parse()
        logging.getLogger('flvlib.tags').removeFilter(f)

        self.assertEquals(f.warnings, 1)

        self.assertEquals(s.read(), '')
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 15)
        self.assertEquals(t.timestamp, -3342565)

    def test_zero_size_data(self):
        s = StringIO('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b')
        t = tags.Tag(None, s)
        t.parse()

        self.assertEquals(s.read(), '')
        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 0)
        self.assertEquals(t.timestamp, 0)

    def test_errors(self):
        # nonzero StreamID
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x01' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # PreviousTagSize too small
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x14')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # PreviousTagSize too big
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x16')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.MalformedFLV, t.parse)

        # DataSize too big
        s = StringIO('\x00\x00\x10\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x11' * 10 +
                     '\x00\x00\x00\x15')
        t = tags.Tag(None, s)
        self.assertRaises(astypes.EndOfFile, t.parse)

        # file too short
        s = StringIO('\x00\x00\x0a\x00\x26\x5f\x00')
        t = tags.Tag(None, s)
        self.assertRaises(primitives.EndOfFile, t.parse)

class TestAudioTag(TestUnderStrictParsing, BodyGeneratorMixin):

    def test_simple_sound_flags(self):
        s = StringIO(self.tag_body('\x2d'))
        t = tags.AudioTag(None, s)
        t.parse()

        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, BodyGeneratorMixin.DATASIZE)
        self.assertEquals(t.timestamp, 9823)
        self.assertEquals(t.sound_format, constants.SOUND_FORMAT_MP3)
        self.assertEquals(t.sound_rate, constants.SOUND_RATE_44_KHZ)
        self.assertEquals(t.sound_size, constants.SOUND_SIZE_8_BIT)
        self.assertEquals(t.sound_type, constants.SOUND_TYPE_STEREO)

    def test_sound_flags_aac(self):
        s = StringIO(self.tag_body('\xaf\x01'))
        t = tags.AudioTag(None, s)
        t.parse()

        self.assertEquals(t.sound_format, constants.SOUND_FORMAT_AAC)
        self.assertEquals(t.sound_rate, constants.SOUND_RATE_44_KHZ)
        self.assertEquals(t.sound_size, constants.SOUND_SIZE_16_BIT)
        self.assertEquals(t.sound_type, constants.SOUND_TYPE_STEREO)
        self.assertEquals(t.aac_packet_type, constants.AAC_PACKET_TYPE_RAW)

    def test_errors(self):
        # wrong sound format
        t = tags.AudioTag(None, StringIO(self.tag_body('\x9f')))
        self.assertRaises(tags.MalformedFLV, t.parse)

        # wrong sound rate for AAC
        t = tags.AudioTag(None, StringIO(self.tag_body('\xa3')))
        self.assertRaises(tags.MalformedFLV, t.parse)

        # wrong sound type for AAC
        t = tags.AudioTag(None, StringIO(self.tag_body('\xa2')))
        self.assertRaises(tags.MalformedFLV, t.parse)

        # wrong packet type for AAC
        t = tags.AudioTag(None, StringIO(self.tag_body('\xaf\x03')))
        self.assertRaises(tags.MalformedFLV, t.parse)

    def test_repr(self):
        t = tags.AudioTag(None, LStringIO(self.tag_body('\xbb'), 10))
        self.assertEquals(repr(t), "<AudioTag unparsed>")

        t.parse()
        self.assertEquals(repr(t),
                          "<AudioTag at offset 0x00000009, "
                          "time 9823, size 10, Speex>")

        t = tags.AudioTag(None, LStringIO(self.tag_body('\xaf\x01'), 10))
        t.parse()
        self.assertEquals(repr(t),
                          "<AudioTag at offset 0x00000009, "
                          "time 9823, size 10, AAC, raw>")

class TestVideoTag(TestUnderStrictParsing, BodyGeneratorMixin):

    def test_simple_video_flags(self):
        s = StringIO(self.tag_body('\x22'))
        t = tags.VideoTag(None, s)
        t.parse()

        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, BodyGeneratorMixin.DATASIZE)
        self.assertEquals(t.timestamp, 9823)
        self.assertEquals(t.frame_type, constants.FRAME_TYPE_INTERFRAME)
        self.assertEquals(t.codec_id, constants.CODEC_ID_H263)

    def test_video_flags_h264(self):
        s = StringIO(self.tag_body('\x17\x01'))
        t = tags.VideoTag(None, s)
        t.parse()

        self.assertEquals(t.frame_type, constants.FRAME_TYPE_KEYFRAME)
        self.assertEquals(t.codec_id, constants.CODEC_ID_H264)
        self.assertEquals(t.h264_packet_type, constants.H264_PACKET_TYPE_NALU)

    def test_errors(self):
        # wrong frame type
        t = tags.VideoTag(None, StringIO(self.tag_body('\x01')))
        self.assertRaises(tags.MalformedFLV, t.parse)

        # wrong codec ID
        t = tags.VideoTag(None, StringIO(self.tag_body('\x18')))
        self.assertRaises(tags.MalformedFLV, t.parse)

        # wrong packet type for H.264
        t = tags.VideoTag(None, StringIO(self.tag_body('\x27\x04')))
        self.assertRaises(tags.MalformedFLV, t.parse)

    def test_repr(self):
        t = tags.VideoTag(None, LStringIO(self.tag_body('\x11'), 10))
        self.assertEquals(repr(t), "<VideoTag unparsed>")

        t.parse()
        self.assertEquals(repr(t),
                          "<VideoTag at offset 0x00000009, "
                          "time 9823, size 10, JPEG (keyframe)>")

        t = tags.VideoTag(None, LStringIO(self.tag_body('\x27\x01'), 10))
        t.parse()
        self.assertEquals(repr(t),
                          "<VideoTag at offset 0x00000009, "
                          "time 9823, size 10, H.264 (interframe), NAL unit>")

class TestScriptTag(TestUnderStrictParsing):

    def test_simple_script_tag(self):
        s = StringIO('\x00\x00\x07\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x02\x00\x03\x66\x6f\x6f\x05\x00\x00\x00\x12')
        t = tags.ScriptTag(None, s)
        t.parse()

        self.assertEquals(t.offset, -1)
        self.assertEquals(t.size, 7)
        self.assertEquals(t.timestamp, 9823)
        self.assertEquals(t.name, 'foo')
        self.assertTrue(t.variable is None)

    def test_variable_parsing(self):
        s = StringIO('\x00\x00\x28\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x02\x00\x0aonMetaData\x08\x00\x00\x00\x01' +
                     '\x00\x08duration\x00\x3f\xf0\x00\x00\x00\x00\x00\x00' +
                     '\x00\x00\x09\x00\x00\x00\x33')
        t = tags.ScriptTag(None, s)
        t.parse()

        self.assertEquals(t.name, 'onMetaData')
        self.assertEquals(t.variable, {'duration': 1.0})

        # try an ECMAArray without the marker and without strict parsing

        tags.STRICT_PARSING = False
        s = StringIO('\x00\x00\x25\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x02\x00\x0aonMetaData\x08\x00\x00\x00\x01' +
                     '\x00\x08duration\x00\x3f\xf0\x00\x00\x00\x00\x00\x00' +
                     '\x00\x00\x00\x30')
        t = tags.ScriptTag(None, s)
        t.parse()
        tags.STRICT_PARSING = True

        self.assertEquals(t.name, 'onMetaData')
        self.assertEquals(t.variable, {'duration': 1.0})

    def test_errors(self):
        # name is not a string (no 0x02 byte before the name)
        s = StringIO('\x00\x00\x07\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x03\x00\x03\x66\x6f\x6f\x05\x00\x00\x00\x12')
        t = tags.ScriptTag(None, s)
        self.assertRaises(tags.MalformedFLV, t.parse)

        # an ECMAArray without the marer, should fail under strict parsing
        s = StringIO('\x00\x00\x25\x00\x26\x5f\x00\x00\x00\x00' +
                     '\x02\x00\x0aonMetaData\x08\x00\x00\x00\x01' +
                     '\x00\x08duration\x00\x3f\xf0\x00\x00\x00\x00\x00\x00' +
                     '\x00\x00\x00\x30')
        t = tags.ScriptTag(None, s)
        self.assertRaises(primitives.EndOfFile, t.parse)

    def test_repr(self):
        s = LStringIO('\x00\x00\x07\x00\x26\x5f\x00\x00\x00\x00' +
                      '\x02\x00\x03\x66\x6f\x6f\x05\x00\x00\x00\x12', 10)
        t = tags.ScriptTag(None, s)
        self.assertEquals(repr(t), "<ScriptTag unparsed>")

        t.parse()
        self.assertEquals(repr(t),
                          "<ScriptTag foo at offset 0x00000009, "
                          "time 9823, size 7>")

class TestFLV(TestUnderStrictParsing, BodyGeneratorMixin):

    def test_simple_parse(self):
        s = StringIO('FLV\x00\x04\x00\x00\x00\x09\x00\x00\x00\x00')
        f = tags.FLV(s)
        f.parse_header()

        self.assertEquals(f.version, 0)
        self.assertEquals(f.has_audio, True)
        self.assertEquals(f.has_video, False)

    def test_parse_tags(self):
        s = StringIO('FLV\x00\x05\x00\x00\x00\x09\x00\x00\x00\x00' +
                     '\x08' + self.tag_body('\x4b') +
                     '\x08' + self.tag_body('\xbb') +
                     '\x09' + self.tag_body('\x17\x00') +
                     '\x12' + ('\x00\x00\x07\x00\x26\x5f\x00\x00\x00\x00' +
                               '\x02\x00\x03\x66\x6f\x6f\x05\x00\x00\x00\x12'))
        f = tags.FLV(s)
        f.read_tags()

        self.assertEquals(f.version, 0)
        self.assertEquals(f.has_audio, True)
        self.assertEquals(f.has_video, True)

        self.assertEquals(len(f.tags), 4)
        self.assertTrue(isinstance(f.tags[0], tags.AudioTag))
        self.assertTrue(isinstance(f.tags[1], tags.AudioTag))
        self.assertTrue(isinstance(f.tags[2], tags.VideoTag))
        self.assertTrue(isinstance(f.tags[3], tags.ScriptTag))

    def test_errors(self):
        # file shorter than 3 bytes
        s = StringIO()
        f = tags.FLV(s)
        self.assertRaises(tags.MalformedFLV, f.read_tags)

        # header invalid
        s = StringIO('XLV\x00\x04\x00\x00\x00\x09\x00\x00\x00\x00')
        f = tags.FLV(s)
        self.assertRaises(tags.MalformedFLV, f.read_tags)

        # invalid tag type
        s = StringIO('FLV\x00\x05\x00\x00\x00\x09\x00\x00\x00\x00' +
                     '\x01' + self.tag_body('\x4b'))
        f = tags.FLV(s)
        self.assertRaises(tags.MalformedFLV, f.read_tags)

class TestCreateTags(TestUnderStrictParsing):

    def test_create_flv_tag(self):
        s = tags.create_flv_tag(0x08, 'random-garbage', 1234)

        self.assertEquals(s, ('\x08\x00\x00\x0e\x00\x04\xd2\x00\x00\x00\x00' +
                              'random-garbage\x00\x00\x00\x19'))

    def test_create_script_tag(self):
        s = tags.create_script_tag('onMetaData', {'silly': True})

        self.assertEquals(s, ('\x12\x00\x00\x1e\x00\x00\x00\x00\x00\x00\x00' +
                              '\x02\x00\x0aonMetaData\x08\x00\x00\x00\x01' +
                              '\x00\x05silly\x01\x01\x00\x00\x09' +
                              '\x00\x00\x00\x29'))

    def test_create_flv_header(self):
        data = (((True, True), 'FLV\x01\x05\x00\x00\x00\t\x00\x00\x00\x00'),
                ((True, False), 'FLV\x01\x04\x00\x00\x00\t\x00\x00\x00\x00'),
                ((False, True), 'FLV\x01\x01\x00\x00\x00\t\x00\x00\x00\x00'),
                ((False, False), 'FLV\x01\x00\x00\x00\x00\t\x00\x00\x00\x00'))

        for has_audio_video, expected in data:
            s = tags.create_flv_header(*has_audio_video)
            self.assertEquals(s, expected)
<|endoftext|>


<commit_before>from browser import window, document
from javascript import JSObject, JSConstructor

GFX = JSObject(window.PIXI)
GFX_Rectangle = JSConstructor(GFX.Rectangle)
GFX_Texture = JSObject(GFX.Texture)
GFX_Texture_fromImage = JSConstructor(GFX_Texture.fromImage)
GFX_Sprite = JSConstructor(GFX.Sprite)
GFX_Graphics = JSConstructor(GFX.Graphics)()
GFX_Text = JSConstructor(GFX.Text)
GFX_DetectRenderer = GFX.autoDetectRenderer
SND = JSObject(window.buzz)
SND_Sound = JSConstructor(SND.sound)

class GFX_Window(object):

  def __init__(self, width, height, onclose):
    self._w = window.open("", "")
    self._stage = JSConstructor(GFX.Container)()
    self._renderer = GFX.autoDetectRenderer(width, height, {'transparent':True})
    self._w.document.body.appendChild(self.renderer.view)
    self._w.onunload = onclose

  def bind(self, evtspec, callback):
    self._w.document.body.bind(evtspec, callback)

  def add(self, obj):
    self._stage.addChild(obj)

  def remove(self, obj):
    self._stage.removeChild(obj)

  def animate(self, stepcallback):
    self._renderer.render(self._stage)
    self._w.requestAnimationFrame(stepcallback)

  def destroy(self):
    self.SND.all().stop()
    self._stage.destroy()

if __name__ == "__main__":
    def close():
        print("Closing Window")

    w = GFX_Window(100, 100, close)
    print("Test Complete")

    <commit_msg>Updated from Brython Server: 7/30/2015 4:46:43 PM<commit_after>from browser import window, document
from javascript import JSObject, JSConstructor

GFX = JSObject(window.PIXI)
GFX_Rectangle = JSConstructor(GFX.Rectangle)
GFX_Texture = JSObject(GFX.Texture)
GFX_Texture_fromImage = JSConstructor(GFX_Texture.fromImage)
GFX_Sprite = JSConstructor(GFX.Sprite)
GFX_Graphics = JSConstructor(GFX.Graphics)()
GFX_Text = JSConstructor(GFX.Text)
GFX_DetectRenderer = GFX.autoDetectRenderer
SND = JSObject(window.buzz)
SND_Sound = JSConstructor(SND.sound)

class GFX_Window(object):

  def __init__(self, width, height, onclose):
    self._w = window.open("", "")
    self._stage = JSConstructor(GFX.Container)()
    self._renderer = GFX.autoDetectRenderer(width, height, {'transparent':True})
    self._w.document.body.appendChild(self.renderer.view)
    self._w.onunload = onclose

  def bind(self, evtspec, callback):
    self._w.document.body.bind(evtspec, callback)

  def add(self, obj):
    self._stage.addChild(obj)

  def remove(self, obj):
    self._stage.removeChild(obj)

  def animate(self, stepcallback):
    self._renderer.render(self._stage)
    self._w.requestAnimationFrame(stepcallback)

  def destroy(self):
    self.SND.all().stop()
    self._stage.destroy()

if __name__ == "__main__":
    def closefunc():
        print("Closing Window")

    w = GFX_Window(100, 100, closefunc)
    print("Test Complete")

    <|endoftext|>


<commit_before>import unittest
import collections

from pyckle import PyckleVisitor, loads

class TestLoads(unittest.TestCase):

    def setUp(self):

        self._valid_test_cases = (
    '42',
    '0x42',
    '0o42',
    '0.42',
    '3+0j',
    '3.2+0.5j',
    '3.2-6.5j',
    '6.5j-4',
    '"some-string"',
    'b"some-bytes"',
    'r"some-raw-string"',
    'True',
    'False',
    'None',
    '("the", "tuple")',
    '["the", "list"]',
    '{"the" : "dict"}',
    '{"the", "set"}',
    'set(("the", "set"))',
    'frozenset(("the", "frozenset"))',
    'dict(a=11, b=12)',
    'complex(2, 2)',)

        self._invalid_test_cases = (
    '1 + 2 (without j)',
    "'a' + 'b'",
    '(1, 2) + (3, 4)',
    '''foo bar'.split(" ")''',
    'Counter("abcdefghaa")',
    'foo = 42',
    'x = lambda x',
    'sorted((1, 2, 3), key=lambda x: x)',
    'def foo(): return 42',
    'class Foo(): pass',
    '(i for i in range(11))',
    '[i for i in range(11)]',
    '{i:i+1 for i in range(11)}')

#   'collections.Counter("abcdefghaa")')
    def testLoads(self):

        gl = PyckleVisitor.__GLOBALS__

        for string in self._valid_test_cases:

            ret = loads(string)
            exp = eval(string, gl)

            self.assertEqual(ret, exp)

    def testLoads2(self):

        gl = PyckleVisitor.__GLOBALS__

        for string in self._invalid_test_cases:

            try:
                ret = loads(string)
            except SyntaxError as se:
                #TODO: we should check the message
                pass
            else:
                self.fail("``{}'' should raise SyntaxError")

if __name__ == '__main__':
    unittest.main()
<commit_msg>Enhance tests<commit_after>import unittest
import collections

from pyckle import PyckleVisitor, loads

class TestLoads(unittest.TestCase):

    def setUp(self):

        self._valid_test_cases = (
    '42',
    '0x42',
    '0o42',
    '0.42',
    '3+0j',
    '3.2+0.5j',
    '3.2-6.5j',
    '6.5j-4',
    '"some-string"',
    'b"some-bytes"',
    'r"some-raw-string"',
    'True',
    'False',
    'None',
    '("the", "tuple")',
    '["the", "list"]',
    '{"the" : "dict"}',
    '{"the", "set"}',
    'set(("the", "set"))',
    'frozenset(("the", "frozenset"))',
    'dict(a=11, b=12)',
    'complex(2, 2)',)

        self._unsupported_test_cases = (
    ('1 + 2',
        ("Illegal expression, only complex numbers are allowed",
         "<string>", 1, 1, "1 + 2")),
    ("'a' + 'b'",
        ("Illegal expression, only complex numbers are allowed",
         "<string>", 1, 1, "'a' + 'b'")),
    ("(1, 2) + (3, 4)",
        ("Illegal expression, only complex numbers are allowed",
         "<string>", 1, 1, "(1, 2) + (3, 4)")),
    ('''"foo bar".split(" ")''',
        ("Only names are supported in attributes, found 'Str'",
         "<string>", 1, 1, '''"foo bar".split(" ")''')),
    ('Counter("abcdefghaa")',
        ("'Counter' is not allowed name",
         "<string>", 1, 1, 'Counter("abcdefghaa")')),
    ('set((lambda x:42, ))',
        ("Unsupported type of node: 'Lambda'",
         "<string>", 1, 6, "set((lambda x:42, ))")),
    ('foo = 42',
        ("invalid syntax",
         "<string>", 1, 5, 'foo = 42')),
    ('def foo(): return 42',
        ("invalid syntax",
         "<string>", 1, 3, 'def foo(): return 42')),
    ('class Foo(): pass',
        ("invalid syntax",
         "<string>", 1, 5, 'class Foo(): pass')),
    ('(i for i in range(11))',
        ("Unsupported type of node: 'GeneratorExp'",
         "<string>", 1, 2, '(i for i in range(11))')),
    ('[i for i in range(11)]',
        ("Unsupported type of node: 'ListComp'",
         "<string>", 1, 2, '[i for i in range(11)]')),
    ('{i:i+1 for i in range(11)}',
        ("Unsupported type of node: 'DictComp'",
         "<string>", 1, 2, '{i:i+1 for i in range(11)}')),
    ('{i for i in range(11)}',
        ("Unsupported type of node: 'SetComp'",
         "<string>", 1, 2, '{i for i in range(11)}')),
        )

#   'collections.Counter("abcdefghaa")')
    def testValidLoads(self):

        gl = PyckleVisitor.__GLOBALS__

        for string in self._valid_test_cases:

            ret = loads(string)
            exp = eval(string, gl)

            self.assertEqual(ret, exp)

    def testUnsupportedLoads(self):

        for string, (msg, filename, lineno, offset, text) in self._unsupported_test_cases:

            try:
                ret = loads(string)
            except SyntaxError as se:
                self.assertTupleEqual(
                (se.msg, se.filename, se.lineno, se.offset, se.text),
                (msg,    filename,    lineno,    offset,    text))
            else:
                self.fail("``{}'' is expected to raise an exception".format(string))

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/python
#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
import os
import sys
import unittest

import bootstrap

from testrunner import pathManager, testhelp

EXCLUDED_PATHS = ['scripts/.*', 'epdb.py', 'stackutil.py', 'test/.*']

def setup():
    xobjPath = pathManager.addExecPath('XOBJ_PATH')
    robjPath = pathManager.addExecPath('ROBJ_PATH')
    pathManager.addResourcePath('TEST_PATH', robjPath + '/test')

def main(argv=None, individual=True):
    if argv is None:
        argv = list(sys.argv)

    from conary.lib import util
    from conary.lib import coveragehook
    sys.excepthook = util.genExcepthook(True, catchSIGUSR1=False)

    handlerClass = testhelp.getHandlerClass(testhelp.ConaryTestSuite,
            lambda handler, environ: os.getenv('ROBJ_PATH'),
            lambda handler, environ: EXCLUDED_PATHS)

    handler = handlerClass(individual=individual)
    results = handler.main(argv)
    return results.getExitCode()

class TestCase(testhelp.TestCase):
    def setUp(self):
        testhelp.TestCase.setUp(self)

        from robj.lib import log
        log.setupLogging()

if __name__ == '__main__':
    setup()
    sys.exit(main(sys.argv, individual=False))
<commit_msg>hook the testserver into each test run<commit_after>#!/usr/bin/python
#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
import os
import sys
import unittest

import bootstrap

from testrunner import pathManager, testhelp

EXCLUDED_PATHS = ['scripts/.*', 'epdb.py', 'stackutil.py', 'test/.*']

def setup():
    xobjPath = pathManager.addExecPath('XOBJ_PATH')
    robjPath = pathManager.addExecPath('ROBJ_PATH')
    pathManager.addResourcePath('TEST_PATH', robjPath + '/test')

def main(argv=None, individual=True):
    if argv is None:
        argv = list(sys.argv)

    from conary.lib import util
    from conary.lib import coveragehook
    sys.excepthook = util.genExcepthook(True, catchSIGUSR1=False)

    handlerClass = testhelp.getHandlerClass(testhelp.ConaryTestSuite,
            lambda handler, environ: os.getenv('ROBJ_PATH'),
            lambda handler, environ: EXCLUDED_PATHS)

    handler = handlerClass(individual=individual)
    results = handler.main(argv)
    return results.getExitCode()

class TestCase(testhelp.TestCase):
    def setUp(self):
        testhelp.TestCase.setUp(self)

        from robj.lib import log
        log.setupLogging()

        import testserver
        ports = testhelp.findPorts(num=1, closeSockets=True)
        self.server = testserver.ThreadServer(port=ports[0])

    def tearDown(self):
        self.server.shutdown()

if __name__ == '__main__':
    setup()
    sys.exit(main(sys.argv, individual=False))
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
"""Simple test suite using unittest.
By clach04 (Chris Clark).

Calling:

    python test/testsuite.py

or
    cd test
    ./testsuite.py

Could use any unitest compatible test runner (nose, etc.)

Aims to test for regressions. Where possible use stdlib to
avoid the need to compile C code.

Known to run clean with:
  * 32bit Linux (python 2.5.2, 2.6)
  * 32bit Windows XP (python 2.4, 2.5, 2.6.1)
"""

import sys
import os
import ctypes
import math
import unittest

test_directory = os.path.abspath(os.path.dirname(__file__))
sys.path.append(test_directory)
sys.path.append(os.path.join(test_directory, '..'))

import ctypesgentest  # TODO consider moving test() from ctypesgentest into this module

class StdlibTest(unittest.TestCase):

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '#include <stdlib.h>\n'
        if sys.platform == "win32":
            # pick something from %windir%\system32\msvc*dll that include stdlib
            libraries=["msvcrt.dll"]
            libraries=["msvcrt"]
        elif sys.platform == "linux2":
            libraries=["libc.so.6"]
        else:
            libraries=["libc"]
        self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_getenv_returns_string(self):
        """Issue 8 - Regression for crash with 64 bit and bad strings on 32 bit.
        See http://code.google.com/p/ctypesgen/issues/detail?id=8
        Test that we get a valid (non-NULL, non-empty) string back
        """
        module = self.module

        if sys.platform == "win32":
            # Check a variable that is already set
            env_var_name = 'USERNAME'  # this is always set (as is windir, ProgramFiles, USERPROFILE, etc.)
            expect_result = os.environ[env_var_name]
            self.assert_(expect_result, 'this should not be None or empty')
        else:
            env_var_name = 'HELLO'
            os.environ[env_var_name] = 'WORLD'  # This doesn't work under win32
            expect_result = 'WORLD'

        result = module.getenv(env_var_name)
        self.failUnlessEqual(expect_result, result)

    def test_getenv_returns_null(self):
        """Related to issue 8. Test getenv of unset variable.
        """
        module = self.module
        env_var_name = 'NOT SET'
        expect_result = None
        try:
            # ensure variable is not set, ignoring not set errors
            del os.environ[env_var_name]
        except KeyError:
            pass
        result = module.getenv(env_var_name)
        self.failUnlessEqual(expect_result, result)

class SimpleMacrosTest(unittest.TestCase):
    """Based on simple_macros.py
    """

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '''
#define A 1
#define B(x,y) x+y
#define C(a,b,c) a?b:c
#define funny(x) "funny" #x
'''
        libraries = None
        self.module, output = ctypesgentest.test(header_str)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_macro_constant_int(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.A, 1)

    def test_macro_addition(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.B(2, 2), 4)

    def test_macro_ternary_true(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.C(True, 1, 2), 1)

    def test_macro_ternary_false(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.C(False, 1, 2), 2)

    def test_macro_string_compose(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.funny("bunny"),  "funnybunny")

class StructuresTest(unittest.TestCase):
    """Based on structures.py
    """

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '''
struct foo
{
        int a;
        int b;
        int c;
};
'''
        libraries = None
        self.module, output = ctypesgentest.test(header_str)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_structures(self):
        """Tests from structures.py
        """
        module = self.module

        struct_foo = module.struct_foo
        self.failUnlessEqual(struct_foo._fields_, [("a", ctypes.c_int), ("b", ctypes.c_int), ("c", ctypes.c_int)])

class MathTest(unittest.TestCase):
    """Based on math_functions.py"""

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '#include <math.h>\n'
        if sys.platform == "win32":
            # pick something from %windir%\system32\msvc*dll that include stdlib
            libraries=["msvcrt.dll"]
            libraries=["msvcrt"]
        elif sys.platform == "linux2":
            libraries=["libm.so.6"]
        else:
            libraries=["libc"]
        self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_sin(self):
        """Based on math_functions.py"""
        module = self.module

        self.failUnlessEqual(module.sin(2), math.sin(2))

    def test_sqrt(self):
        """Based on math_functions.py"""
        module = self.module

        self.failUnlessEqual(module.sqrt(4), 2)

        def local_test():
            module.sin("foobar")

        self.failUnlessRaises(ctypes.ArgumentError, local_test)

    def test_bad_args_string_not_number(self):
        """Based on math_functions.py"""
        module = self.module

        def local_test():
            module.sin("foobar")

        self.failUnlessRaises(ctypes.ArgumentError, local_test)

def main(argv=None):
    if argv is None:
        argv = sys.argv

    unittest.main()

    return 0

if __name__ == "__main__":
    sys.exit(main())
<commit_msg>Added new simple macro tests (math related), total number of tests is 17.<commit_after>#!/usr/bin/env python
# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
"""Simple test suite using unittest.
By clach04 (Chris Clark).

Calling:

    python test/testsuite.py

or
    cd test
    ./testsuite.py

Could use any unitest compatible test runner (nose, etc.)

Aims to test for regressions. Where possible use stdlib to
avoid the need to compile C code.

Known to run clean with:
  * 32bit Linux (python 2.5.2, 2.6)
  * 32bit Windows XP (python 2.4, 2.5, 2.6.1)
"""

import sys
import os
import ctypes
import math
import unittest

test_directory = os.path.abspath(os.path.dirname(__file__))
sys.path.append(test_directory)
sys.path.append(os.path.join(test_directory, '..'))

import ctypesgentest  # TODO consider moving test() from ctypesgentest into this module

class StdlibTest(unittest.TestCase):

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '#include <stdlib.h>\n'
        if sys.platform == "win32":
            # pick something from %windir%\system32\msvc*dll that include stdlib
            libraries=["msvcrt.dll"]
            libraries=["msvcrt"]
        elif sys.platform == "linux2":
            libraries=["libc.so.6"]
        else:
            libraries=["libc"]
        self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_getenv_returns_string(self):
        """Issue 8 - Regression for crash with 64 bit and bad strings on 32 bit.
        See http://code.google.com/p/ctypesgen/issues/detail?id=8
        Test that we get a valid (non-NULL, non-empty) string back
        """
        module = self.module

        if sys.platform == "win32":
            # Check a variable that is already set
            env_var_name = 'USERNAME'  # this is always set (as is windir, ProgramFiles, USERPROFILE, etc.)
            expect_result = os.environ[env_var_name]
            self.assert_(expect_result, 'this should not be None or empty')
        else:
            env_var_name = 'HELLO'
            os.environ[env_var_name] = 'WORLD'  # This doesn't work under win32
            expect_result = 'WORLD'

        result = module.getenv(env_var_name)
        self.failUnlessEqual(expect_result, result)

    def test_getenv_returns_null(self):
        """Related to issue 8. Test getenv of unset variable.
        """
        module = self.module
        env_var_name = 'NOT SET'
        expect_result = None
        try:
            # ensure variable is not set, ignoring not set errors
            del os.environ[env_var_name]
        except KeyError:
            pass
        result = module.getenv(env_var_name)
        self.failUnlessEqual(expect_result, result)

class SimpleMacrosTest(unittest.TestCase):
    """Based on simple_macros.py
    """

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '''
#define A 1
#define B(x,y) x+y
#define C(a,b,c) a?b:c
#define funny(x) "funny" #x
#define multipler_macro(x,y) x*y
#define minus_macro(x,y) x-y
#define divide_macro(x,y) x/y
#define mod_macro(x,y) x%y
'''
        libraries = None
        self.module, output = ctypesgentest.test(header_str)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_macro_constant_int(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.A, 1)

    def test_macro_addition(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.B(2, 2), 4)

    def test_macro_ternary_true(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.C(True, 1, 2), 1)

    def test_macro_ternary_false(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.C(False, 1, 2), 2)

    def test_macro_ternary_true_complex(self):
        """Test ?: with true, using values that can not be confused between True and 1
        """
        module = self.module

        self.failUnlessEqual(module.C(True, 99, 100), 99)

    def test_macro_ternary_false_complex(self):
        """Test ?: with false, using values that can not be confused between True and 1
        """
        module = self.module

        self.failUnlessEqual(module.C(False, 99, 100), 100)

    def test_macro_string_compose(self):
        """Tests from simple_macros.py
        """
        module = self.module

        self.failUnlessEqual(module.funny("bunny"),  "funnybunny")

    def test_macro_math_multipler(self):
        module = self.module

        x, y = 2, 5
        self.failUnlessEqual(module.multipler_macro(x, y), x * y)

    def test_macro_math_minus(self):
        module = self.module

        x, y = 2, 5
        self.failUnlessEqual(module.minus_macro(x, y), x - y)

    def test_macro_math_divide(self):
        module = self.module

        x, y = 2, 5
        self.failUnlessEqual(module.divide_macro(x, y), x / y)

    def test_macro_math_mod(self):
        module = self.module

        x, y = 2, 5
        self.failUnlessEqual(module.mod_macro(x, y), x % y)

class StructuresTest(unittest.TestCase):
    """Based on structures.py
    """

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '''
struct foo
{
        int a;
        int b;
        int c;
};
'''
        libraries = None
        self.module, output = ctypesgentest.test(header_str)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_structures(self):
        """Tests from structures.py
        """
        module = self.module

        struct_foo = module.struct_foo
        self.failUnlessEqual(struct_foo._fields_, [("a", ctypes.c_int), ("b", ctypes.c_int), ("c", ctypes.c_int)])

class MathTest(unittest.TestCase):
    """Based on math_functions.py"""

    def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = '#include <math.h>\n'
        if sys.platform == "win32":
            # pick something from %windir%\system32\msvc*dll that include stdlib
            libraries=["msvcrt.dll"]
            libraries=["msvcrt"]
        elif sys.platform == "linux2":
            libraries=["libm.so.6"]
        else:
            libraries=["libc"]
        self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)

    def tearDown(self):
        del self.module
        ctypesgentest.cleanup()

    def test_sin(self):
        """Based on math_functions.py"""
        module = self.module

        self.failUnlessEqual(module.sin(2), math.sin(2))

    def test_sqrt(self):
        """Based on math_functions.py"""
        module = self.module

        self.failUnlessEqual(module.sqrt(4), 2)

        def local_test():
            module.sin("foobar")

        self.failUnlessRaises(ctypes.ArgumentError, local_test)

    def test_bad_args_string_not_number(self):
        """Based on math_functions.py"""
        module = self.module

        def local_test():
            module.sin("foobar")

        self.failUnlessRaises(ctypes.ArgumentError, local_test)

def main(argv=None):
    if argv is None:
        argv = sys.argv

    unittest.main()

    return 0

if __name__ == "__main__":
    sys.exit(main())
<|endoftext|>


<commit_before>#!/usr/bin/python

import pylink
import pytest

@pytest.fixture
def example_rf_chain():
    return [
        pylink.Element(gain_db=-0.1,
                       noise_figure_db=0.1,
                       name='attenuator')
        ]

@pytest.fixture
def attenuator_1db():
    return pylink.Element(gain_db=-1,
                          noise_figure_db=1,
                          name='attenuator')

@pytest.fixture
def amplifier_10db():
    return pylink.Element(gain_db=10,
                          noise_figure_db=3,
                          name='amplifier')

perf = [
    pylink.Code("BPSK", .5, .5, 4),
    pylink.Code("QPSK", 1, 1, 8),
    pylink.Code("8PSK", 2, 2, 12),
    ]

@pytest.fixture
def model():
    return pylink.DAGModel([pylink.Geometry(),
                            pylink.Antenna(is_rx=True),
                            pylink.Interconnect(is_rx=True),
                            pylink.Receiver(),
                            pylink.Transmitter(),
                            pylink.Interconnect(is_rx=False),
                            pylink.Antenna(is_rx=False),
                            pylink.Channel(),
                            pylink.Modulation(name='QPSK', perf=perf),
                            pylink.LinkBudget()])
<commit_msg>pep-8<commit_after>#!/usr/bin/python

import pylink
import pytest

@pytest.fixture
def example_rf_chain():
    return [
        pylink.Element(gain_db=-0.1,
                       noise_figure_db=0.1,
                       name='attenuator')
        ]

@pytest.fixture
def attenuator_1db():
    return pylink.Element(gain_db=-1,
                          noise_figure_db=1,
                          name='attenuator')

@pytest.fixture
def amplifier_10db():
    return pylink.Element(gain_db=10,
                          noise_figure_db=3,
                          name='amplifier')

perf = [
    pylink.Code("BPSK", .5, .5, 4),
    pylink.Code("QPSK", 1, 1, 8),
    pylink.Code("8PSK", 2, 2, 12),
    ]

@pytest.fixture
def model():
    return pylink.DAGModel([pylink.Geometry(),
                            pylink.Antenna(is_rx=True),
                            pylink.Interconnect(is_rx=True),
                            pylink.Receiver(),
                            pylink.Transmitter(),
                            pylink.Interconnect(is_rx=False),
                            pylink.Antenna(is_rx=False),
                            pylink.Channel(),
                            pylink.Modulation(name='QPSK', perf=perf),
                            pylink.LinkBudget()])
<|endoftext|>