def test_calculate(amount, input_currency, output_currency, expected):
    from src.converter import Converter
    converter = Converter(amount, input_currency, output_currency)
    converter.rates = {"USD": 1, "ABC": 42}

    assert converter.calculate(converter.amount, converter.input_currency,
                               converter.output_currency) == expected
def main():
    '''
    Main method, executes program.
    '''
    def get_args():
        '''
        Gets arguments from commandline.

        Arguments consist of input sources, output destination, and missed files (error) destination.
        '''
        parser = argparse.ArgumentParser(
            description=
            'Convert users from csv to json format, as described by schema.')
        parser.add_argument('--input',
                            nargs='+',
                            required=True,
                            help='One or more csv files of users.')
        parser.add_argument('--output',
                            required=True,
                            help='Output file destination.')

        return parser.parse_args()

    args = get_args()
    conv = Converter()
    conv.convert(args.input, args.output)
    def test(self):
        try:
            fullpath = os.path.join(
                os.path.split(__file__)[0], 'res', 'testcases', fname)
            inputs = os.listdir(os.path.join(fullpath, 'input'))
            inputs = map(lambda x: os.path.join(fullpath, 'input', x), inputs)
            inputs = sorted(inputs)

            expected = os.path.join(fullpath, 'expected.json')
            fhandle, got = tempfile.mkstemp()

            c = Converter()
            c.convert(inputs, got)

            with open(expected, 'r') as exf:
                exj = json.load(exf)
            with open(got, 'r') as gotf:
                gotj = json.load(gotf)

            self.assertEqual(exj['user_list_size'], gotj['user_list_size'])
            self.assertListEqual(exj['user_list'], gotj['user_list'])
            self.assertDictEqual(exj, gotj)

        finally:
            os.close(fhandle)
            os.remove(got)
Example #4
0
def currency_converter():
    if request.method == "GET":
        input_currency = request.args.get("input_currency", type=str)
        amount = request.args.get("amount", type=float)
        output_currency = request.args.get("output_currency", type=str)
        logging.info(f"{input_currency} - {type(input_currency)}")
        logging.info(f"{output_currency}  - {type(output_currency)}")
        logging.info(f"{amount}  - {type(amount)}")
        if input_currency and amount:
            converter = Converter(
                input_currency=input_currency,
                amount=amount,
                output_currency=output_currency,
            )
            response, status_code = converter.convert()
            response = (
                jsonify(response) if status_code == 200 else jsonify(message=response)
            )
            return response, status_code
        else:
            return (
                jsonify(message="Missing required params or wrong type of params."),
                400,
            )
    else:
        return jsonify(message="Unsupported HTTP method."), 400
Example #5
0
 def test_one_to_one(self):
     with self.rates_mock as mock:
         mock.return_value = self.test_rates
         converter = Converter(input_currency="AUD", amount=1, output_currency="CZK")
         result, status_code = converter.convert()
         self.assertEqual(result["input"]["currency"], "AUD")
         self.assertEqual(result["output"]["CZK"], 15.65)
         self.assertEqual(status_code, 200)
Example #6
0
def start():
    crawler = Crawler()
    crawler_results = crawler.crawl()
    for crawler_result in crawler_results:
        attribute_string = crawler_result.get('attribute_string')
        attribute_usd_price = crawler_result.get('attribute_usd_price')
        attribute = crawler_result.get('attribute')
        converter = Converter()
        print attribute,converter.convert(attribute_usd_price,attribute_string)
Example #7
0
 def localize(self, paths: List[Path]):
     """
     download images to local directory and then convert the urls of the 'src' attribute to relative local paths
     :param paths:
     """
     for p in paths:
         logger.info(f"localizing [{p}]...")
         converter = Converter(self.url, p)
         converter.localize_img()
     logger.info("localize finished")
Example #8
0
 def test_empty_rates_storage(self):
     with self.rates_mock as mock:
         mock.return_value = {}
         converter = Converter(input_currency="CZK", amount=1)
         result, status_code = converter.convert()
         self.assertEqual(
             result,
             "Missing currency exchange rates. Please try to update the storage.",
         )
         self.assertEqual(status_code, 400)
