示例#1
0
def TestExternalCompoundsRandom():
    print("Loading libraries...")
    from numpy import random
    from scipy.stats.stats import pearsonr
    from JsonParser import JsonParser
    jp = JsonParser()
    data = jp.LoadFile(COMPOUNDSFILE)

    while True:
        expected = []
        results = []

        for value in data:
            print("== Comparing %s to %s. ==" % (value["one"], value["two"]))
            result = random.uniform(0.0, 1.0)
            print("Similarity expected - found: %s - %s\n" %
                  (value["sim"], result))

            expected.append(value["sim"])
            results.append(result)

        print("Pearson correlation, 2-tailed p-value:")
        print(pearsonr(expected, results))
        print("==============================")
        print()

        if not TryAgain():
            break
示例#2
0
def TestExternalCompounds():
    print("Loading libraries...")
    from scipy.stats.stats import pearsonr
    from CompoundHandler import CompoundHandler
    ch = CompoundHandler(settings)
    from JsonParser import JsonParser
    jp = JsonParser()
    data = jp.LoadFile(COMPOUNDSFILE)

    while True:
        if settings.Reload is True:
            settings.LoadSettings()
            ch.ReloadSettings(settings)

        expected = []
        results = []

        for value in data:
            print("== Comparing %s to %s. ==" % (value["one"], value["two"]))
            result = ch.GetSimilarity(value["one"], value["two"])
            print("Similarity expected - found: %s - %s\n" %
                  (value["sim"], result))

            expected.append(value["sim"])
            results.append(result)

        print("Pearson correlation, 2-tailed p-value:")
        print(pearsonr(expected, results))
        print("==============================")
        print()

        if not TryAgain():
            break
示例#3
0
def TestSuiteSimilarityWeights():
    print("Loading libraries...")
    import numpy as np
    from CompoundHandler import CompoundHandler
    ch = CompoundHandler(settings, loadAll=True)
    from JsonParser import JsonParser
    jp = JsonParser()
    data = jp.LoadFile(COMPOUNDSFILE)

    lambdas = []
    mus = []
    results = []

    for _lambda in np.linspace(settings.MinLambda, settings.MaxLambda,
                               settings.LambdaSteps):
        mu = (settings.MaxLambda - _lambda)

        lambdas.append(_lambda)
        mus.append(mu)

        results.append(
            PerformTests(_lambda, mu, settings.Gamma, settings.Delta,
                         settings.Epsilon, ch, data))

    i = 0
    for value in results:
        print("l: %s m: %s result: %s" % (lambdas[i], mus[i], value))
        i += 1
示例#4
0
def test_json_loadDict():
    d = {'您key': [u'key', 123], 'key2':{'a':321}}
    jp = JsonParser()
    jp.loadDict(d)
    print repr(jp)
    print repr(jp.dump())
    print jp['您key']
示例#5
0
def LoadConcepts():
    from JsonParser import JsonParser
    jp = JsonParser()

    return jp.LoadFile(
        CONCEPTSFILE, debug=True
    )  # DEBUG - Not the entire line, only the "debug = True" part.
示例#6
0
def main(argv):
    input_stream = FileStream(argv[1])
    lexer = JsonLexer(input_stream)
    stream = CommonTokenStream(lexer)
    parser = JsonParser(stream)
    tree = parser.json()

    walker = ParseTreeWalker()
    walker.walk(JsonFormatterListener(4), tree)
示例#7
0
def check_invalid(s):
    jp = JsonParser()

    try:
        jp.load(s)
    except (TypeError, ValueError):
        assert True
    else:
        print('assertion has failed:\n    should raise an error when parsing %r\n' % s)
        assert False
示例#8
0
    def LoadCollections(self, collections):
        from JsonParser import JsonParser
        jp = JsonParser()

        i = 1  # DEBUG
        for collection in collections:
            self.collections[collection] = jp.LoadFile(collections[collection])
            print("Collection %s loaded: %s" %
                  (i, self.collections[collection]))  # DEBUG
            i += 1  # DEBUG
示例#9
0
def test_json_dump():
    d = {"abc": 123}
    a = json.dumps(d)

    jp = JsonParser()
    jp.loadJson(u"TestCaseForLoad.txt", 'utf8')
    print jp
    json_str = jp.dump()
    print repr(json_str)
    print jp['a']
    print jp[u'我']
示例#10
0
def test_json_loadJson():
    # fp = open(u"中文_utf8.txt")
    # print fp.read().decode('utf8')
    # fp = open(u"中文_gbk.txt")
    # print fp.read().decode('gbk')
    jp = JsonParser()
    # print jp.loadJson(u"中文_utf8.txt", 'utf8')
    jp.loadJson(u'json_test/test_case/pass1.json')
    fp = open("save.txt", mode='w')
    s = jp.dump()
    fp.write(s.encode('utf8'))
