コード例 #1
0
def publish_from_post(post, channel_id):
    pub = Publishing()
    pub.post_id = post.id
    pub.user_id = post.user_id
    pub.title = post.title
    pub.description = post.description
    pub.date_from = post.date_from
    pub.date_until = post.date_until
    pub.state = 0
    pub.channel_id = channel_id
    return pub
コード例 #2
0
ファイル: test_wiki.py プロジェクト: AdriLezaack/SuperForm
def test_uncorrect_config():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'descr'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Wiki'
    bad_json = json.dumps({"hello": ["coucou"]})

    answer = wiki.run(pub, bad_json)
    assert answer[0].value == StatusCode.ERROR.value
    assert answer[
        1] == "Error when getting the configuration"  # should not be "Couldn't connect to server"
コード例 #3
0
def test_run_PDF():
    pub = Publishing()
    pub.title = 'test-Title'
    pub.description = "Very long test : Le mot « wiki » signifie, en hawaïen, rapide2, vite3 ou informel4. Il a été choisi par Ward Cunningham lorsqu'il créa le premier wiki, qu'il appela WikiWikiWeb. Il utilisa l'expression « wiki wiki », un redoublement qui signifie « très rapide », « très vite »5, car c'est le premier terme hawaïen qu'il apprit lorsqu'il dut prendre un bus à la sortie de l'aéroport, et qu'à la création de son site, il voulait un terme amusant pour dire rapide. Dans l'URL du site, apparaissait uniquement le terme « wiki », ce qui a probablement poussé les visiteurs à l'appeler ainsi5. Pour l'OQLF le terme « wiki » est donc un nom commun qui s'accorde au pluriel6. Le journal The Economist fait remarquer que le mot wiki peut être lu comme l'acronyme de « What I Know Is » (littéralement : « ce que je sais est » ou « voici ce que je sais »)7. Le concours de création littéraire et artistique Dis-moi dix mots a sélectionné le mot « wiki » pour son édition de 2014-20158 et en donne une définition."
    config_channel = json.dumps({'Logo': "UCL", 'Format': "A4"})
    run_result = pdf.run(pub, config_channel, True)
    assert (run_result[0].value == StatusCode.OK.value)  # pdf was generated
    fileName = run_result[1]
    fileSize = run_result[2]
    fileNameWithoutDot = fileName[:-4]
    fileNameWithoutDotWithoutFormatWithoutLogo = fileNameWithoutDot[
        fileNameWithoutDot.find("-") + 4:]
    assert (fileNameWithoutDotWithoutFormatWithoutLogo.isalnum()
            )  # pdf name contains no special char
    assert (fileName.startswith("UCL-A4"))  # it used UCL logo and A4 format
    assert (fileSize > 0)  # verify that the pdf size is bigger than 0
コード例 #4
0
ファイル: test_gcal.py プロジェクト: AdriLezaack/SuperForm
def basic_publish(title=None, delta=timedelta(hours=1)):
    pub = Publishing()
    pub.title = title if title else ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
    pub.description = 'This is a test !'
    pub.date_from = datetime.now() + timedelta(days=1)
    pub.date_until = pub.date_from + delta
    pub.state = 0
    pub.channel_id = 'gcal'
    return pub
コード例 #5
0
def test_run_with_empty_tweet():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = ''
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Twitter'

    configdata = {"consumer_key": ["kTB8ji6trOpAXoQQBMgRwOUoz"],
                  "consumer_secret": ["oJpKcyObcM6sakaStGsIJ0XnQceebPOrC5CcpJeD54jou1XAEm"],
                  "access_token_key": ["1052553285343858688-2KPjU0CKB5Y6HxR3G5FVUnC8bxZDTJ"],
                  "access_token_secret": ["Sd8Se0oRuffyBwyRBmkgyJlaFVeE8HqQPcQm5rx08S9dx"]}
    config = json.dumps(configdata)
    code = twitter.run(pub, config)
    assert code[0].value == StatusCode.ERROR.value
    assert code[1] == "Empty tweet"