Example #9
0
 def test_non_valic_code(self):
     with self.rates_mock as mock:
         mock.return_value = self.test_rates
         converter = Converter(input_currency="XYZ", amount=1)
         result, status_code = converter.convert()
         self.assertEqual(
             result,
             "Unsupported currency symbol/code! Please check inserted values with supported values help and try again!",
         )
         self.assertEqual(status_code, 400)
Example #10
0
 def test_many_to_one(self):
     with self.rates_mock as mock:
         mock.return_value = self.test_rates
         converter = Converter(input_currency="$", amount=1, output_currency="US$")
         result, status_code = converter.convert()
         self.assertEqual(
             result,
             "Too many input currency options! Please insert a currency code/symbol matching the unique currency.",
         )
         self.assertEqual(status_code, 400)
Example #11
0
def convert(amount, input_currency, output_currency):
    try:
        converter = Converter(amount, input_currency, output_currency)
        if converter.check_parameters():
            print(json.dumps(converter.convert(), sort_keys=True, indent=4))
        else:
            print("Wrong parameters.")
    except FileNotFoundError:
        print("Cannot find file with currency symbols.")
        exit(-1)
Example #12
0
 def test_symbol_to_symbol(self):
     with self.rates_mock as mock:
         mock.return_value = self.test_rates
         converter = Converter(input_currency="£", amount=1, output_currency="zł")
         result, status_code = converter.convert()
         self.assertEqual(result["input"]["currency"], "GBP")
         self.assertEqual(result["input"]["amount"], 1)
         self.assertEqual(len(result["output"]), 1)
         self.assertEqual(list(result["output"].keys())[0], "PLN")
         self.assertEqual(list(result["output"].values())[0], 4.94)
         self.assertEqual(status_code, 200)
Example #13
0
def convert(amount, input_currency, output_currency=""):
    try:
        converter = Converter(amount, input_currency, output_currency)
        if converter.check_parameters():
            return converter.convert()
        else:
            return problem(400, "Bad Request", "Wrong parameters",
                           "about:blank")
    except FileNotFoundError:
        return problem(400, "Error", "Cannot find file with currency symbols.",
                       "about:blank")
Example #14
0
def run(arguments):
    '''Loads configs and calls procedures'''
    try:
        cfg_file = arguments.config
        if type(arguments.config) == list:
            cfg_file = arguments.config[0]
        conf = json.load(cfg_file)
        if conf:
            Converter(conf, arguments.filename[0]).convert()
    except Exception as e:
        raise Exception(e)
Example #15
0
 def convert_file(self):
     if not file_exists(self.RawFileName) and not self.SingleMode:
         self.merge_root_files()
     warning(
         'final root file "{}" does not exist. Starting Converter!'.format(
             self.FileName))
     converter = Converter(self.RawFileName,
                           self.DUTNr,
                           join(self.TCDir, self.DUTName),
                           first_run=int(self.Logs.keys()[0]))
     converter.run()
     if not self.SingleMode:
         info('removing raw file "{}"'.format(self.RawFileName))
         remove(self.RawFileName)
Example #16
0
def test_converter():
    file = Path.cwd().joinpath('mocks/test_converter.json')
    file_dir = Path.cwd().joinpath('mocks')
    base_url = URL("https://www.cnblog.com")

    converter = Converter(base_url, file)
    converter.localize_img()

    handled = etree.fromstring(converter._load_file(file)['article'])
    handled_img = handled.xpath('//*/img')[0].get('src')

    test_img = Path('./1004427-20200329151921980-987119585.png')
    relative_url = f'./{test_img}'

    assert file_dir.joinpath(test_img).exists() is True
    assert handled_img == relative_url