示例#11
0
def TestCompletePackage(existingConcepts):
    from SynonymRemover import SynonymRemover
    sr = SynonymRemover(existingConcepts, settings)
    from JsonParser import JsonParser
    jp = JsonParser()
    newConcepts = jp.LoadCommit(COMMITFILE)

    newConcepts = sr.RemoveSynonyms(existingConcepts, newConcepts)

    print("New concepts: %s" % newConcepts)
    jp.MakeFile(newConcepts, OUTFILE)
示例#12
0
def check_invalid(s):
    jp = JsonParser()

    try:
        jp.load(s)
    except (TypeError, ValueError):
        assert True
    else:
        print(
            'assertion has failed:\n    should raise an error when parsing %r\n'
            % s)
        assert False
示例#13
0
def test_parse():
    jp = JsonParser()
    jp.load(JSON)
    out = jp.dump()
    print repr(out)
    d1 = jp.dumpDict()
    jp.load(out)
    d2 = jp.dumpDict()
    print d1==d2
示例#14
0
def test_unit(str,Success,msg):
    jpaser=JsonParser()
    try:
        result = jpaser.load(str)
        if jpaser is None:
            if Success == False:
                print 'Test ' + msg + ' Success Result None'
                exit()
            else:
                print 'Test ' + msg + ' Fail Result None'
                exit()
    except JsonError,e:
        result = False;
示例#15
0
class FailTest(unittest.TestCase):
    def setUp(self):
        self.jp = JsonParser()

    def test_fail_example(self):
        for key, value in enumerate(JSONDOCS):
            try:
                self.jp.load(value)
            except ValueError as err:
                print "Testcase {}:{}: raise exception: {}".format(key + 1, value, err.message)
                continue
            else:
                self.fail("ValueError has no been raise when try {}".format(value))
        print "FailTest finished!"
class PlayerTestHarness:
    def __init__(self):
        self.parser = JsonParser()

    def main(self):
        commands = self.parser.parse_stream(sys.stdin)
        place_command = commands[0]
        play_commands = commands[1:]
        color = place_command[1]

        init_board = place_command[2]
        player = Player(color)
        positions = player.place_workers(Board(init_board))

        place_output = map(self._format_position, positions)
        play_outputs = map(
            lambda play: self._execute_play_command(play, player),
            play_commands)
        print(json.dumps(place_output))
        for output in play_outputs:
            print(json.dumps(output))

    def _format_position(self, position):
        return [position.row, position.col]

    def _execute_play_command(self, play_command, player):
        board = Board(play_command[1])
        viable_plays = player.get_plays(board)
        return map(self._format_play, viable_plays)

    def _format_play(self, play):
        directions = [play.move_direction]
        if (play.build_direction): directions.append(play.build_direction)
        return [play.worker, directions]
示例#17
0
 def SaveFile(text):
     jsonText = JsonParser.CreateJson(text)
     root = tk.Tk()
     root.withdraw()
     path = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
     if (path != None):
         f = open(path.name, "w")
         f.write(jsonText)
     else:
         print("Not saved because no file was selected!")
示例#18
0
    def LoadFigure(self, path):
        figure = JsonParser.CreateFigure(path)
        if (figure.MinSizeX + 1 >= self.Layout.HorizontalLength):
            self.Layout.HorizontalLength = figure.MinSizeX + 1
            self.InitiateBoard()

        if (figure.MinSizeY + 1 >= self.Layout.VerticalLength):
            self.Layout.VerticalLength = figure.MinSizeY + 1
            self.InitiateBoard()

        for temp in figure.ActiveCells:
            self.Board[temp[1]][temp[0]] = 1
示例#19
0
def test_check_circular():
    x = []
    x.append(x)
    d = {'x': x}
    jp = JsonParser()
    jp.loadDict(d)
    jp.dump()