コード例 #6
0
def test_run_uncorrect_credentials_JSON():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'something something'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Twitter'

    configdata = {"csumer_key": ["coucou"],
                  "consumer_seet": ["thisisfalse"],
                  "accesken_key": ["blabla"],
                  "acc_token_secret": ["beuh"]}
    config = json.dumps(configdata)
    code = twitter.run(pub, config)
    assert code[0].value == StatusCode.ERROR.value
    assert code[1] == "Uncorrect credentials, please review your configuration"
コード例 #7
0
def test_uncorrect_config():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'descr'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Wiki'
    bad_json = json.dumps({"hello": ["coucou"]})
    try:
        answer = wiki.run(pub, bad_json)
        assert answer == "error json decoder"
    except BaseException as e:
        #print(type(e))
        #print(e)
        # This could be a connection error, you need a live server to run this test successfully
        raise (e)
コード例 #8
0
def test_wiki_post(client, testserver):
    login(client, 'myself')

    pub = Publishing(title="test wiki", description="This is a test description feed", link_url="www.facebook.com",
                     channel_id=1, post_id=1)

    conf = "{\"username\": \"myself\", \"password\": \"myself\", \"base_url\": \"" + testserver.url + "\"}"

    status_code, _, _ = wiki.run(pub, conf)

    assert status_code == StatusCode.OK
コード例 #9
0
def test_run_false_credentials():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'something something'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Twitter'

    configdata = {
        "consumer_key": ["coucou"],
        "consumer_secret": ["thisisfalse"],
        "access_token_key": ["blabla"],
        "access_token_secret": ["beuh"]
    }
    config = json.dumps(configdata)
    result = twitter.run(pub, config)
    assert result == "uncorrect credentials"
コード例 #10
0
def test_wiki_server_down(client):
    login(client, "myself")

    pub = Publishing(title="test wiki", description="This is a test description feed", link_url="www.facebook.com",
                     channel_id=1, post_id=1)

    conf = "{\"username\": \"myself\", \"password\": \"bad\", \"base_url\": \"http://server.down\"}"

    status_code, error_message, _ = wiki.run(pub, conf)

    assert status_code == StatusCode.ERROR
    assert error_message == "Couldn't connect to server"
コード例 #11
0
def test_wiki_bad_base_url(client):
    login(client, "myself")

    pub = Publishing(title="test wiki", description="This is a test description feed", link_url="www.facebook.com",
                     channel_id=1, post_id=1)

    conf = "{\"username\": \"myself\", \"password\": \"bad\", \"base_url\": \"server.down\"}"

    status_code, error_message, _ = wiki.run(pub, conf)

    assert status_code == StatusCode.ERROR
    assert error_message == "Wrong base_url, please check the format again"
コード例 #12
0
def test_correct_wiki_post():
    config = {'username': ['superform'], 'password': ['superform']}
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'descr'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Wiki'

    config_str = json.dumps(config)

    try:
        answer = wiki.run(pub, config_str)
        assert answer.status_code == 200
    except BaseException as e:
        #print(type(e))
        #print(e)
        # This could be a connection error, you need a live server to run this test successfully
        raise (e)
コード例 #13
0
def test_send_tweet_correct_tweet():
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.link_url = ' : test string'
    rabdomStr = randomword(12)
    pub.description = "<tweet-separator>" + rabdomStr + "</tweet-separator> "
    pub.image_url = ""
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Twitter'

    configdata = {'consumer_key': 'kTB8ji6trOpAXoQQBMgRwOUoz',
                  'consumer_secret': 'oJpKcyObcM6sakaStGsIJ0XnQceebPOrC5CcpJeD54jou1XAEm',
                  'access_token_key': '1052553285343858688-2KPjU0CKB5Y6HxR3G5FVUnC8bxZDTJ',
                  'access_token_secret': 'Sd8Se0oRuffyBwyRBmkgyJlaFVeE8HqQPcQm5rx08S9dx'}
    config = json.dumps(configdata)

    code = twitter.run(pub, config)
    assert code[0].value == StatusCode.OK.value