Example #17
0
class TransformerTest(unittest.TestCase):

    tested = Converter()

    def setUp(self):
        # print('---')
        pass

    def testConversionMD(self):
        res: str = self.tested.convertMarkdown(MD_1)
        self.assertIsNotNone(res)
        self.assertTrue('<h1>Header' in res)
        self.assertTrue('<li>Item' in res)
        self.assertFalse('* Item' in res)

    def testCodeFormat(self):
        res = self.tested.convertMarkdown(MD_WITH_CODE)
        self.assertIsNotNone(res)
        self.assertTrue('<code>System.out.println();' in res)
        self.assertTrue("""<blockquote>\n<p>Um""" in res)

    # TODO re check cases with \n
    @unittest.skip
    def testTransformArea(self):
        value = self.tested.convertAmdAreasToMD(MD_DELIMITED)
        self.assertIsNotNone(value)
        self.assertTrue("""<i>Outer MD</i>
<h1>Converted</h1>
<ul>""" in value)
        self.assertFalse('<amd>' in value)

    def testClearHTML(self):
        value = self.tested.getTextFromHtml(HTML_CODE2)
        self.assertIsNotNone(value)
        self.assertTrue("> Some text here" in value)
        self.assertFalse("&gt;" in value)

    def testHtmlToMarkdown(self):
        value = self.tested.getTextFromHtml(HTML_CODE1)
        self.assertIsNotNone(value)
        self.assertTrue('# Header 1' in value)
        self.assertTrue('* My list item' in value)
        self.assertTrue('> My quote' in value)

    def testTextWithHTML(self):
        # cleanedCode = self.tested.getTextFromHtml(DEMILITED_CODE.strip())
        value = self.tested.convertAmdAreasToMD(DEMILITED_CODE, True)
        self.assertTrue("<h2>Exemplos vão aqui!</h2>" in value)
        self.assertTrue("<code>" in value)

    def testTextWithHTML2(self):
        value = self.tested.convertAmdAreasToMD(DEMILITED_CODE2, True)
        self.assertTrue("<code>" in value)

    # TODO re check cases with spaces
    @unittest.skip
    def testInlineTrimParam(self):
        res = self.tested.findConvertArea(
            """<amd trim="true">  <i>  # Header</i>  </amd>""")
        self.assertTrue('<h1>Header' in res)
        self.assertFalse('  # Header' in res)

    # HTML with inline options
    def testConvertArea(self):
        res = self.tested.convertAmdAreasToMD("""
<amd trim="false" replace-spaces="true">
          System.out.println();\\n    def test():\\n
          ra()
</amd>""")
        print(res)
        self.assertTrue('<code>' in res)

    def testClozeParts(self):
        res = self.tested.convertAmdAreasToMD(BLOCK_CLOZE)
        # print(res)
        self.assertTrue('def <span class=cloze>[...]' in res)
        self.assertTrue('def <span class=cloze>Result' in res)
        self.assertFalse('[[...CLOZE...]]' in res)

    def testInputsParts(self):
        res = self.tested.convertAmdAreasToMD(BLOCK_INPUTS, isTypeMode=True)

        # print(res, flush=True)
        self.assertTrue('def <input type=text style="anytrhing;" />' in res)
        self.assertTrue('id="iptID"' in res)
        self.assertFalse('||...INPUT...||' in res)

    @unittest.skip
    def testMultipleBlocks(self):
        value = self.tested.convertAmdAreasToMD(MULTIPLE_BLOCKS)
        print(value)

    def testCodeToMarkdown(self):
        t = self.tested
        # print(t.getTextFromHtml(t.convertMarkdown("""
        # def _wrapOnPaste(self, fn):
        #     ref = self

        # def _onPaste(self, mode):
        #     extended = self.editor.mw.app.queryKeyboardModifiers() & Qt.ShiftModifier
        #     mime = self.editor.mw.app.clipboard().mimeData(mode=mode)
        # """)))

    def test_stripAmdTags(self):
        t = self.tested
        self.assertEqual(
            '{{FieldOne}}',
            t.stripAmdTagForField('<amd>{{FieldOne}}</amd>', 'FieldOne'))
        self.assertEqual(
            '{{FieldOne}}',
            t.stripAmdTagForField('<amd some="param">{{FieldOne}}</amd>',
                                  'FieldOne'))
        # self.assertEqual('More Content [[FieldOne]] After', t.stripAmdTags('More Content <amd>[[FieldOne]]</amd> After'))

    def test_stripAmdTagsMultiple(self):
        t = self.tested
        self.assertEqual(
            '{{FieldOne}}',
            t.stripAmdTagForField('<amd><amd>{{FieldOne}}</amd></amd>',
                                  'FieldOne'))
        self.assertEqual(
            '{{FieldOne}}<amd>:Two</amd>',
            t.stripAmdTagForField(
                '<amd some="param">{{FieldOne}}</amd><amd>:Two</amd>',
                'FieldOne'))