示例#20
0
def TestSuiteCompoundWeights():
    print("Loading libraries...")
    import numpy as np
    from CompoundHandler import CompoundHandler
    ch = CompoundHandler(settings)
    from JsonParser import JsonParser
    jp = JsonParser()
    data = jp.LoadFile(COMPOUNDSFILE)

    gammas = []
    deltas = []
    epsilons = []
    results = []

    gammanum = 0  # Counts at which gamma value we're at. Increases by one every time we finish a gamma pass, is used to ensure step size is identical for gamma and delta.
    for gamma in np.linspace(settings.MinGamma, settings.MaxGamma,
                             settings.GammaSteps):
        for delta in np.linspace(settings.MinGamma, settings.MaxGamma - gamma,
                                 settings.GammaSteps - gammanum):
            epsilon = (settings.MaxGamma - gamma - delta) / 2

            gammas.append(gamma)
            deltas.append(delta)
            epsilons.append(epsilon)

            results.append(
                PerformTests(settings.SpaCyWeight, settings.WordNetWeight,
                             gamma, delta, epsilon, ch, data))
        gammanum += 1

    i = 0
    pastgamma = gammas[i]
    for value in results:
        print("g: %s d: %s e: %s result: %s" %
              (gammas[i], deltas[i], epsilons[i], value))
        i += 1
        if i < len(gammas) and pastgamma != gammas[
                i]:  # Minor readability improvement.
            pastgamma = gammas[i]
            print()
示例#21
0
    def __init__(self):
        current_directory = os.getcwd()
        print("\n")
        print(f"Current Directory : \t {current_directory}")
        current_files = self.show_json_files_here()
        print("\n")
        value = eval(input("Choose a folder or JSON file :"))
        if isinstance(value,int):
            if value == 0:
                splittedversion = current_directory.split("/")
                if(len(splittedversion) > 2):
                    splittedversion.pop()
                    changed_dir = ("/").join(splittedversion)
                    os.chdir(changed_dir)
                    Navigator()
                else:
                    print("\n","<<<<< You are at the root >>>>>>")
                    Navigator()
            elif value == 1:
                JsonParser(current_directory)
                
            elif value in range(len(current_files)+1):
                if(current_files[value].endswith(".json")):
                    JsonParser(current_directory+"/"+current_files[value])
                else:
                    os.chdir(current_directory+"/"+current_files[value])
                    Navigator()

                print(f'current_directory ====== {current_directory+"/"+current_files[value]}')
                Navigator()
            else:
                print("\n","<<<<< Please enter a valid option >>>>>>")
                Navigator()    

        else:
            print("\n","<<<<< Please enter a valid option >>>>>>")
            Navigator()
示例#22
0
def encodeFields(df):
    # return dict with 'raw_url', 'raw_title', & 'tweet_ids'
    data = JsonParser(df).execute()

    # encode each of the data_portions
    encodeUrl = UrlParser(data['raw_url']).execute()
    encodeTitle = TitleHandler(data['raw_title']).execute()
    encodedTweet_ids = data['tweet_ids']

    newDF = pd.DataFrame()
    newDF['domain_type'] = [encodeUrl['domain_type']]
    newDF['protocol'] = [encodeUrl['protocol']]
    newDF["title_capital_freq"] = [encodeTitle['title_capital_freq']]
    newDF["tweet_ids"] = [encodedTweet_ids]
    newDF["internal_links"] = [encodeUrl['internal_links']]

    #print("\n\n--------------------\n",newDF , "\n--------------------\n\n")
    return newDF
class PlayerTestHarness:
    def __init__(self):
        self.parser = JsonParser()

    def main(self):
        commands = self.parser.parse_stream(sys.stdin)
        admin = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        admin.bind(('', 8000))
        admin.listen(5)
        client, ip = admin.accept()
        proxy = ProxyPlayer(client)
        outputs = []
        outputs = [proxy.send_msg(json.dumps(['Register']))]
        for command in commands:
            output = proxy.send_msg(json.dumps(command))
            if output:
                outputs.append(output)
        admin.close()
        for output in outputs:
            print output
class RuleCheckerTestHarness:
  def __init__(self):
    self.parser = JsonParser()
    self.rule_checker = RuleChecker()

  def main(self):
    inputs = self.parser.parse_stream(sys.stdin)
    is_valid_play_list = map(self._check_play, inputs)
    responses = map(lambda is_valid_play: 'yes' if is_valid_play else 'no', is_valid_play_list)
    for response in responses:
      print(json.dumps(response))

  def _check_play(self, test_play):
    game_board = test_play[0]
    worker = test_play[1]
    directions = test_play[2]
    move_direction = directions[0]
    build_direction = directions[1] if len(directions) == 2 else None
    board = Board(game_board)
    play = Play(worker, move_direction, build_direction)
    return self.rule_checker.is_valid_play(board, play)