コード例 #14
0
ファイル: test_wiki.py プロジェクト: AdriLezaack/SuperForm
def test_correct_wiki_post():
    # verify that the server is on
    try:
        response = requests.post(wiki.urlwiki, None)
    except requests.exceptions.ConnectionError:
        assert False, "Can't connect to the pmwiki server."
    assert response.status_code == 200

    config = {'username': ['superform'], 'password': ['superform']}
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'descr'
    pub.image_url = 'imague url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 'Wiki'

    config_str = json.dumps(config)

    answer = wiki.run(pub, config_str)
    assert answer[0].value == StatusCode.OK.value
    assert answer[1].status_code == 200
コード例 #15
0
def test_send_tweet_bad_config(client):
    name = "unittest_twitter"
    module = "superform.plugins.twitter"
    P = Publishing(post_id=0,channel_id=name,state=0,title='test',description='unit test')
    C = Channel(name=name, module=module, config="{}")
    db.session.add(C)
    db.session.add(P)
    db.session.commit()
    pub = db.session.query(Publishing).filter(Publishing.post_id == 0, Publishing.channel_id == name).first()
    c = db.session.query(Channel).filter(Channel.name == pub.channel_id).first()
    temp_stdout = StringIO()
    with contextlib.redirect_stdout(temp_stdout):
        twitter.run(pub,c.config)
    output = temp_stdout.getvalue().strip()
    db.session.query(Publishing).filter(Publishing.post_id == 0).delete()
    db.session.query(Channel).filter(Channel.name == name).delete()
    db.session.commit()
    assert 'Missing' in output
コード例 #16
0
def test_publish_base():
    """
        Trying publishing to an existing RSS Feed
    :return:
    """
    json_data = {}
    rname = "Test Publishing"
    json_data['Feed title'] = rname
    rdescription = "Used for trying to publish a new post"
    json_data['Feed description'] = rdescription
    link = None
    origin = None

    title = "Test title"
    body = "I don't know what to write"

    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'a link'
    determinants = ["une", "un", "le", "la", "les", "vos", "nos", "mes", "tes"]
    nomCommuns = [
        "chien", "chat", "vache", "cheval", "poney", "cochon", "poule", "coq"
    ]
    verbes = [
        "aller", "venir", "courir", "voler", "manger", "mourir", "partir",
        "skier"
    ]
    lieux = [
        "campagne", "montagne", "aeroport", "ecole", "mer", "jardin",
        "toilette"
    ]
    testDeterminant = determinants[random.randint(0, 8)]
    testNomCmmun = nomCommuns[random.randint(0, 7)]
    testVerbe = verbes[random.randint(0, 7)]
    testLieu = lieux[random.randint(0, 6)]
    pub.description = " " + testDeterminant + " " + testNomCmmun + " " + testVerbe + " " + testLieu + " " + str(
        random.randint(0, 10000))
    pub.image_url = 'image url'
    pub.date_until = '14.02.19'
    pub.state = 1
    c = db.session.query(Channel).filter(Channel.module == "rss").first()

    if c is None:
        print("No Rss Channel found")
        return
    pub.channel_id = c.channel_id
    plugin_name = c.module
    c_conf = c.config
    channel_config = None

    rss.run(pub, channel_config)

    localPath = os.path.dirname(__file__) + "/rss/feed_" + str(
        pub.channel_id) + ".xml"
    items = rss.import_items(localPath)
    found_wanted_feed = False

    for item in items:
        if item.description == rdescription and item.title == rname.replace(
                " ", "_"):
            found_wanted_feed = True
            print("The new field was well created")
            return
    assert found_wanted_feed, "The new rss publishign failled"