Example #18
0
 def test_right_template_name(self):
     converter = Converter()
     result = converter.to_jinja("storage")
     self.assertEqual(result, "storage.j2")
 def test_invalid_convert(self):
     self.converter = Converter()
     self.assertEquals(self.converter.convert('100dh####sb', 'Revenuedd#$@$#%#^EUR100 billion (2018)'),None)
def test_currency_symbols(input_currency, output_currency, expected):
    from src.converter import Converter
    converter = Converter(0, input_currency, output_currency)

    assert (converter.input_currency, converter.output_currency) == expected
Example #21
0
                           x_tit='Column DUT',
                           y_tit='Row DUT',
                           canvas=c.cd(2))

    # endregion DRAW
    # ----------------------------------------


if __name__ == '__main__':

    from pixel.run import PixelRun
    from src.converter import Converter
    from src.analysis import Analysis

    # eg. (489/490, 201610), (147, 201810)
    pp = init_argparser(return_parser=True)
    pp.add_argument('dut', nargs='?', default=None, type=int)
    pp.add_argument('-x', action='store_true')
    pp.add_argument('-y', action='store_true')
    pargs = pp.parse_args()
    this_tc = Analysis.find_testcampaign(pargs.testcampaign)

    zrun = PixelRun(pargs.run,
                    testcampaign=this_tc,
                    load_tree=False,
                    verbose=True)
    z = PixAlignment(Converter(zrun),
                     dut_plane=pargs.dut,
                     mode='x' if pargs.x else 'y' if pargs.y else '')
    z.reload()
Example #22
0
from src.converter import Converter

# This is the initial point of execution
if __name__ == '__main__':
    filenames = ["compute", "storage"]
    for f in filenames:
        converter = Converter()
        template = converter.to_jinja(f)
        print(template)

def test_check_parameters(input_currency, output_currency, expected):
    from src.converter import Converter
    converter = Converter(0, input_currency, output_currency)

    assert converter.check_parameters() == expected
Example #24
0
                    0, max(x),
                    int(
                        choose(bin_size,
                               self.BinSize / self.get_pulser_rate().n))),
                show=0))
        return self.Draw.graph(x,
                               y,
                               x_tit='Event Number',
                               y_tit='N Hits @ Pulser',
                               w=2,
                               show=show,
                               draw_opt='alx',
                               y_range=ax_range(0, max(max(y).n, 5), .1, .3))


if __name__ == '__main__':

    from pad.run import PadRun
    from src.converter import Converter

    # examples: 7(201708), 218(201707)
    # not possible to align: 442(201508), 439(201508)
    args = init_argparser(run=143, tc='201707-2')
    zrun = PadRun(args.run,
                  testcampaign=args.testcampaign,
                  load_tree=False,
                  verbose=True)
    z = PadAlignment(Converter(zrun))
    if not z.IsAligned:
        z.reload()
Example #25
0
    def convert(self):
        """ convert binary raw file to root file with eudaq"""
        cal_path = self.generate_fit_files()
        if self.FilePath is None:
            critical('raw file does not exist for run: {}'.format(
                self.RunNumber))
        self.OutFilePath.parent.mkdir(exist_ok=True)
        cmd = f'{self.SoftDir.joinpath("bin", "euCliConverter")} -i {self.FilePath} -o {self.OutFilePath} -c {cal_path}'
        info(
            f'Convert {self.FilePath.name} to {self.OutFilePath.name} using EUDAQ-2\n'
        )
        info(f'{cmd}\n')
        check_call(cmd, shell=True)
        for f in Path().glob('AutoDict_vector*'):
            remove_file(f)

    def make_cuts(self):
        [t.SetEstimate(t.GetEntries() * 10) for t in self.P]
        n = [get_tree_vec(t, 'NHits', dtype='i2') for t in self.P[:6]]
        c = all([i == 1 for i in n], axis=0)
        return [c.repeat(i) for i in n]


if __name__ == '__main__':
    from src.analysis import Analysis

    a = Analysis()
    c0 = Converter(a.BeamTest.Path, 17, a.Config)
    z = Raw(c0, load_file=True)