示例#25
0
def test_dict_related_operation():
    # test dict related operation, include 1) load only str key item 2) deepcopy original dict
    d_a = {'a': [1], 2: 'notexist', 'nested': [{'a': 'b', 3: 2}, 2]}
    d_a_back = deepcopy(d_a)

    jp = JsonParser()
    jp.loadDict(d_a)

    # only copy str key item
    d_a_g = {'a': [1], 'nested': [{'a': 'b'}, 2]}
    assert_eq(jp.dumpDict(), d_a_g)

    # dump get a deepcopy of jp dict
    d_d = jp.dumpDict()
    d_d['x'] = 'x'
    assert_eq(jp.dumpDict(), d_a_g)

    # not change origin dict && support [] operator
    jp['a'].append(2)
    jp['nested'][0]['c'] = 100
    assert_eq(jp['a'], [1, 2])
    assert_eq(d_a_back, d_a)
示例#26
0
def test_dict_related_operation():
    # test dict related operation, include 1) load only str key item 2) deepcopy original dict
    d_a = {'a': [1], 2:'notexist', 'nested':[{'a':'b', 3:2}, 2]}
    d_a_back = deepcopy(d_a)

    jp = JsonParser()
    jp.loadDict(d_a)

    # only copy str key item
    d_a_g = {'a':[1], 'nested':[{'a':'b'}, 2]}
    assert_eq(jp.dumpDict(), d_a_g)

    # dump get a deepcopy of jp dict
    d_d = jp.dumpDict()
    d_d['x'] = 'x'
    assert_eq(jp.dumpDict(), d_a_g)

    # not change origin dict && support [] operator
    jp['a'].append(2)
    jp['nested'][0]['c'] = 100
    assert_eq(jp['a'], [1, 2])
    assert_eq(d_a_back, d_a)
示例#27
0
def test_json_load():
    j = JsonParser()
    j.load(r'["a\tb"]')
    print j
    print j.dump()
    print json.loads(r'"\ttabcharacterinstring"', strict = True)
示例#28
0
 def setUp(self):
     self.jp = JsonParser()
     self.maxDiff = None
示例#29
0
def test_float_out_of_range():
    jp = JsonParser()
    jp.loadJson('json_test/test_case/fail35.json')
    print jp
    print jp.dump()
示例#30
0
class DecisionMaker:

    def __init__(self):
        self.parser = JsonParser()
        self.database = CryptoDatabase()

    # TODO make into 4 methods [Done -TJ]


    def ifHolding(self, holdingBool, connection, mainConfig):
        try:
            r = requests.get(mainConfig.gdax_api_url + '/accounts', auth=connection)
        except:
            print("Error getting account info")
            return

        try:
            holdingBool = 0 < self.parser.parseHoldingAmountSelectedCurrency(r.json(), mainConfig)
        except:
            print('Error with jsonParser.parseAvailableSelectedCurrency()')
            return

        return holdingBool

    # Determine if Limit Set For Selected Crypto
    def ifOrderExists(self, limitSetBool, config, connection):
        try:
            r = requests.get(config.gdax_api_url + '/orders/', auth=connection)
        except:
            print("Error getting account info")
            return None

        try:
            if not r.json():
                limitSetBool = False
        except:
            limitSetBool = False

        return limitSetBool

    # Sell checks and stuff
    def sellLogic(self, emaTracker, connection, currentSelectedCryptoPrice, mainConfig):

        avgPosVariance = emaTracker.getAvgPosVariance()

        print("Avg Pos Variance: ", avgPosVariance)

        ema = emaTracker.getEMA()

        try:
            last_ema_val = ema[len(ema) - 1]
        except:
            print("Error with getting Ema")
            return

        trade_handler = TradeHandler(connection, Config())

        if avgPosVariance is not None:

            print("Last EMA Val: ", last_ema_val, '   ', "Current Price: ", currentSelectedCryptoPrice)
            # print("Step Value decisionMaker.sellLogic(): ", stepValue)
            print("Sell Val: ", last_ema_val + (avgPosVariance / mainConfig.order_rate))

            last_buy_price = self.database.getLastBoughtPrice()
            sell_price = last_buy_price + (avgPosVariance / mainConfig.order_rate)

            if sell_price < last_buy_price:
                sell_price = last_buy_price + .01
                print("Sell Price is currently being calculated below profitability.")
                print("Selling at 1 cent above bought price: ", sell_price)

            trade_handler.sell(sell_price)
            # stepValue += 1
            # print("Step Value decisionsMaker.sellLogic() 2:", stepValue)
            # return stepValue


    def buyLogic(self, emaTracker, connection, currentSelectedCryptoPrice, mainConfig):
        ################################################################################################################
        #################################### Buy #######################################################################
        # See if the conditions are right for a sell limit to be placed

        avgNegVariance = emaTracker.getAvgNegVariance()

        print("Avg Neg Variance: ", (avgNegVariance / mainConfig.order_rate))

        ema = emaTracker.getEMA()

        try:
            last_ema_val = ema[len(ema) - 1]
        except:
            print("Error with getting Ema")
            return

        print("Last EMA Val: ", last_ema_val, '   ', "Current Price: ", currentSelectedCryptoPrice)

        if avgNegVariance is not None:
            print("Min Buy Val: ", last_ema_val - avgNegVariance)

            # Altered buy logic to immediately set buy order
            # The Buy orders are all timed to elapse in 1 hour, with the amount needed scaling towards EMA
            buy_val = float(currentSelectedCryptoPrice) - float(avgNegVariance / mainConfig.order_rate)  # hard-coding offset
            tradeHandler = TradeHandler(connection, Config())
            tradeHandler.buy(buy_val)


    def makeDecision(self, currentSelectedCryptoPrice, mainConfig, api_url, connection, emaTracker):
        # Determine if holding Selected Crypto
        # print("Top of DecisionMaker stepVal: ", stepValue)
        holdingBool = None
        holdingBool = self.ifHolding(holdingBool, connection, mainConfig)
        print("Holding: ", holdingBool)

        # Determine if Limit Set For Selected Crypto
        limitSetBool = True
        limitSetBool = self.ifOrderExists(limitSetBool, mainConfig, connection)

        if limitSetBool is None:
            return

        print("Limit Extant: ", limitSetBool)

        # Checks for Sell stuff
        if holdingBool:
            if not limitSetBool:
                self.sellLogic(emaTracker, connection, currentSelectedCryptoPrice, mainConfig)

        # Checks for Buy stuff
        elif not holdingBool:
            if not limitSetBool:
                self.buyLogic(emaTracker, connection, currentSelectedCryptoPrice, mainConfig)