コード例 #17
0
def test_run_linkedin():
    """
    Checks if a simple linkedin post can be created (require a testchannel in the DB)
    Since it was not possible to directly call the LinkedIn.run methode from here (using requests and dynamic url).
    We basically code again the LinkedIn.run methode in a more "harcoded" way but it's
    exactly the same as the LinkedIn.run method
    """
    pub = Publishing()
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'a link'
    determinants = ["une", "un", "le", "la", "les", "vos", "nos", "mes", "tes"]
    nomCommuns = [
        "chien", "chat", "vache", "cheval", "poney", "cochon", "poule", "coq"
    ]
    verbes = [
        "aller", "venir", "courir", "voler", "manger", "mourir", "partir",
        "skier"
    ]
    lieux = [
        "campagne", "montagne", "aeroport", "ecole", "mer", "jardin",
        "toilette"
    ]
    testDeterminant = determinants[random.randint(0, 8)]
    testNomCmmun = nomCommuns[random.randint(0, 7)]
    testVerbe = verbes[random.randint(0, 7)]
    testLieu = lieux[random.randint(0, 6)]
    pub.description = " " + testDeterminant + " " + testNomCmmun + " " + testVerbe + " " + testLieu + " " + str(
        random.randint(0, 10000))
    pub.image_url = 'image url'
    pub.date_until = '14.02.19'
    pub.state = 1
    print("The  LinkedIn posting test has started...")
    linkedIn_Channel = db.session.query(Channel).filter(
        Channel.name == "TestLinkedInDoNotDelete").first()
    if (linkedIn_Channel is None):
        assert (
            False
        ), "LinkedIn test_run requires the DB to have a testChannel named TestLinkedInDoNotDelete"
    else:
        channel_config = linkedIn_Channel.config
        pub.channel_id = linkedIn_Channel.id
        json_data = json.loads(channel_config)
        access_token = json_data['token']
        title = pub.title
        body = pub.description
        link = pub.link_url

        comment = title + "\n" + body + "\n" + link
        import collections
        AccessToken = collections.namedtuple('AccessToken',
                                             ['access_token', 'expires_in'])

        try:
            client_id = LinkedIn.get_client_id()
        except FileNotFoundError:
            client_id = None
            assert (False), "bad configuration, requires a linkedin.ini file "
        try:
            client_secret = LinkedIn.get_client_secret()
        except FileNotFoundError:
            client_secret = None
            assert (False), "bad configuration, requires a linkedin.ini file "

        return_url = url_root + "/channels"
        authentication = linkedin.LinkedInAuthentication(
            client_id, client_secret, return_url,
            linkedin.PERMISSIONS.enums.values())

        assert (authentication
                is not None), "LinkedIn.LinkedInAuthentification failed"
        authentication.token = AccessToken(access_token, "99999999")
        application = linkedin.LinkedInApplication(authentication)
        status = ""
        try:
            resp = application.submit_share(comment,
                                            title,
                                            description=None,
                                            submitted_url=None,
                                            submitted_image_url=None,
                                            visibility_code='anyone')
            status = "Success publishing"
        except Exception as e:
            print(e)
            status = "Error publishing. The testChannel (named TestLinkedInDoNotDelete) may be banned for spamming)" \
                     + "\n" +"if so, go to the channel config and relink it to a non-valuable linkedIn account"

        assert status == "Success publishing", "Couldn't post on LinkedIn"
コード例 #18
0
def test_makeText():
    pub = Publishing()
    pub.user_id = "Superform"
    pub.post_id = "1"
    pub.date_from = '13.02.02'
    pub.title = 'test-Title'
    pub.link_url = 'blablablablablablablajdsfvjdbvjdnfvqebdnbqdfnvsdùnvbmqknkfnbùsfvdf'
    pub.description = 'descr'
    pub.image_url = 'image url'
    pub.date_until = '14.02.16'
    pub.state = 1
    pub.channel_id = 8

    text = wiki.makeText(pub, pub.user_id)
    tab_of_text = text.splitlines()
    date = str(datetime.datetime.now().strftime("%d/%m/%Y"))

    assert tab_of_text[0] == "!! " + pub.title
    assert tab_of_text[1] == "Par " + "Superform" + " Publié le " + date
    assert tab_of_text[2] == ""
    assert tab_of_text[
        3] == "-----"  #+str(pub.description).replace("\n","[[<<]]")
    assert tab_of_text[4] == str(pub.description).replace("\n", "[[<<]]")
    assert tab_of_text[5] == ""
    assert tab_of_text[6] == "-----" + "[[" + pub.link_url + "]]"
    assert tab_of_text[7] == "-----"
    assert tab_of_text[8] == pub.image_url