示例#31
0
 def __init__(self):
     self.parser = JsonParser()
     self.database = CryptoDatabase()
示例#32
0
    def test_main(self):
        file_path = "output1.json"
        a1 = JsonParser()
        a2 = JsonParser()
        a3 = JsonParser()

        # test_json_str、test_dict
        a1.load(JSON)
        d1 = a1.dumpDict()
        # 粗糙比较test_dict和d1

        a2.loadDict(d1)
        a2.dumpJson(file_path)
        a3.loadJson(file_path)
        d3 = a3.dumpDict()
        # 比较d1和d3是否完全一样
        self.assertEqual(d1, d3)
 def __init__(self):
   self.parser = JsonParser()
   self.rule_checker = RuleChecker()
示例#34
0
    def test_basic(self):
        a1 = JsonParser()
        a2 = JsonParser()
        a3 = JsonParser()

        a1.load(test_json_str)
        d1 = a1.dumpDict()

        a2.loadDict(d1)
        a2.dumpJson('jsonfile.txt')

        a3.loadJson('jsonfile.txt')
        d3 = a3.dumpDict()
        self.assertEqual(d1, d3)
示例#35
0
def check(s, d):
    ''' check basic operation of JsonParser'''

    # load and dump
    jp = JsonParser()
    jp.load(s)
    assert_eq(jp.dumpDict(), d)
    assert_eq(jp.dump(), s)

    # load and dump by another JsonParser
    jp2 = JsonParser()
    jp2.load(jp.dump())
    assert_eq(jp2.dumpDict(), jp.dumpDict())
    assert_eq(jp2.dump(), jp.dump())

    # check update
    jp3 = JsonParser()
    jp3.update(jp.dumpDict())
    assert_eq(jp3.dumpDict(), jp.dumpDict())
    assert_eq(jp3.dump(), jp.dump())

    # check file operation
    f = 'temp_for_test'
    jp.dumpJson(f)
    jp4 = JsonParser()
    jp4.loadJson(f)
    os.remove(f)
    assert_eq(jp4.dumpDict(), jp.dumpDict())
    assert_eq(jp4.dump(), jp.dump())
示例#36
0
 def is_meet_group_expr(self, group):
     for key in group:
         value = group[key]
         data = JsonParser().process_dict(key, self.dict_data)
         return self.process_dict(data, value) if isinstance(
             data, dict) else self.process_list(data, value)
示例#37
0
 def setUp(self):
     self.jp = JsonParser()
示例#38
0
    ('{"a":[1,2,3]}', "a", [1, 2, 3]),  #数组
    ('{"a":[1,2,"aaa"]}', "a", [1, 2, "aaa"]),  #数组
    ('{"a": "a\\\\"}', "a", "a\\"),  #反斜杠
    ('{"d{": "}dd"}', "d{", "}dd"),  # {}
    ('{"d,": ",dd"}', "d,", ",dd"),  # ,
    ('{"d\\\"": "\\\"dd"}', "d\"", "\"dd"),  # "
    ('{"a": {"a": {"a": 123}}}', "a", {"a": {"a": 123}}),  #嵌套
    ('{"a": {"a": {"a": 123, "b": [1,2,3]}}}', "a", {"a": {"a": 123, "b": [1, 2, 3]}}),  #嵌套
    ("""
{ "ab{" : "}123" }
""", "ab{", "}123"),  #复杂类型
]

s = '{"a": {"a": {"a": 123, "b": [1,2,3]}}}'



import json
a = JsonParser()

a.load(s)

for item in jsons:
    json.dumps(item[0])
    print item[0]
    a.load(item[0])
    assert a.dict.keys()[0] == item[1]
    print "k", item,
    assert a.dict[item[1]] == item[2]
    print "v"
示例#39
0
class JsonParserTest(unittest.TestCase):
    def setUp(self):
        self.jp = JsonParser()
        self.maxDiff = None

    def test_main(self):
        file_path = "output1.json"
        a1 = JsonParser()
        a2 = JsonParser()
        a3 = JsonParser()

        # test_json_str、test_dict
        a1.load(JSON)
        d1 = a1.dumpDict()
        # 粗糙比较test_dict和d1

        a2.loadDict(d1)
        a2.dumpJson(file_path)
        a3.loadJson(file_path)
        d3 = a3.dumpDict()
        # 比较d1和d3是否完全一样
        self.assertEqual(d1, d3)

    def test_load(self):
        slist = [r'''{}''',
                 r'''{"abc":123}''',
                 r'''{"abc":{"abc":{"abc":123}}}''',
                 r'''{"abc":{"abc":{"abc":[123,234,567,null,false,true,[]]}}}''']
        for s in slist:
            self.jp.load(s)
            self.assertEqual(self.jp.dictcontent, json.loads(s))

    def test_dump(self):
        slist = [r'''{}''',
                 r'''{"abc":123}''',
                 r'''{"abc":{"abc":{"abc":123}}}''',
                 r'''{"abc":{"abc":{"abc":[123,234,567,null,false,true,[]]}}}''']
        for s in slist:
            self.jp.load(s)
            self.assertEqual(self.jp.dump(), s)

    def test_loadJson(self):
        self.jp.loadJson("JSON.txt")
        with open("JSON.txt") as f:
            content = f.read()
        self.assertEqual(self.jp.dictcontent, json.loads(content))  # 比较使用标准库和JsonParser加载相同字符串结果是否相同

    def test_dumpJson(self):
        output = "output2.json"
        self.jp.load(JSON)
        self.jp.dumpJson(output)
        first = copy.deepcopy(self.jp.dictcontent)  # 创建一个原字典的拷贝
        with open(output) as f:
            content = f.read()
        self.jp.load(content)
        self.assertEqual(first, self.jp.dictcontent)

    def test_loadDict(self):
        d1 = {"abc": 123, 123: "abc", False: "test", None: 123}
        e1 = {"abc": 123}
        self.jp.loadDict(d1)
        self.assertEqual(e1, self.jp.dictcontent)

    def test_dumpDict(self):
        d1 = r'''{"abc": 123, "bcd": false, "cde": null}'''
        self.jp.load(d1)
        # dumpDict返回的字典跟原字典具有相同的键值,但是不是同一个对象
        self.assertEqual(self.jp.dictcontent, self.jp.dumpDict())
        self.assertFalse(self.jp.dictcontent is self.jp.dumpDict())

    def test_getitem(self):
        d = {"abc": "cde", "cde": "abc"}
        self.jp.loadDict(d)
        key = "abc"
        value = "cde"
        self.assertEqual(value, self.jp[key])

    def test_setitem(self):
        d = {"abc": "cde", "cde": "abc"}
        self.jp.loadDict(d)
        key = "abc"
        expected = "abcdefg"
        self.jp[key] = expected
        self.assertEqual(expected, self.jp[key])

    def test_update(self):
        d = {"abc": "cde", "cde": "abc"}
        d1 = {"abc": "abc", "cde": "cde"}
        self.jp.loadDict(d)
        self.jp.update(d1)
        self.assertEqual("abc", self.jp["abc"])
        self.assertEqual("cde", self.jp["cde"])

    def test_deepdump(self):
        d0 = {"a": 123}
        d1 = {"b": d0}
        d2 = {"c": [d1]}
        d3 = self.jp.deepdump(d2)  # 深拷贝对象
        d3['c'][0]['b']['a'] = 234  # 修改拷贝后嵌套对象中的值
        self.assertEqual(d2['c'][0]['b']['a'], 123)  # 断言原本对象的值未改变

    def test_getnumber(self):
        s1 = r'-0.123'
        e1 = -0.123
        s2 = r'0.123456789E1'
        e2 = 1.23456789
        s3 = r'1231235234234234'
        e3 = 1231235234234234L
        s4 = r'-0'
        e4 = 0
        s5 = r'-0.0e+1'
        e5 = -0.0
        self.assertEqual(self.jp.getnumber(s1)[0], e1)
        self.assertEqual(self.jp.getnumber(s2)[0], e2)
        self.assertEqual(self.jp.getnumber(s3)[0], e3)
        self.assertEqual(self.jp.getnumber(s4)[0], e4)
        self.assertEqual(self.jp.getnumber(s5)[0], e5)

    def test_getchar(self):
        c = r'\ude1c'
        expected = unichr(int('de1c', 16))
        result, index = self.jp.getchar(c, 2)
        self.assertEqual(expected, result)

    def test_getstring(self):
        s0 = '"very simple"'
        e0 = 'very simple'
        s1 = r'''"`1~!@#$%^&*()_+-={':[,]}|;.</>?"'''
        e1 = r'''`1~!@#$%^&*()_+-={':[,]}|;.</>?'''
        self.assertEqual(e0, self.jp.getstring(s0[1:])[0])
        self.assertEqual(e1, self.jp.getstring(s1[1:])[0])

    def test_getarray(self):
        liststr = r'''{"key":[{"integer": 1234567890,
        "real": -9876.543210,
        "e": 0.123456789e-12,
        "E": 1.234567890E+34,
        "":  23456789012E6,
        "zero": 0,
        "one": 1,
        "space": " ",
        "quote": "\"",
        "backslash": "\\",
        "unicode":"\uedda",
        "controls": "\b\f\n\r\t"}]}'''
        self.jp.load(liststr)
        expected = json.loads(liststr)
        self.assertEqual(0, cmp(expected, self.jp.dictcontent))

    def test_getobject(self):
        self.jp.load(JSON)
        expected = json.loads(JSON)
        self.assertEqual(0, cmp(expected, self.jp.dictcontent))

    def test_final(self):
        for tub in finaljson:
            self.jp.load(tub[0])
            assert self.jp.dictcontent[tub[1]] == tub[2]
            print tub[1], tub[2]
示例#40
0
        "array":[  ],
        "object":{  },
        "address": "50 St. James Street",
        "url": "http://www.JSON.org/",
        "comment": "// /* <!-- --",
        "# -- --> */": " ",
        " s p a c e d " :[1,2 , 3

,

4 , 5        ,          6           ,7        ],
        "compact": [1,2,3,4,5,6,7],
        "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
        "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
: "A key can be any string"
    },
    0.5 ,98.6
,
99.44
,

1066


,"rosebud"]}
'''
    paser = JsonParser()
    paser.load(testdata)
    d = paser.dumpDict()
    print d
    pass
 def __init__(self):
     self.parser = JsonParser()
示例#42
0
class TestCases(unittest.TestCase):
    def setUp(self):
        self.jp = JsonParser()

    def test_basic(self):
        a1 = JsonParser()
        a2 = JsonParser()
        a3 = JsonParser()

        a1.load(test_json_str)
        d1 = a1.dumpDict()

        a2.loadDict(d1)
        a2.dumpJson('jsonfile.txt')

        a3.loadJson('jsonfile.txt')
        d3 = a3.dumpDict()
        self.assertEqual(d1, d3)

    def test_load(self):
        self.jp.load(test_json_str)
        self.assertEqual(self.jp.dict, json.loads(test_json_str))

    def test_dump(self):
        self.assertEqual(self.jp.dump(), json.dumps(self.jp.dict))

    def test_loadJson(self):
        f = 'jsonfile.txt'
        self.jp.loadJson(f)
        with open(f, 'r+') as fb:
            self.assertEqual(self.jp.dict, json.load(fb))

    def test_dumpJson(self):
        f = 'jsonfile1.txt'
        f2 = 'jsonfile2.txt'
        self.jp.load(test_json_str)
        self.jp.dumpJson(f)
        with open(f2, 'w+') as fb:
            json.dump(self.jp.dict, fb)
        self.assertEqual(True, filecmp.cmp(f, f2))

    def test_loadDict(self):
        d1 = {'a': 1, 'b': ['c', 2, 3], 'd':  {'e': True}}
        d2 = {'a': 1, False: 2, 3: 'd'}
        self.jp.loadDict(d1)
        self.assertEqual(d1, self.jp.dict)
        self.assertFalse(d1 is self.jp.dict)
        self.jp.loadDict(d2)
        for key in self.jp.dict.keys():
            self.assertEqual(True, isinstance(key, str))

    def test_dumpDict(self):
        d = self.jp.dumpDict()
        self.assertEqual(d, self.jp.dict)
        self.assertFalse(d is self.jp.dict)

    def test_getitem(self):
        d = {'test': 'getitem'}
        self.jp.loadDict(d)
        self.assertEqual(d['test'], self.jp['test'])

    def test_setitem(self):
        self.jp['test'] = 'getitem'
        dic = self.jp.dumpDict()
        self.assertEqual(dic['test'], 'getitem')

    def test_update(self):
        d1 = {'a': 1, 'b': 2}
        d2 = {'b': 3, 'c': 4}
        self.jp.loadDict(d1)
        self.assertEqual(self.jp.update(d2), d1.update(d2))
示例#43
0
'''
Created on Mar 2, 2013

@author: zhumeiqi
'''
from JsonParser import JsonParser,JsonError
if __name__ == '__main__':
    paser = JsonParser()
    paser2 = JsonParser()
    paser3 = JsonParser()
    paser4 = JsonParser()
    paser.loadJson('test.json')
    d1 = paser.dumpDict()
    paser2.loadDict(d1) 
    paser2.dumpJson('test_r.json')
    paser3.loadJson('test_r.json')
    d3 = paser3.dumpDict()
    print paser.dump()
    print d1
    print d3
   
    pass
示例#44
0
文件: test.py 项目: fanwlexca/netease
		if isinstance(l1[i], list):
			if not comparel(l1[i], l2[i]):
				print 'dict:%s not equal to %s' % (l1[i], l2[i])
				return False
		elif isinstance(l1[i], dict):
			if not compared(l1[i], l2[i]):
				print 'list:%s not equal to %s' % (l1[i], l2[i])
				return False
		else:
			if l1[i] != l2[i]:
				print 'element:%s not equal to %s' % (l1[i], l2[i])
				return False
	return result

if __name__ == '__main__':
	a1 = JsonParser()
	a2 = JsonParser()
	a3 = JsonParser()
	a1.loadJson('./test')
	d1 = a1.dumpDict()
	print 'd1:', d1 
	a2.loadDict(d1)
	a2.dumpJson('./test1')
	a3.loadJson('./test1')
	d3 = a3.dumpDict()
	print 'd3:', d3
	if compared(d1, d3):
		print 'All is OK!'

	a1[u'root'][8][u'integer'] = 9876543210
	print a1[u'root'][8][u'integer']
示例#45
0
	},
	0.5 ,98.6
	,
	99.44
	,

	1066


	,"rosebud"]
}'''


test_dict={u'root': [u'JSON Test Pattern pass1', {u'object with 1 member': [u'array with 1 element']}, {}, [], -42, True, False, None, {u'comment': u'// /* <!-- --', u'false': False, u'chinese': u'\u4e2d\u6587', u'backslash': u'\\', u'one': 1, u'quotes': u'&#34; " %22 0x22 034 &#x22;', u'zero': 0, u'alpha': u'abcdefghijklmnopqrstuvwyz', u'array': [], u'# -- --> */': u' ', u'special': u"`1~!@#$%^&*()_+-={':[,]}|;.</>?", u'compact': [1, 2, 3, 4, 5, 6, 7], u'null': None, u'space': u' ', u'hex': u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', u'controls': u'\x08\x0c\n\r\t', u'slash': u'/ & /', u'real': -9876.54321, u'digit': u'0123456789', u'E': 1.23456789e+34, u'quote': u'"', u'object': {}, u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?': u'A key can be any string', u'address': u'50 St. James Street', u'integer': 1234567890, u'true': True, u'e': 1.23456789e-13, u'url': u'http://www.JSON.org/', u'jsontext': u'{"object with 1 member":["array with 1 element"]}', u' s p a c e d ': [1, 2, 3, 4, 5, 6, 7], u'ALPHA': u'ABCDEFGHIJKLMNOPQRSTUVWYZ'}, 0.5, 98.6, 99.44, 1066, u'rosebud']}
file_path="data.txt"
a1 = JsonParser()
a2 = JsonParser()
a3 = JsonParser()

a1.load(test_json_str)
print 'a1.dump():\n',a1.dump()
d1=a1.dumpDict()
print 'd1:\n',d1

print 'test_dict:\n',test_dict
assert test_dict==d1

a2.loadDict(d1)
assert id(a2["root"])!=id(d1["root"])

a2.dumpJson(file_path)
示例#46
0
def test_back_slash_forward_slash():
    # test '\/', support load '\/', but only write back '/'(according to simplejson)
    jp = JsonParser()
    jp.load('{"\\/":""}')
    assert_eq(jp.dump(), '{"/":""}')
    assert_eq(jp.dumpDict(), {'/':''})